Preprocess views view to concat two dates and add variable

hook_preprocess_views_view() is used to alter the variables that are passed to a views-view[...].html.twig template file which is for the entire View, not just for the fields. It might make more sense for you to use hook_preprocess_views_view_fields() or hook_preprocess_views_view_field() since you are trying to alter the variables that are used in a views-view-field[...].html.twig template file (specific to the individual field, not the whole view).

See:

https://api.drupal.org/api/views/theme%21theme.inc/function/template_preprocess_views_view_fields/7.x-3.x

https://api.drupal.org/api/views/theme%21theme.inc/function/template_preprocess_views_view_field/7.x-3.x


How do I send webform submission data to a google sheet?

Right now the only available solution is to use Zapier.

Ivan Zugec did a great screencast showing How to Create Forms using Webform and Contact in Drupal 8 and includes a demo showing how to push webform submissions into a Google Sheet using Zapier.

Hopefully, someone will port the Webform to Google Docs module from D7 to D8.


source code shows proper img tag from $row output, but no actual image in browser

Ok creds to clive. See syntax error in comments.

For those who need the actual code in the answer:
<img scr should be <img src :)


How to load an OpenLayers view into the content area with an AJAX link?

NOTE FROM THE QUESTION'S AUTHOR:
This solution works for non OpenLayers views. It fails to build up the wrapper when the view is an OpenLayers though.

So the question remains to be answered.

You have to create a div wrapper where you are supposed to show the
ajaxified view content. You have to add the div wrapper in the
template file (MYTEMPLATE.tpl.php)
Create a module that will register the ajax link in hook_menu().
In the callback of the menu item you have to render the view content
using ajax_commands.

Sample code:

function MYMODULE_init() {
  // Add the Drupal AJAX library.
  // You can optionally provide a check to add AJAX library only on certain pages.
  drupal_add_library('system', 'drupal.ajax');
}

function MYMODULE_menu() {
  $items = array();

  $items['ajax-link/nojs'] = array(
    'title' => 'TITLE',
    'description' => 'DESCRIPTION',
    'page callback' => 'MYMODULE_ajax_link_callback',
    'page arguments' => array(1),
    'access callback' => PERMISSION,
    'type' => MENU_CALLBACK,
  );

  $items['ajax-link/ajax'] = array(
    'delivery callback' => 'ajax_deliver',
  ) + $items['ajax-link/nojs'];
}

function MYMODULE_ajax_link_callback($ajax) {
  // Check whether this is AJAX callback.
  $is_ajax = $ajax === 'ajax';

  if ($is_ajax) {
    // Your code to obtain view content in HTML format and store it in some variable say $ajax_content.

    $commands = array();

    $commands[] = ajax_command_replace('div.WRAPPER-YOU-ADDED-PREVIOUSLY', $ajax_content);

    return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );

  }
  else {
    drupal_set_message('Content added');
    drupal_goto();
  }
}


How can I add a CC field to webform email send?

I have done some similar thing to send the email to another email-address. You can use the following solution for changing the content of the email or to add an attachment or things like this...

/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {
  // Check message id
  if ($message['id'] == '...') {
    $email_key = 'new_email_key_if_you_want';

    // Block email which is sending right now.
    $message['send'] = FALSE;

    // send original email
    drupal_mail('MYMODULE', $email_key, $message['to'], language_default(), $message['params'], $message['from']);

    // send copy of the email.
    drupal_mail('MYMODULE', $email_key, 'ticket_system@domain.com', language_default(), $message['params'], $message['from']);
  }
}

You can add this in an own module, in the MYMODULE.module.


It looks like that module is in the very early stages of development and is not widely deployed.

There is an abandon dokeos module as well, but I think that you may be out of luck with this particular feature?


Which is the leading facebook module for Drupal 7 a complete site integration?

You need FB. It offers all what you need.

I've been in the same dilemma and went with that one.

I suggest to try all of them and see for yourself though. Don't waste time with modules which offer third party integration - they rely on registration on those websites and usually paying a fee to them. I think it's silly registering and paying for a third party service in order to use another (free) third party service.


Is there an alternative private messsage module that integrates with Views?

You can also consider theming Private Message.  Private Message is an extremely powerful module that offers a much higher degree of customization than some sites may need (messages can be sent to users + roles at the same time, etc.)

For my site, I added several tweaks to actually limit/reduce Private Message's functionality (users can only have one thread per user, users can only message one user at a time, users cannot send more than three messages in a row to the same user, etc.)

Messaging systems are pretty complex so I found it easier to start with the huge number of options Private Message provides and then reduce them.

You could also help work on privatemsg views integration, though this is a huge project.


Drupal 7 Form API file field - not recognizing the imported file

I tried #file_managed instead of the file, and then I am able to upload the files into the application. But, this option stores the file in managed_file table in the database with a temporary storage.
The file details are not visible in the dsm() (devel module).


How to remove the global library from specific page??

You need to implement hook_page_attachments_alter().


How do I change theme for tables rendered with theme_table()?

I think that what you need is just to change the CSS styles used for the table, as Clive suggested. That would not change the output produced from theme('table'), but it would change how that output is rendered.

If you really want to change the output, because you want to add HTML tags to what normally output for the tables, you need to override the theme function. If THEMENAME is your theme's name, then you need to write the THEMENAME_table() function in the template.php file for your theme. you can look at the code of theme_table() as example of which code to write. Normally you want to add output, or slightly change the output, and in that case you use most of the code already used in theme_table().

In Drupal 7 there is another alternative, which is possible if what you want to do is alter the value of the variables passed to the theme function: Each theme function, even the ones not using a template, have a preprocess function. In this case, the variables used from the theme function are the following ones:

$variables['header']
$variables['rows']
$variables['attributes']
$variables['caption']
$variables['colgroups']
$variables['sticky']
$variables['empty']

Writing code in a function called THEMENAME_preprocess_table() (with $variables as parameter), you can alter the value of those variables before they are passed to the theme function.

  How can I change template for tables?

For the table theme function, there aren't template files involved; it is possible to use a template file in this case too, but you should write more code to gain few. I can report how to do this, but I would not suggest doing it.

  How do I use that theme for my tables?

You just call the theme function with theme('table', $variables), where $variables is an array containing the values required from the theme function, which are:

header: An array containing the table headers. Each element of the array can be either a localized string or an associative array with the following keys:

"data": The localized title of the table column.
"field": The database field represented in the table column (required if user is to be able to sort on this column).
"sort": A default sort order for this column ("asc" or "desc").
Any HTML attributes, such as "colspan", to apply to the column header cell.

rows: An array of table rows. Every row is an array of cells, or an associative array with the following keys:

"data": an array of cells
Any HTML attributes, such as "class", to apply to the table row.
"no_striping": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.

Each cell can be either a string or an associative array with the following keys:

"data": The string to display in the table cell.
"header": Indicates this cell is a header.
Any HTML attributes, such as "colspan", to apply to the table cell.


Installing/Enabling Custom Webform Hander

A few things in addition to what @4k4 commented:

Please replace your annotation plugin reference with @WebformHandler

Use lower case / snake case names for your Webform Handler ID eg. redirect_to_ccbilling

Ensure correct directory structure where the plugin discovery will look for Webform Handler classes. This should be /modules/custom/redirect_to_ccbilling/src/Plugin/WebformHandler/RedirectToCCBillingWebformHandler.php

Ensure that your module is enabled. Either via drush en redirect_to_ccbilling -y or by enabling it on the Extend module page.

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "redirect_to_ccbilling",
 *   label = @Translation("Redirect to CC Billing"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Redirect user to the credit card billing page."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class RedirectToCCBillingWebformHandler extends WebformHandlerBase {


How can I change the temporary file directory path without the UI?

Drush

drush config:set system.file path.temporary /tmp -y

settings.php

If done through settings.php it will no longer be changeable via either the interface or Drush.

Drupal 8.8+

See the change record.

$settings['file_temp_path'] = '/tmp';

Drupal 8.7 and below

$config['system.file']['path']['temporary'] = '/tmp';


Auto pulling an image from a post in Views

Yes select the cck field in the fields of the view and then in its options select number of images to display  to one. This should do the job.


Why file field button disappeared while uploading file?

Don't set upload_max_filesize larger than post_max_size if you are not using any library that takes care for such cases. Plupload integration with FileField Sources Plupload can get it managed for you.

Currently you are confusing your Drupal by allowing file upload larger than allowed data size. Given that data posted is file size + metadata size, both always equal to or greater than 0, it makes no sense and Drupal may fail.

Specifically, button disappeared because Form or Field API crashed, and it crashed because you mismatched sizes without providing appropriate handler.


In Drupal 7, the parameters for node_load() has been changed. To get the nodes that match some conditions, you should use the EntityFieldQuery class.

$query = new EntityFieldQuery();

 $entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'your_node_type')
  ->propertyCondition('title', 'your node title')
  ->propertyCondition('status', 1)
  ->range(0,1)
  ->execute();

  if (!empty($entities['node'])) {
    $node = node_load(array_shift(array_keys($entities['node'])));
  }


You're looking for the Custom Search module.
This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box, this module is for you.

Basic options
The module adds options to select:

which content type(s) to search,
which specific module search to use (node, help, user or any module    that implements search),
which input type to use (with Elements),
advanced criteria

For all these choices, there are options to switch between a select
box, checkboxes or radio buttons, and also customize the selector
label and the default - Any - text.
Advanced options
There are also options to:

change the default search box label,
add a default text in the search box,
add advanced search criteria,
change the default submit button text,
use an image instead of the submit button,
change the order of all the elements,
include some elements in a popup block,
add a filter to the results page,
show/hide basic and/or advanced search in the results page,
show/hide meta data in the results page,
multiple search paths

You can also achieve that by writing a custom module. Have a look at
Build a Drupal 7 Content Type Search Block in 5 Easy Steps


Views show list of nodes that have referenced node on another content type

I found the solution:

Add view from people content type.
and add relationship referencing entity with the author_name field and check Require this relationship.
To remove repeated rows use Views Distinct module.


How to add link module in Bootstrap Paragraphs?

If you add a Simple paragraph into the Content field, you can add whatever content you want in the wysiwyg without the need for a link field modification.

Here is of the hero the Bootstrap Paragraphs demo site.


You can do the following:

Run drush cex to export your configuration to the config directory.
Find the core.extensions.yml file in the configuration directory. Edit it, and remove the line that says: oauth2_server: 0
Run drush cim  to import your configuration. It should disable that module.


Pull content from production to staging server

Content is particularly difficult to Migrate. It's not as clean as Configuration. Generally, what you are talking about is not done - as Kevin points out, content is created on prod, and databases are pulled from prod to any other environment that needs that content. That said you could set up a Migration strategy with the Migrate API that could be used to migrate content around between environments. You're mostly on your own with this though - I haven't seen any tutorials for your specific issue.


How to increase the speed of exposed autocomplete field in views using drupal 6?

Assuming a Drupal installation configured for a production environment (including Apache and MySQL tuning), there are two things that impact autocomplete latency.

One, is a built-in delay between user input and running searches.  This is baked into misc/autocomplete.js.  The value is set to 300ms (line 245), and get used in Drupal.ACDB.prototype.search (line 287).

The second is that searches will run on a single character.  If your autocomplete result set is large, this can have huge performance impacts.

Unfortunately, there isn't a good way to alter either of these behaviors.  You can add your own Javascript and redeclare Drupal.ACDB to use a shorter delay, eg

Drupal.ACDB = function (uri) {
  this.uri = uri;
  this.delay = 100;
  this.cache = {};
};

and Drupal.ACDB.prototype.search to add in some logic to enforce a minimum number of characters, eg

...
// See if this string needs to be searched for anyway.
searchString = searchString.replace(/^\s+|\s+$/, '');
if (searchString.length <= min ||
  searchString.charAt(searchString.length - 1) == ',') {
  return;
}
...

However, 400 results isn't a huge number.  I have mainly seen the delays this with 10000+ results.  This suggests that you may need to do some additional profiling on your server.


How to detect device in template file in drupal 7

I would use Context & Context Mobile Detect


How to add a custom display field to a content type in Drupal 6

About uneditable custom field, here is a resource with several suggestions: http://drupal.org/node/1034768

about how to use a php code for pull data inside a custom cck field (If I understood well), I guess that you can build a module for use your respective code inside this module, and show the desired data inside a custom cck. This page have information related about How to create a CCK content type and fields from a module http://drupal.org/node/1044248

I hope information be useful


How to create a drop down menu for monthly archives?

I have create a new content type name with blog which have default fields(node title and body) Steps are given below.

First create a view(jump menu) for monthly archive.

Select post date of node one for drop-down text and second for link. All settings are given in screenshot.

Settings for jump menu

Settings for post date(first)

Settings for post date(Second)

Now add a page where display list of node based on drop-down value selection

Follow Page settings

Contextual filter settings for year

Contextual filter settings for year

Select a region for your monthly archive block. Here I am adding views export code that will help you better.

Views export code

$view = new view();
$view->name = 'monthly_archives';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Monthly Archives';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Monthly Archives';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'jump_menu';
$handler->display->display_options['style_options']['hide'] = TRUE;
$handler->display->display_options['style_options']['path'] = 'created_1';
$handler->display->display_options['style_options']['choose'] = 'Select Month';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'blog' => 'blog',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'jump_menu';
$handler->display->display_options['style_options']['hide'] = TRUE;
$handler->display->display_options['style_options']['path'] = 'created_1';
$handler->display->display_options['style_options']['choose'] = 'Select Month';
$handler->display->display_options['style_options']['default_value'] = TRUE;
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = '';
$handler->display->display_options['fields']['created']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['created']['alter']['text'] = '[created]';
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'custom';
$handler->display->display_options['fields']['created']['custom_date_format'] = 'F Y';
/* Field: Content: Post date */
$handler->display->display_options['fields']['created_1']['id'] = 'created_1';
$handler->display->display_options['fields']['created_1']['table'] = 'node';
$handler->display->display_options['fields']['created_1']['field'] = 'created';
$handler->display->display_options['fields']['created_1']['label'] = 'link path';
$handler->display->display_options['fields']['created_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['created_1']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['created_1']['alter']['text'] = 'archive/[created_1]';
$handler->display->display_options['fields']['created_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created_1']['date_format'] = 'custom';
$handler->display->display_options['fields']['created_1']['custom_date_format'] = 'Y/m';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Monthly Archives';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = '';
$handler->display->display_options['fields']['body']['element_label_colon'] = FALSE;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Content: Created year */
$handler->display->display_options['arguments']['created_year']['id'] = 'created_year';
$handler->display->display_options['arguments']['created_year']['table'] = 'node';
$handler->display->display_options['arguments']['created_year']['field'] = 'created_year';
$handler->display->display_options['arguments']['created_year']['default_action'] = 'default';
$handler->display->display_options['arguments']['created_year']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['created_year']['default_argument_options']['index'] = '1';
$handler->display->display_options['arguments']['created_year']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['created_year']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['created_year']['summary_options']['items_per_page'] = '25';
/* Contextual filter: Content: Created month */
$handler->display->display_options['arguments']['created_month']['id'] = 'created_month';
$handler->display->display_options['arguments']['created_month']['table'] = 'node';
$handler->display->display_options['arguments']['created_month']['field'] = 'created_month';
$handler->display->display_options['arguments']['created_month']['default_action'] = 'default';
$handler->display->display_options['arguments']['created_month']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['created_month']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['created_month']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['created_month']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['created_month']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['path'] = 'archive/%/%';


Here is the module that you need to import taxonomy from csv https://www.drupal.org/project/taxonomy_csv


Live filtering of nodes by taxonomy terms?

What you're after is known as Faceted Search. You're able to drill down your Views results based on taxonomy terms (or other fields for that matter) as you described.

A good example of Faceted Search can be found within the Commerce Kickstart demo store.

You'll need the Search API module as a basis, and I found a really good tutorial on getting started with Faceted search here: http://vimeo.com/15556855

If you're setting up a site which will get a lot of traffic, you might want to consider using Apache Solr to take some stress off your database when performing search queries.


How to add the current title to the breadcrumb without preprocess function?

There is also an alter hook for breadcrumbs, where you can alter them in a non-theme specific way, in case the breadcrumbs are also used somewhere else.

I've implemented this in a project:

/**
 * Implements hook_system_breadcrumb_alter().
 */
function yourmodule_system_breadcrumb_alter(array &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  // Append the current page title to the breadcrumb for non-admin routes.
  if ($breadcrumb && !\Drupal::service('router.admin_context')->isAdminRoute()) {

    $title = \Drupal::service('title_resolver')
      ->getTitle($request, $route_match->getRouteObject());
    if (!empty($title)) {
      breadcrumb->addLink(Link::createFromRoute($title, '<none>'));
    }
  }
}

EDIT for Drupal 8.2.x

I add a lot of error with this code, which I believe is the best approach for altering the breadcrumb has seen on Drupal API.
So here is the code for Drupal 8.2.x

/**
 * Implements hook_system_breadcrumb_alter().
 */
function YOURMODULE_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  // Append the current page title to the breadcrumb for non-admin routes.
  if ($breadcrumb && !\Drupal::service('router.admin_context')->isAdminRoute()) {

    $title = \Drupal::service('title_resolver')->getTitle(\Drupal::request(), $route_match->getRouteObject());
    if (!empty($title)) {
      $breadcrumb->addLink(\Drupal\Core\Link::createFromRoute($title, '<none>'));
    }
  }
}


TinyMCE input format is set to "Full HTML" but code is still being stripped

Assuming that the stripped tags in question are mostly things like embedded CSS style tags you might need to enable the Full Page plugin to allow them in your content, apparently having style tags in regions apart from HEAD tag is not the best practice and that's the reason the functionality is not enabled out of the box from my understanding. Also assuming that you have the WYSIWYG module with TinyMCE library installed for your cause and not the TinyMCE module, here's a sample code of how I enabled the full page plugin in my case. (The code goes in your custom module, replacing your module name with MYMODULE in the function name).

/**
 * Implementation of hook_wysiwyg_plugin
 *
 */
function MYMODULE_wysiwyg_plugin($editor) {
  // if the editor is tinymce include the fullpage plugin so that embedded css is included
  $plugin_path = wysiwyg_get_path('tinymce');
  switch ($editor) {
    case 'tinymce':
      $plugins = array(
        'fullpage' => array(
          'path' => $plugin_path . '/jscripts/tiny_mce/plugins/fullpage',
          'buttons' => array('fullpage' => t('Full Page')),
          'url' => 'http://www.tinymce.com/wiki.php/Plugin:fullpage',
          'internal' => TRUE,
          'load' => TRUE
        )
      );
      return $plugins;
    default:
      break;
  }
}


How do I send a variable value from my form to another page using the POST method?

This is how I send information from one form to another.

In the first page:

use \Drupal\Core\Url;

function submitForm(array &$form, FormStateInterface $form_state){
  drupal_set_message($this->t('@candidate_name! Wow! Nice choice! Thanks for telling us!', array('@candidate_name' => $form_state->getValue('candidate_name'))));

  $params['query'] = [
    'candidate_name' => $form_state->getValue('candidate_name'),
  ];

  $form_state->setRedirectUrl(Url::fromUri('internal:' . 'second_page', $params));
}

In the second page:

public function buildForm(array $form, FormStateInterface $form_state) {
  $candidate_name = \Drupal::request()->query->get('candidate_name');

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Candidate Name:'),
    '#required' => TRUE,
    '#value' => $candidate_name,
  );

  return $form;
}

EDIT: For POST method I never see it before, but you can create in the first page a session var and use this var in the second var after the redirection. Take a look in Storing Session Data with Drupal 8.

SECOND EDIT: It seems that the correct way todo this is with PrivateTempStore, if you go to see the CommentAdminOverview in Core you will see this:

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
      ...
      $info = [];
      /** @var \Drupal\comment\CommentInterface $comment */
      foreach ($comments as $comment) {
        $langcode = $comment->language()->getId();
        $info[$comment->id()][$langcode] = $langcode;
      }
      $this->tempStoreFactory
        ->get('comment_multiple_delete_confirm')
        ->set($this->currentUser()->id(), $info);
      $form_state->setRedirect('comment.multiple_delete_confirm');
    }
  }

In this page you collect the comment id that you want to delete and made a redirect, and the comment deletion happens in comment.multiple_delete_confirm (ConfirmDeleteMultiple) that have the following code:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->commentInfo = $this->tempStoreFactory->get('comment_multiple_delete_confirm')->get($this->currentUser()->id());
    if (empty($this->commentInfo)) {
      return $this->redirect('comment.admin');
    }
    /** @var \Drupal\comment\CommentInterface[] $comments */
    $comments = $this->commentStorage->loadMultiple(array_keys($this->commentInfo));
  ...
  }

So, we don't have a POST method from one form to another in Drupal 8 but this can be solved in this way.


Where is this file supposed to really be?

It's config, so config/install is fine

  What should it be named to get picked up?

Like other config it's module_name.type.machine_name.yml, so (e.g.) migrate_plus.migration.id.yml

  do I have to uninstall/install the module numerous times as I iterate over a POC and make changes to the migration definition?

No, just like a normal config import you can do it partially:

drush cim --partial --source=/path/to/your/module/config/install

I did exactly what you did when I first played with Migrate Plus - tried to put the config in a migrations folder, like the example, but it didn't work for me either.

As migrations are config, this does make sense looking back - otherwise Migrate Plus would need to do something non-standard when discovering/importing migration configurations.


You have to override theme_pager_link() as well. The last line calls the l() function and you have to force it to render html.

Another possibility is to use css to theme the links


Cleanest way to write EntityCondition on field from widget

I was trying to find a way to filter on complex parts of the node - ie widget items that were attached as properties.

I didn't find a way. Resolved with just SelectQuery. I manually did the join instead of using node semantics and related node hooks. It would be nice to have findNodeByPnid... - and I can't see a way to build a condition without having to go another layer down into the node and working out how it is built.

Lots of our code has various forms of 'find where parent is' and 'show me the parent of this node' - subtly different enough to make it hard to generalise. Therefore, the code is broken up into parts.

1 initiate query

Always adding tag.

$query_key = 'associatenode_' . implode('', $node_types);
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title'))
      ->condition('n.type', $node_types, 'IN')
      ->orderBy('title', 'ASC')
      ->addTag($query_key);

2 Add join

Either calling join function directly or by tag. Further mangle query later.

function hottopicsresearch_query_associatenode_hot_topic_research_alter(QueryAlterableInterface $query) {

Calls

function hottopicsresearch_research_for_topic_query_join($parent_nid, QueryAlterableInterface $query) {
  // Find our menu links
  $query->leftJoin('nodehierarchy_menu_links', 'nh', 'n.nid = nh.nid');

  // Find associated menus. This is used to find the parent menus.
  $query->leftJoin('menu_links', 'menu', 'nh.mlid = menu.mlid');

  // Now find the parent menu
  $query->leftJoin('nodehierarchy_menu_links', 'nh_parent', 'menu.plid = nh_parent.mlid');

  // Grab the actual parent nodes
  $query->leftJoin('node', 'node_parent', 'nh_parent.nid = node_parent.nid');

  // Filter out anything that is not our parent
  $query->condition('nh_parent.nid', $parent_nid, '=');
}


Recieving error: Fatal error: Class 'panels_renderer_standard' not found in

Check your modules/panels/plugins/display_renderers folder and make sure there is a file named panels_renderer_standard.class.php inside, that's where the class is contained that is supposedly missing.

Try completely replacing the panels module code with a fresh download, that is: move the current module folder somewhere else (so you can get it again if you need to) and re-upload the module.

If you're applying any patches, make sure you check them for code that might be deleting, renaming, or disabling the display_renderer_standard class.


Your code is working perfectly ok. I installed it you can check the screenshot below.


If you can export the content to a csv format. Then use Feeds to import the csv file to the mapped fields.


Drupal 7 doesn't do anything like that in core. You likely used another module. Pathologic provides this, also exists as a D8 version, only as a dev version, though.


How to customize my front page with background image?

Try eiher of hese searches:

Specific to sub-theme topics.
Specific to front.tpl.php.

Pick any of the proposed answers that fits best your needs. Such as a solution that is based on using something like firebug to find the CSS file that allows you to adapt your background to fit your needs.


I might suggest using Rules, Node Limit and Field Permissions for this... something like:

limit the user to creating one node (restaurant) type
create a field for the user, alter its access using Field Permissions, so they can't see or change it
use Rules on the event of new content created (restaurant), assign that user Field the node id of the newly created node
using Rules again, assign the appropriate field in any further node creation (menu item) using the user field value (which now contains the node id of the restaurant)
using Rules again, check url for /node/[menu-item]/add and see if that user has a user field containing a node id - if no id, redirect to a message screen saying they have to create a restaurant first

In this way, you limit each user to one restaurant, assign a permanent value to that user for the restaurant they create, and make some checks to ensure they have an assigned node id before they are able to create a menu item.

Rules:

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module

Node LImit:

  The Node Limit module allows administrators to restrict the number of
  nodes of a specific type that roles or users may create. For example,
  if a site has an "Advertiser" role that can create "advertisement"
  nodes, then the node limit administrator can restrict all users in
  that role to a specific number of nodes. He may also restrict users on
  a per-user basis.

Field Permissions

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


If you are trying to add a js library from an external cdn in drupal 8 then, in your theme/module mycustom.libraries.yml file add do like this:

NOTE: Make sure you indent each spaces with two spacebar press button and not a tab press.

NOTE: version is optional here. You may not need add in.

mycustom.flexslider:
  version: 2.6.3
  css:
    theme:
      //cdnjs.cloudflare.com/ajax/libs/flexslider/2.6.3/flexslider.css: {type: external}
  js:
    //cdnjs.cloudflare.com/ajax/libs/flexslider/2.6.3/flexslider.min.css: {type: external}
  dependencies:
    - core/jquery

If you are hosting it within your module or theme then:

NOTE: Here I placed flexslider within my theme or module vendor directory. So it would be inside mycustom/vendor/flexslider

mycustom.flexslider:
  version: 2.6.3
  css:
    theme:
      vendor/flexslider/flexslider.css: {}
  js:
    vendor/flexslider/jquery.flexslider-min.js: {}
  dependencies:
    - core/jquery

If you are just trying to host your custom js or css file then:

mycustom.myscript:
  js:
    js/script.js: {}

If its dependent on other library like core jquery or custom library then:

mycustom.myscript:
  js:
    js/script.js: {}
  dependencies:
   - core/jquery
   - mycustom.myscript2

Then like in example module If I had to add flexslider library:

public function getFlexSliderImplementation() {

    $build['myelement'] = array(
      '#theme' => 'js_flexslider',
    );
    // Add our script. It is tiny, but this demonstrates how to add it. We pass
    // our module name followed by the internal library name declared in
    // libraries yml file.
    $build['myelement']['#attached']['library'][] = 'mycustom/mycustom.flexslider';
    // Return the renderable array.
    return $build;
  }

Update:
Download and extract Flotr2 to your module or theme vendor directory. Modify libraries.yml file to include flotr2

js_example.flotr2:
 js:
   vendor/flotr2/flotr2.min.js : {}

js_example.sdashboard:
  css:
    component:
      vendor/sDashboard/sDashboard.css: {}
  js:
    vendor/sDashboard/jquery-sDashboard.js : {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.datatables
    - js_example/js_example.flotr2


If your are using Drupal 7 you could make a use of the administrative overlay with a custom module.

You will need 3 hooks in your CUSTOM_MODULE_NAME_HERE.module file :

/**
 * Implements hook_menu().
 */
function CUSTOM_MODULE_NAME_HERE_menu() {
  $items = array();
  $items['your/path/to/your/page'] = array(
     'page callback'    => 'CUSTOM_MODULE_NAME_HERE_page',
     'access arguments' => array('access content'),
     'type'             => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implements hook_admin_paths_alter().
 */
function CUSTOM_MODULE_NAME_HERE_admin_paths_alter(&$paths) {
    $paths['your/path/to/your/page'] = TRUE;
}

/**
 * page callback
 */
 function CUSTOM_MODULE_NAME_HERE_page(){
    $output = 'your page content';
    return $output;
}


Does the Drupal FAPI support more than one AJAX callback?

Yes, you can solve it with core Drupal AJAX framework. You are already using $commands, you just need one more custom command.

Javascript code to provide new command:

(function ($) {
  Drupal.ajax.prototype.commands.change_title = function(ajax, response, status) {
    // Update the <title> element.
    document.title = response.data;

    // Update the page title.
    response.data = response.prefix + response.data;
    this.insert(ajax, response, status);
  }

})(jQuery);

PHP code to call this command:

  $commands['#commands'][] = array(
    'command' => 'change_title',
    'method' => 'html',
    // Selector targets Drupal 7's default theme
 title (Bartik 7.12).
    'selector' => 'div#branding h1.page-title',
    'data' => check_plain($form_state['node']->title),
    'settings' => NULL,
    'prefix' => 'Edit '. node_type_get_name($form_state['node']). ' ',
  );

Original idea is taken from here.


I would add JS/CSS files inside the preprocess_page() function. If I don't want the CSS/JS files loading on some pages I will use an IF statement and check for a setting or if something exists etc, this will depend on the project.


Apache solr search integration at live site

You can't run a solr instance on a regular hosting service; the most of them give you a database server and Apache Server.

However, you can use a Free or Paid solutions like OpenSolr, for example.
Once you have this configured, you just need to copy and paste the Solr URL into your Drupal Solr configuration.


Send POST data to payment gateway on form submit

Check drupal_http_request().

  Performs an HTTP request.

  This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.


Until pull requests on https://git.drupalcode.org become a thing the procedure still is basically as follows:

Create an issue in that module's issue queue on drupal.org.
Git clone that module's repo and checkout the branch where you wanna fix something.
Fix the bug.
Create a patch: $ git diff > [project_name]-[short-description]-[issue-number]-[comment-number].patch
Upload that patch in the issue from step 1. and set the issue to "Ready for review".

Now everybody finding the same bug can apply that patch at best using Composer and maybe cweagans/composer-patches until the patch got committed and released by one of the module's maintainers.

The full documentation can be found on drupal.org:

Making a Drupal patch with Git
Advanced patch contributor guide.


If blocks are added via /block/add you can edit the block content via /admin/structure/block/block-content. Click on Edit and you should see a body text area appear. You can enter your block content there.


How do you create a block that contains fields from the User Profile?

render() only returns the string, it doesn't print it to the output. This code should work:

<?php print render(user_view($account)); ?>

Assuming of course that you have loaded the $account object. If not you probably want to use something like:

global $user;
$account = user_load($user->uid);

As an aside, using the PHP filter is considered bad practice (it uses eval() which is an inherent security risk).

The best way to get what you're looking for is to write a small custom module that implements hook_block_info() and hook_block_view():

function MYMODULE_block_info() {
  return array(
    'user_profile' => array(
      'info' => 'User Profile Block',
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  if ($delta == 'user_profile') {
    global $user;
    $account = user_load($user->uid);
    $block['subject'] = 'User Profile';
    $block['content'] = user_view($account);
  }

  return $block;
}

If your new to writing modules the best resource I know of is the Module developer's guide, and in particular the Creating Drupal 7.x modules sub-section; it will walk you through all of the steps necessary to get your module up and running.

UPDATE

Just to address your second comment...

I think the easiest way to get only certain fields to display would be to install the Entity View Modes module. Then you can create a custom view mode for the user entity (called block_profile or something), and in the "Manage Fields" admin page for users assign only the fields you want to be displayed to that new view mode.

Then you can pass the new view mode to the user_view() function:

$block['content'] = user_view($account, 'block_profile');

And voila, your block will contain only the fields that you've added to the new view mode through the admin UI.

If Entity View Modes is causing you issues you can just uninstall it, and add the new view mode yourself using hook_entity_info_alter() (again in your new custom module):

function MYMODULE_entity_info_alter(&$info) {
  $info['user']['view modes']['profile_block'] = array(
    'label' => t('Profile Block'),
    'custom settings' => TRUE
  );
}


Only remove the curly brackets, not what's inside the them. The brackets contain the actual table name, and directly after is the table alias which is used later.

This should work (only brackets removed):

SELECT taxonomy_term_data.name AS taxonomy_term_data_name,
       taxonomy_term_data.vid AS taxonomy_term_data_vid,
       taxonomy_term_data.tid AS tid,
       taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name
FROM   taxonomy_term_data taxonomy_term_data
       LEFT JOIN taxonomy_term_hierarchy taxonomy_term_hierarchy
              ON taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
       INNER JOIN taxonomy_term_data taxonomy_term_data_taxonomy_term_hierarchy
               ON taxonomy_term_hierarchy.parent =
                  taxonomy_term_data_taxonomy_term_hierarchy.tid
       LEFT JOIN taxonomy_vocabulary taxonomy_vocabulary
              ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE  ((( taxonomy_vocabulary.machine_name IN ( 'book_category' ) )))

Note that if your tables has a prefix, i.e. drupal_ then you need to add that to the table name, because that's the reason the brackets are used, in case of table prefix.

Cheers,


It is easy to use GET instead of POST, but Drupal sends a lot of information about dom-elements and loaded css/js, so that it is often too long for a GET request..

var ax = new Drupal.ajax("element-name", this, element_settings);
ax.options.type = "GET";

If you do not use these, you can strip them:

//Override parameters for Get Requests
var backup = Drupal.ajax.prototype.beforeSerialize;
Drupal.ajax.prototype.beforeSerialize = function(element, options) {
  if(options.type != "GET") backup.call(this, element, options);
}


Form Default Values missing on theming form

See examples for developers. You should not theme form in form alter hook. Do it in hook_theme(). In a module it looks like that:

function yourmodule_theme() {
  return array(
    'yourmodule_form' => array(
      'render element' => 'form',
      'file' => 'forms/yourmodule_form.inc',
    ),
  );
}

If you move elements around in form_alter(), they became different fields. If #tree is set to false (default), it does not interfere with submit, but it may interfere with defaults and validation.


Use one theses modules :

User Field Privacy

  All the user fields should have an "alterable privacy" checkbox.
  If this checkbox is ticked, the user should be presented with an    additional checkbox for the privacy-enabled fields on user edit forms
  to be able to make that fields' values private.
  If this second checkbox is ticked for a field of a user, only the    site administrators (members of roles with the "Access private
  fields" permission) and the user herself should be able to view that
  field's value.

CCK Private Fields

  This module allows users to mark administrator selected CCK fields as
  Public (visible to everyone), Hidden (visible to node author, hidden
  from everyone else) or Private (visible to node author and "friends";
  see requirements section below).

Field Permissions

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned    based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on    who the entity owner is.
  Permissions for each field are not enabled by default. Instead,    administrators can enable these permissions explicitly for the fields
  where this feature is needed.


If you are having issue with the content that is being printed on the front page.
Then you can create a page--front.tpl.php and print the variable according to the requiremt.

If $title gives you the <h1> and <h2> tags, then you can strip_tags($title, 'tags that need to be maintained e.g. <a>') to remove the tags.

If you have issues with views field label, you can use 'Rewrite the output of this field' and 'Strip HTML tags' to change the output mentioned in the image below:-

Hope it will help!


Whats best practices for handling Drupal 8 core file paths for vendor package.json

I think this is a slight misinterpretation of the security risk.

The core/ directory needs to be in your DOCROOT; it has assets that the webserver needs to serve up (JS, CSS, and images).

The vendor/ directory should (mostly) be outside of your DOCROOT; some packages have files that shouldn't really be accessed by the webserver directly and have been the focus of recent SAs.

The exception to this are dependencies that need to be served up or be in the proper place, hence why people use the installer-paths to place modules, themes, and JS libraries in the right place.

While not universal, I would say that drupal-composer/drupal-project is a growing best practice, at least for starting points for websites.  This will place vendor/ outside of DOCROOT, take care of the autoloader and scaffold files, and set up a sane set of installer-paths.  Even if I am not using this directly, I look to its composer.json for inspiration.


Remove js file by template or add condition in info file

You can use hook_js_alter()

Perform necessary alterations to the JavaScript before it is presented on the page.
Parameters
$javascript: An array of all JavaScript being presented on the page.

Then you should be able to use menu_get_object() to load the node type and unset the js file in the $javascript array.
function MYTHEME_js_alter($javascript) {
  $node = menu_get_object();
  if ($node->type == 'node_type) {
    unset($javascript['path/to/script.js']);
  }
}

Note: I haven't tested this or checked syntax, let me know if it doesn't work and I will test.


Taxonomy filter exposed to user that dynamically only includes terms attached to currently published content

You should have a look at Views Selective Exposed Filters, part of the Views Hacks module. It will limit the taxonomy terms to those in your view's result set.


In form alter what is the different way of hiding fields and what is the difference between them?

The basic differences are:

$form['field_name']['#access'] = FALSE; hides the form element. When saving the form Drupal will not touch the field. That means the initial value will remain. Maybe interesting: Other users can do with that node's field what ever they want. You saving the node will not undo their changes, although you only know about the old value of that field.

hide($form['picture']); is afaik used in theme functions only. It can cause forms to break because after saving a form this field is expected to have a value but is not even rendered. So use this with care. When you hide a field that is important make sure to manually render it later. Calling hide will also hide all child elements of the element you hide. A use case could be: Render child elements of a form manully and call hide on those elements. When you now render the parent element only those child elements are rendered that did not go through hide.

unset($form['picture']); should not be used. It just drops parts of an array. It is better to use one of the other three functions that keep the data consistent and not delete stuff Drupal expects.

$form['account']['mail']['#disabled'] = TRUE; will not hide the element but just make it unchangable (greyed dropdowns, etc.). It acts like a normal field but the initial value cannot be changed by the user.

In addition to what you asked, Clive added something:

Form elements are commonly converted to array('#type' => 'value', '#value' => 'foo') to remove them from the form but keep them server side, and not mess up the submission process. It's the best of all available methods IMO

Hope that help although I am not completely sure about the consequences of unset.

cheers,
j


how to check if the image field is empty or have uploaded image?

Try this:

if ($node = menu_get_object('node')) {

  // Set default language if not set
  $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;

  if ($node->type == 'page' && isset($node->field_page_cover_image[$node->language][0]['uri'])) {
    print theme('image_style',
            array('path' => $node->field_page_cover_image[$node->language][0]['uri'],
                  'style_name' => 'page_theme'));
  }

}

Odd you're printing out the image though, must be in a tpl file. I'd suggest moving the code logic to a hook_preprocess_node and setting a template variable instead.

e.g:

/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node($variables){

  $node =& $variables['node']; // by reference
  // Set default language if not set
  $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;

  if ($node->type == 'page' && isset($node->field_page_cover_image[$node->language][0]['uri'])) {
    // Add new template variable called $page_theme_image
    $variables['page_theme_image'] = theme('image_style',
            array('path' => $node->field_page_cover_image[$node->language][0]['uri'],
                  'style_name' => 'page_theme'));
  }

}

and then in your tpl.php file, you just go:

if (!empty($page_theme_image)) {
  print $page_theme_image;
}


How to use CiviCRM Entity for searches with Facet API

A wee bit of info here:

http://forum.civicrm.org/index.php?topic=32169.0

but seems like u'll need to dig around and help build it

lobo


What is the memcache report screen telling me?

Those are operations on your memcached server.

Sets: Data placed into cache by sets/second; by absolute number (by % of total commands); and a display of total number of commands. Sets are expensive (it represents needing to retrieve from your DB or other slower data sources) so you want this to be as low as possible, relative to gets.
Gets: Data requested from cache by gets/second; by absolute number (by % of total commands); by absolute number of cache retrievals (by % of total gets); by absolute number of cache misses (by % of total gets). Gets are the entire reason you employ memcache (to retrieve from fast memory rather than a slower disk/network) so you want this to be high as possible, relative to sets.
Counters: The number of increment/decrement operations performed on memcached counters.
Transferred: The ratio of read to written data. Since it's in absolute data amount, it gives you an idea of how much you're saving in reading from slow disk/network storage.
Per-connection average: The average amount of data and memcache operations made in a Drupal connection by gets/sets. The should give you an idea of how much memcache is employed on a Drupal request.
Available memory: The amount of memory used / available on the server. This is another metric showing how much you're utilizing memcache.
Evictions: The number of evictions or cached data removals from your memcached server.


how to put arguments into contextual filters

There's a comment in that article down below with a code to import for D7 and Views 3.

If you import that code into your Views 3 and then study the Contextual Filters and the Relationships you should get a good idea on how to achieve this.


Drupal 7 how to use item menu as MENU_LOCAL_TASK and MENU_NORMAL_ITEM simultaneous?

You can use a bitwise operator for that, e.g.

MENU_LOCAL_TASK | MENU_NORMAL_ITEM

There's a real-world example in the core comment module (comment_menu()):

$items['admin/content/comment'] = array(
  'title' => 'Comments',
  'description' => 'List and edit site comments and the comment approval queue.',
  'page callback' => 'comment_admin',
  'access arguments' => array('administer comments'),
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'file' => 'comment.admin.inc',
);


Different roles create different amounts of a specific content type

Sounds like you should have a look at the Group module, which gives you all the features you are looking for, using the "roles" of the Group module (as explained in "What are the various roles supported by the Group module?"), combined with granting the relevant permissions for each of the groups you'd configure. Refer to some of these questions to get you going with the Group module.

BTW, even though this question is about D8, same is true for D7 ...


What version of Drupal is this?

It's against best practices to go directly to the database but if you really need to I don't see why you can't query the field's table. What problems are you having?

When entering data for a field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

You may wanted to use format_date to convert your time.
See: https://api.drupal.org/api/drupal/includes!common.inc/function/format_date/7

UPDATE:

I don't know what source you time is in, either a timestamp or formatted date/time. In your example you're using  2014-04-28 11:00:00 so lets convert that to a unix timestamp:

  $newdate = new DateTime('2014-04-28 11:00:00 UTC', new DateTimeZone(date_default_timezone_get()));
  $unixts = $newdate->getTimestamp();
  $siteDate = format_date($unixts, 'small', '', date_default_timezone_get());


This is in the view mode "teaser" of the content type "article":

/admin/structure/types/manage/article/display/teaser

Go there and click on the setting symbol in the field "image" and choose the new image style.


You don't have to worry about the values which are set for cache max-age in other places, because when these are merged the lower time that you have set wins.

But you can't control with max-age the page cache for anonymous users. You have to use \Drupal::service('page_cache_kill_switch')->trigger(); in the block build method to disable the page cache or you can simply uninstall the module Internal Page Cache if you plan to use the block on all pages.

  but I don't have max age in admin/config/development/performance

You should set this to the same max-age to control the browser cache and proxies.


Add CSS class to view image_field in twig

This is what worked for me: It's a preprocess function in the .theme file. I wish there was a way to do this directly into the template. This would apply that class everywhere the field appears.

/**
 * Implements hook_preprocess_field().
 * Adds a class to a People image.
 */
function themename_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_machine_name') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['content']['#item_attributes']['class'][] = 'my_class';
    }
  }
}

themename, field_machine_name, and my_class are placeholders for your values.

This produces:

<img class="my_class" src="/your/image/location.png" alt="Your alt text." typeof="foaf:Image" width="458" height="354">


How to restrict field permissions to referenced user?

I assume field_reviewer is an user reference field with only a single value allowed. If so use the following to get the referenced user's uid which is directly stored in field_reviewer array in submission:

// is current user == node reviewer?
if (!empty($entity->field_reviewer)) {
  $reviewerId = $entity->field_reviewer['uid'];
  return ($reviewerId == $user->uid);
}
return FALSE;


The last time I tried node fields block, some of the fields doesn't really show. So I just switched to using the views blocks. it's just the same. Just insert the fields you wanted to show. If you want users to upload files on the current page you could try Block upload - it's a simple module, which allow users to upload images/files into field without node edit page.

Did I understand your case correctly?


How do I change the views handler type for a field from string to int?

You "should" just need to override the filter handler for the field, e.g.

function mymodule_views_data_alter(&$data) {
  $data['user']['field_my_custom_field']['filter']['handler'] = 'views_handler_filter_numeric';
}

Untested, use with caution!


How can webform performance be improved on low internet connection?

To enable all caching:

Navigate to "Extend" and enable the following modules:

Internal page cache
Internal dynamic page cache

Navigate to "Configuration > Development > Performance" and enable cache for a period of time (E.g. 6 hours) and check both the options for "Aggregrate CSS/JS"

Hopefully that may help with your issue.


Using HOOK_preprocess_field(&$variables):

/**
 * Implements HOOK_preprocess_field().
 *
 * @inheritdoc
 */
function HOOK_preprocess_field(&$variables) {
  $element = $variables['element'];
  // Check that field_name is set.
  if (isset($element['#field_name'])) {
    // Checking for field_name, but could check for field_type.
    if ($element['#field_name'] == 'field_name') {
      // Set our file size to a variable.
      $fileSize = $element[0]['#file']->filesize->value;
      // Edit our title for the field display.
      $element[0]['#file']->filename->value = $element[0]['#file']->filename->value . ' ' . $fileSize;
    }
  }
}

Using HOOK_preprocess_file_link(&$variables):

/**
 * Add the "file-link.html.twig" template to your theme and adjust as needed.
 *
 * Twig variables:
 * - {{ fileLinkDisplay.fileBundle }}
 * - {{ fileLinkDisplay.fileCreatedTime }}
 * - {{ fileLinkDisplay.fileChangedTime }}
 * - {{ fileLinkDisplay.fileFid }}
 * - {{ fileLinkDisplay.fileLangcode }}
 * - {{ fileLinkDisplay.fileMime }}
 * - {{ fileLinkDisplay.fileName }}
 * - {{ fileLinkDisplay.fileOwnerId }}
 * - {{ fileLinkDisplay.fileOwnerName }}
 * - {{ fileLinkDisplay.fileOwnerUserPictureUrl }}
 * - {{ fileLinkDisplay.fileSize }}
 * - {{ fileLinkDisplay.fileSizeFormatted }}
 * - {{ fileLinkDisplay.fileStatus }}
 * - {{ fileLinkDisplay.fileUrl }}
 * - {{ fileLinkDisplay.fileUuid }}
 */

function HOOK_preprocess_file_link(&$variables) {
  if (isset($variables['file'])) {
    $variables['fileLinkDisplay'] = [
      'fileBundle' => $variables['file']
        ->bundle(),
      'fileCreatedTime' => $variables['file']
        ->getCreatedTime(),
      'fileChangedTime' => $variables['file']
        ->getChangedTime(),
      'fileFid' => $variables['file']
        ->fid->value,
      'fileLangcode' => $variables['file']
        ->langcode->value,
      'fileMime' => $variables['file']
        ->getMimeType(),
      'fileName' => $variables['file']
        ->getFilename(),
      'fileOwnerId' => $variables['file']
        ->getOwnerId(),
      'fileOwnerName' => $variables['file']
        ->getOwner()->name->value,
      'fileOwnerUserPictureUrl' => file_create_url($variables['file']
        ->getOwner()->user_picture->entity->uri->value),
      'fileSize' => $variables['file']
        ->getSize(),
      'fileSizeFormatted' => format_size($variables['file']
        ->getSize()),
      'fileStatus' => $variables['file']
        ->status->value,
      'fileUrl' => file_create_url($variables['file']
        ->getFileUri()),
      'fileUuid' => $variables['file']
        ->uuid->value,
    ];
  }
}

See https://gitlab.com/prestosaurus/file-link-display/blob/master/file_link_display.module

Then your file-link.html.twig might look like:

{#
/**
 * @file
 * Theme override for a link to a file.
 *
 * @see template_preprocess_file_link()
 */
#}
{{ attach_library('classy/file') }}
<span{{ attributes }}>{{ icon }} {{ link }} {{ fileLinkDisplay.fileSize }} {{ fileLinkDisplay.fileMime }}</span>


Drupal services forbbiden error on put but not on post

Assuming it is an apache web server you could try this in your .htaccess file.

<Limit GET POST PUT DELETE>
  Allow from all
</Limit>

Otherwise you may need to contact the hosting support to see if they have restricted PUT requests


If two modules both defined the same menu path in 'hook_menu', which one Drupal will choose?

The function invoking hook_menu() is menu_router_build(), called by menu_rebuild(). It contains the following code.

  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }
  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);

If there are two modules defining the same route, the last module in the array returned by module_implements() will override the value defined from the other modules.

The second parameter required by module_implements() is defined as:

  $sort By default, modules are ordered by weight and filename, settings this option to TRUE, module list will be ordered by module name.

Since menu_router_build() doesn't pass the second parameter to menu_implements(), the function is using the default value for that parameter. This means the list of modules are ordered by their weight and filename; when two modules have the same weight, the first module that appears in the list is the one that alphabetically comes first.

Furthermore, any module implementing hook_module_implements_alter() can alter the order the hooks are invoked.

For this reason, you should not assume to know in which order the hooks are invoked.
If the purpose of the code is altering the route implemented by another module, for example because a route should be removed when a second module is installed and enabled, the code should use hook_menu_alter(). If you are trying to understand which module would "win" in the case of route conflicts, I would rather avoid such route conflict, and define a route that is not already defined from another module.

If then you are implementing hook_menu_alter(), and you want to be sure your module is executed last, to be the module that effectively overrides a route, you should implement hook_module_implements_alter() too.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move mymodule_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}


Ho to improve Drupal site score on PageSpeed Insights Site

A possible starting point might be the Advanced CSS/JS Aggregation module.

The following article shows some possible configuration options that can increase your PageSpeed Insights score:

https://www.northstudio.com/blog/increase-your-drupal-site-pagespeed-score-part-2-advagg


Step 1

Create a Rule Component to "Grant a user the Trusted authenticated user permission" (whereas the user is specified as a parameter for this Rules Component).

Step 2

Enable the rules scheduler (a sub-module of the Rules module).

Step 3

Adapt the rule you seem to have in place already for that "movement from 1) to 2)" (or create a new rule that catches that as a Rules Event): at the end of this rule, add another Rules Action to schedule the execution of the Rules Component in Step1, after 24 hours.

Optionally you may also want to add some extra Rules Conditions that the user does not have rule "3)" yet (or any other Rules Condition that may fit).

Step 4

Next time your cron job runs, the permission "Trusted authenticated user" will get granted.

PS: I'm assuming this question is about D7.


drupal_mail() supports a display name in the From: field, but it's up to the whatever module you're using to send mail. If you'd like to force the name, you can use the MIMEMail module.

Once installed, under the Configuration > System > Mimemail administration menu, you can set the default Name/Email that will be sent.


How do I make twig variables available in node.html.twig accessible in my html.html.twig?

Kevin is right, creating a library and then attaching it is the better approach for this.
theme-name.theme
THEME_NAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->field_bootstrap->value) { // checks boolean is true
     $variables['#attached']['library'][] = 'theme-name/bootstrap-files';
  }
}

theme-name.libraries.yml
bootstrap-files:
  version: 1.x
  css:
    theme:
      css/boostrap.css: {}
  js:
    js/boostrap.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

and you'll have to put the bootstrap css and js files inside the /css and /js folders of your theme.

Better Yet
Install Bootstrap Library module.
theme-name.theme
THEME_NAME_preprocess_node(&$variables) {
  if (\Drupal::moduleHandler()->moduleExists('bootstrap_library')) {
    $node = $variables['node'];
    if ($node->field_bootstrap->value) { // checks boolean is true
       $variables['#attached']['library'][] = 'bootstrap_library/bootstrap-cdn';
    }
  }
}


Try using a

hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  ....
  if (isset($form['actions']['submit'])) {
    $form['actions']['submit']['#ajax'] = [
      'callback' => '/path/to/your/controller/or/webformhandler/submitModalFormAjax',
      'event' => 'click',
    ];
}

in your *.module and then implement the callback function somewhere

public static function submitModalFormAjax(array &$form, FormStateInterface $form_state) {...}


For preprocess function you can use HOOK_preprocess_menu_local_tasks(&$variables) {... where HOOK is the name of your active theme.
And for template suggestions you need to enable debugging and see with inspect element, as usual it must be menu-local-tasks.html.twig


Reusing drupal forms in a profile installation?

The problem

A bad implementation of your code is causing the confusion. The input data is not stored in the $form_state variable, but in $form_state['input'] initially.

Once the user submit a form, Drupal will build the form again and process the values. In this step, the system make some checks. You can take a look of functions that have been called.

The function _form_builder_handle_input_element($form_id, &$element, &$form_state) is the one that set the values in $form.

The previous function is called in the middle of form_builder().  At the end of same function, drupal will fill the values in '$form_state' variable .

Why the function is not filling the values?

Because the next code is checking the input form:

// Set a flag if we have a correct form submission. This is always TRUE for
// programmed forms coming from drupal_form_submit(), or if the form_id coming
// from the POST data is set and matches the current form_id.

if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
  $form_state['process_input'] = TRUE;
}
else {
  $form_state['process_input'] = FALSE;
}

The result is FALSE because $form_state['input']['form_id'] != $form_id.

'site_google_analytics_form' != 'googleanalytics_admin_settings_form'

So, the input finally is not processed for security reasons

Solution

Your code should be implemented like this:

/*
* hook_install_tasks(&$install_state)
*/
function hook_install_tasks(&$install_state){

$tasks['site_google_analytics_form'] = array(
        'display' => TRUE,
        'type' => 'form',
        'display_name' => st('Google Analytics Configuration'),
);

return $tasks;

}

/**
* Configure google analytics.  The only required field is the tracking code.
*/
function site_google_analytics_form($form, &$form_state){

    module_load_include('inc', 'googleanalytics', 'googleanalytics.admin');
    return googleanalytics_admin_settings_form($form, $form_state);

}

The run_task() call itself the drupal_get_form(), so it was no necessary call yourself in your code.


Views: Display Total number of products in commerce kickstart shopping cart

In menu badges module check line no 335 code

/**
 * Drupal Commcerce cart items count callback.
 * @param array $arguments
 */
function menu_badges_commerce_cart_item_count() {
  global $user;

  if (module_exists('commerce_cart') && $order = commerce_cart_order_load($user->uid)) {
    // Count the number of product line items on the order.
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
    if ($quantity > 0) {
      return $quantity;
    }
  }
  return NULL;
}

You can get total quantity using below code also...

  global $user;
  $order = commerce_cart_order_load($user->uid);
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $quantity_total = 0;
  foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $quantity = $line_item_wrapper->quantity->value();
    $quantity_total = $quantity_total + $quantity;
  }

Commerce modules does not provide view handler for Quantity Total.. If you are interested you can create one and share it with community.. Other wise you can use views php module to achieve same...


Get all registered Users into a Field Type List

You can create form using Entity form.
It provides interface you to fetch content from the drupal fields taxonomy and other fields.
Term reference is inbuilt in drupal to add the Sports list.

For user reference list you can add the references module which will ask you to choose users from the registered users.

Hope it will help you


How to set up permissions for the private files directory?

I would not create the folder as root, let the site create its own folder. Just set the path in your settings.php and then go to 'File system' in the Drupal site (configuration). You can see your path reflected here. Then just save the form and Drupal will create the folders with right permissions.


How can I change the title tag in header of just one page?

You can manage this in template.php file.

function MYTHEMENAME_preprocess_page(&$vars) {
    $vars['title'] = $custom_title;
    $vars['head_title'] = $custom_title;
}

Just put the condition in the page like for specific path, content type etc. and change the title of the page.

function mytheme_preprocess_page(&$vars){
    if (isset($vars['node']) && $vars['node']->type == 'news'){
        drupal_set_title('News');
    }
}


Where should I download libraries for modules through composer?

Install Composer Manager, then you won't need to think about it:

  Composer expects each project (Drupal installation, in our case) to have a single composer.json file listing all required packages. Composer Manager allows each contributed module to ship with its own composer.json file, listing the module-specific requirements. It then merges the requirements of all found modules into the consolidated composer.json file. This results in a single vendor/ directory shared across all modules which prevents code duplication and version mismatches.


There's no such option in drush, all users are sanitized.

As a workaround you can save the user 1 data (or any other user you want) with drush sqlq and restore after sanitization.

Using bash:

user_data=$(drush sqlq "SELECT pass, mail FROM users WHERE uid = 1"| tail -n1)
user_pass=$(echo $user_data | cut -f1 -d" ")
user_mail=$(echo $user_data | cut -f2 -d" ")

drush sql-sanitize ...

drush sqlq "UPDATE users SET pass='$user_pass', mail='$user_mail' WHERE uid = 1"


Rebuild form AFTER ajax callback has run

You could try like this making submit different and callback different and see if it helps.

$form['save'] = array(
    '#type' => 'button',
    '#submit' => array('emtr_shift_plan_form_ajax_submit'),
    '#value' => 'Save',
    '#ajax' => array(
        'callback' => 'emtr_shift_plan_form_ajax',
        'wrapper' => 'postions',
    ),
    '#id' => 'ajax-save-form-values',
);

function emtr_shift_plan_form_ajax($form, &$form_state){
  return $form['positions'];
}
function emtr_shift_plan_form_ajax_submit($form, &$form_state) {

    ddl('ajax submit'); // log the ajax callback is being called

    $form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?

    emtr_shift_plan_form_save($form, $form_state); // save the values

    // This is the point at which I want the form to be rebuilt
}


You want to use hook_form_alter for this to add custom validation to core forms

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_form_alter/7

Create a form_alter_hook in your module and add a validation function to the taxonomy field in your form:

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "<your contenttype>_node_form") {
        $form['#validate'][]='yourmodule_taxonomy_length_check';
    }
}

Then just create a validation function to implement your logic, ex:

function yourmodule_taxonomy_length_check($form, &$form_state) {
    if (strlen($form_state['values']['<taxonomy_field_name>']) > <your value>) {
        form_set_error('<taxonomy_field_name>', 'Term is too long');
    }
}

For your taxonomy_field_name, you want to use the 'name' value of the taxonomy field in your target content type.


Creating multiple views from Entityform Submissions

It should be available, create a view of Entityform Submission and add the filter Entityform Type, if you want. Add the fields that you want to display, make sure you have selected Show : Fields under Format section.

By default entity form module creates two views, Entityforms & Entityform Type List, you can edit the Entityforms view instead creating a new view, if you want.


Why doesn't drupal_render work, but render does?

Once you've done this:

$kickoff_deadline .= '
Between kickoff and deadline
'.drupal_render($table);

The render array is marked as #printed, and won't be rendered again. So this

$after_deadline .= '
After the deadline
' . drupal_render($table);

Will do nothing.

If you take a look at the code for render():

function render(&$element) {
  if (is_array($element)) {
    show($element);
    return drupal_render($element);
  }
  else {
    // Safe-guard for inappropriate use of render() on flat variables: return
    // the variable as-is.
    return $element;
  }
}

You can see it runs show($element);, making it available for rendering again. Which is why this works:

$after_deadline .= '
After the deadline
'.render($table);


How do I create and theme an image link in Drupal 7 Views?

This doesn't directly answer your two questions but should help...

The Views documentation on template overrides doesn't need to be particularly good...as those overrides are self documenting.

Open up any View for edit, open the Advanced fieldset, and click "Theme: Information" at the bottom.

You'll get something like this:

A complete list of every template file available for every field, and the view itself. From there you should be able to experiment quite quickly to find the template name you're looking for.


The easiest way to do it would be to iterate through the array

$options = array();
foreach($project as $option_group)
{
   $options[key($option_group)] = next($option_group);
}

Or, if you can't count on there being only one element in each option group, do:

$options = array();
foreach($project as $option_group)
{
   $options = array_merge($options, $option_group);
}


Adding Profile2 fields to user registration

I had this in my module:

unset($form['profile_memberlist']);

Which is what I needed to do so I could override and theme the way the form elements were presented.  I commented that out but then I got a dual display of form elements, which I was able to disable with the follwing code:

$form['profile_memberlist'] = array(
      '#type' => 'hidden',
);


Using ColorBox to popup "iFrame" shows original page content after the "iFrame" data?

OK, so originally I had tried echo $data; then return;

I then tried: return $data; but that kept showing the header/footer.

I've found that this works well:

echo $data;
die;

Though it's probably not the best way to do it, but it works for the way the module was wrote... should really use the Node/Entity API next time :)


How-to display a product variation field twice (or more)?

You should be able to use template_preprocess_node() to duplicate a field.

I've not run this code and just written it from memory but something like this should suffice:

function template_preprocess_node(&$variables) {

  // Check this is the node type for commerce products
  if($variables['node']['#type'] == 'product') {

    // Copy the existing field to a new item
    $variables['content']['YOUR_FIELD_2'] = $variables['content']['YOUR_FIELD'];

    // Now make any changes to how you want to render the duplicate field
  }

}


How to reset UID number back to default order?

I've found the discussion thread about the issue about why users table is not auto-increment and creating a new sequences table for that purpose.

  This is NOT a full sequences API not at all but it's enough for some uses. actions_aid and simpletest_test_id , that's duplicate code not to mention it belongs to the DB layer. This patch solves that. Further work: we can reuse this for users.uid as that should not be serial because of the known problems. The postgresql folks can create a version which uses proper sequences. The mysql folks can support more than the single serial mysql allows -- like a timestamp and a serial. Sorry for the hasty writeup.

In your case, you just update the value in sequences table to 1.

AND

You need to run ALTER TABLE sequences AUTO_INCREMENT = 1 as well.


Get current taxonomy in template_preprocess_html()

First, check if the route is for a taxonomy term; then, get the term ID.

if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
  $term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
}


How to attach a list of fields to an entity

There are a few possible solutions to what I believe you are asking:

Use a field collection.
http://drupal.org/project/field_collection

It allows you to create a field containing a few fields of information and attach those to a node. I think it is most likely what you are after.

A simple multi-value text field
The simplest option to attach a bunch of names to a node is just to set up a text field with unlimited values. Then you can add as many as you like. But I imagine that's simpler than what you need.

Taxonomy terms
If the values need to relate to each other across the site, use a term reference field with unlimited values and allow your users to create new terms on the fly when they don't exist already.

Content Type
If all of the names you need to add have additional data attached to them, you might need to go down the additional content type and node reference path you mention in your question.

I hope one of those ideas is what you after.


Drupal / Ubercart says it's not saving CC data... then what's "_save_cc_data_to_order"?

_save_cc_data_to_order() is called from 3 places:

uc_credit_order()'s Save operation.  When Debug mode (uc_credit_debug) is on, it saves the full payment details.  When Debug mode is off, it saves the last 4 digits of the credit card number (and all other payment details except the CVV).
uc_credit_order()'s Submit operation.  When Debug mode is on, it saves the full payment details.  When Debug mode is off, it's never called.
uc_credit_terminal_form_submit().  When Debug mode is on, it saves the full payment details.  When Debug mode is off, it's never called.

So, under normal circumstances (when Debug mode is off), Ubercart is storing some sanitized information.  I can't speak to whether this meets your level of PCI compliance requirements, but this answer might be helpful.


Restrict product availability to certain languages/countries in Commerce

I am assuming you have shipping enabled for your site. In that case, you can add a country field to your product display, say "Unsupported countries". And while creating a product, you can chose countries for which you are not going to sell. On checkout, add a rule to compare this field's value and the shipping address and If the shipping country is one of unavailable country, show a message and re-direct to cart page asking them to remove this product from their cart.


How to pass variables to OpenModalDialogCommand

Solved.
Thanks @kiamlaluno.
I was convinced the variables were OK. But after your comment and a fresh look I saw what I was missing:
$this->nid, $this->foo, $this->bar are optional parameters for the UploadForm formbuilder. I was passing only nid and bar, but missing foo, which messed-up things.
So, instead of:

\Drupal::formBuilder()->getForm('UploadForm', $this->nid, $this->bar) //don't need foo

I needed to call:

\Drupal::formBuilder()->getForm('UploadForm', $this->nid, null, $this->bar)

A bit obvious, I'm afraid...


You should consider using Drush (or Bash running Drush) for that. With drush site:install you can set the default language via --locale.

The following command will (re)install Drupal using the expert install profile and set default language to Ukrainian.

drush si expert --locale=uk

Source: https://drushcommands.com/drush-9x/site/site:install/


Online payemnts with commerce: what charges should I expect

you shouldn't pay for the module itself, most gateways have free modules, see https://drupalcommerce.org/extensions/module/payment. When you click on each module the CommerceGuys have been so nice to list transaction fees
I recommend not using a gateway charging more than PayPal. See their fees here: https://www.paypal.com/dk/webapps/mpp/merchant
Laws on online payments differ from country to country, so there isn't one answer to this. To my knowledge PayPal is the closest thing to free. No-one handles payments for free but some don't take setup fees, only transaction fees.
Accepting cards directly on your site requires a lot from you, both in terms of subscription to an organization offering merchant accounts (NETS in my case charges around 300€ for this in Denmark - and have a monopoly on the market). Proper gateways like ePay etc. furthermore charges a subscription plus transaction fees (on top of whoever has given you the merchant status). Finally you need to meet certain criteria about how you handle payments. For Example:

It's illegal to accept payment for something yet to be delivered in DK, so our gateway has to be able to only reserve the money. We're also obliged to offer our terms and conditions on both english & danish. And the list goes on - and varies locally.

I recommend you to keep it simple and easy by using PayPal until your sales are high and your knowledge on these matters have increased significantly.
For your last question I again recommend the drupal commerce module list in my first bullet


Visit admin/config/system/site-information, and set the panel's path as the default home page.


Best practice to have a 'category' fields where admin can choose wich voices the user can choose

You could use a Node Reference field where your 'Voices' are nodes that only administrators can make, that way you can restrict the maximum number of 'Voices' allowed in the Node Reference field settings, and you could turn 'Voices' off by un-publishing them, or if you need the boolean value for the Node output you could just add a Checkbox text field on the 'Voices' node and use the Custom Formatters module to render the Node Reference field out as you wish.


How to get a list of modules implementing hooks?

You are looking for the module_implements function

  Determines which modules are implementing a hook.

Use this function in the devel/php form, for example.

dpm(module_implements('THE_HOOK'));

This way you can see easily if your module implements 'THE_HOOK'.


How do I change the output of a database query from an integer to a string?

The numeric value from the country is essentially a database lookup value to either a Taxonomy Term, a Countries entry ... or whatever module you're using to reference the location. This is typical DB usage, store keys -- not (text) values of the data. If it was a taxonomy term you could do:

function drupalform_form1_submit($form, $form_state) {

  // Lookup the value for the country id key, somewhere, here I assume Taxonomy.
  $country_term = taxonomy_term_load($form_state['values']['country']);
  $d_id = db_insert('drupalform')
    ->fields(array(
      'name' => $form_state['values']['name'],
      'last_name' => $form_state['values']['last_name'],
      'email' => $form_state['values']['email'],
      // Store the country text value, for Taxonomy Terms thats the name value of the object.
      'country' => $country_term->name,
    ))
    ->execute();
   drupal_set_message("Form has been submitted");
}

Assuming your using Taxonomy Terms as countries, and the TID is in only 1 Taxonomy. You would use the same approach with any 3rd party location module.


Is it possible to hide fields on node edit form?

You can use the Field permissions module and disable the edit permission for that field, or you can use hook_form_alter and the #access property, here's an example:
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == "contenttype_node_form") {
    $form['field_foo']['#access'] = FALSE;
  }
}

For a node edit form you must also check if the node exists.


Private file folder outside document root

Looking at the code in system.install that raises this error it just checks if private://.htaccess exists:

$htaccess_files['private://.htaccess'] = [
    'title' => t('Private files directory'),
    'directory' => drupal_realpath('private://'),
];

...

foreach ($htaccess_files as $htaccess_file => $info) {
  // Check for the string which was added to the recommended .htaccess file
  // in the latest security update.
  if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
    $url = 'https://www.drupal.org/SA-CORE-2013-003';
    $requirements[$htaccess_file] = [
      'title' => $info['title'],
      'value' => t('Not fully protected'),
      'severity' => REQUIREMENT_ERROR,
      'description' => t('See @url for information about the recommended .htaccess file which should be added to the %directory directory to help protect against arbitrary code execution.', [':url' => $url, '@url' => $url, '%directory' => $info['directory']]),
    ];
  }
}

At no point does it check if your private file directly is actually inside webroot or not.

This means in your case it's a false warning and you can ignore it, as your right in saying there is no point putting an .htacess file to deny access in a folder outside of webroot.


How to prevent installation to run from UI?

Just specify hidden: true in the info yml file


Hook for module activation and deactivation

The docs say that hook_enable() and hook_disable() are for versions 5-7.


Disable all form elements when doing AJAX

Yes, it's possible. For example, you can attach a .js file to your form and extend the Drupal.ajax object.
Every element which can initiate AJAX submission from a form has its own instance of Drupal.ajax. You can find it in the global object Drupal.ajax. And every Drupal.ajax object has the methods success, error, beforeSend etc.
Here is a simple example to demonstrate the idea:

;(function($) {

  Drupal.testAjax = {
    // Our form
    form_id: 'node-type-form'  //Yes, I tested on my extended node creation form
  };

  Drupal.behaviors.testAjax = {
    attach: function(context, settings) {
      // We extend Drupal.ajax objects for all AJAX elements in our form
      for (ajax_el in settings.ajax) {
        if (Drupal.ajax[ajax_el].element.form) {
          if (Drupal.ajax[ajax_el].element.form.id === Drupal.testAjax.form_id) {
            Drupal.ajax[ajax_el].beforeSubmit = Drupal.testAjax.beforeSubmit;
            Drupal.ajax[ajax_el].success = Drupal.testAjax.success;
            Drupal.ajax[ajax_el].error = Drupal.testAjax.error;
          }
        }
      }
    }
  };

  // Disable form
  Drupal.testAjax.beforeSubmit = function (form_values, form, options) {
    $(form[0].elements).not(':disabled')
                       .addClass('test-ajax-disabled')
                       .attr('disabled', true);
  }

  // Enable form
  Drupal.testAjax.enableForm = function(form) {
    $(form).find('.test-ajax-disabled')
            .removeClass('test-ajax-disabled')
            .attr('disabled', false);

  }

  Drupal.testAjax.success = function (response, status) {
    Drupal.testAjax.enableForm(this.element.form);
    // Call original method with main functionality
    Drupal.ajax.prototype.success.call(this, response, status);
  }
  Drupal.testAjax.error = function (response, uri) {
    Drupal.testAjax.enableForm(this.element.form);
    // Call original method with main functionality
    Drupal.ajax.prototype.error.call(this, response, uri);
  }

})(jQuery);

This approach may seem a little difficult, but it gives you full control over AJAX in your forms.
Another way is to use jQuery methods like .ajaxStart(), because Drupal uses jQuery AJAX Framework.


Using an include file from a different module

The files[] = declarations are only for classes you want to reference at runtime. The declaration should be in the module using the classes (not some other module).

If that doesnt work, look at the xautoload module for D7. Or, simply put include 'includes/Permissions.inc'; into the top your custom module file using those classes/functions -- if you use Features, that's what features (for D7) does; adds an include for features.inc.


Is there any implication/consideration for using the boost module on many different websites running on the same VPS?

Boost has options for how you structure the files, you can use the ip address or the host name.

In your case you would want to stick to the host name so the files are separate. Other than that I see no reason why it shouldn't work. Though I haven't tried.


How to have OutboundPathProcessorInterface change the URL of the loading page

You need three components for this task:

Your outbound path processor UrlRemapOutboundPathProcessor::processOutbound is the first step to get this started.

Second add an inbound path processor UrlRemapOutboundPathProcessor::processInbound to the class similar to Drupal\system\PathProcessor\PathProcessorFiles\processInbound:

  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;

Your path processor won't change the URL in the browser, this is by the way the same with other path processors, for example you can access nodes still by their internal paths (/node/[id]) after you've entered an alias.

So third you need a request event subscriber which redirects the unwanted internal URLs.

An example would be how Redirect does this in RouteNormalizerRequestSubscriber::onKernelRequestRedirect:

 /**
   * Performs a redirect if the URL changes in routing.
   *
   * The redirect happens if a URL constructed from the current route is
   * different from the requested one. Examples:
   * - Language negotiation system detected a language to use, and that language
   *   has a path prefix: perform a redirect to the language prefixed URL.
   * - A route that's set as the front page is requested: redirect to the front
   *   page.
   * - Requested path has an alias: redirect to alias.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The Event to process.
   */
  public function onKernelRequestRedirect(GetResponseEvent $event) {

http://cgit.drupalcode.org/redirect/tree/src/EventSubscriber/RouteNormalizerRequestSubscriber.php

Probably this global redirect catches the internal paths from step one/two as well. If you don't want to redirect all URLs globally or find issues with the alpha version of this module, you can use this event subscriber as example to write  custom code to target only the specific URLs.


Fetching field values only if they exist and applying them automatically as entity labels

As far as I remember, field_get_items() returns an array of items.
In your case something like:

    if (count($address)) {
       print $address[0]['value'];

       if (count($entrance)) {
          print ' ' . $entrance[0]['value'];
       }

      if (count($apartment_number)) {
         print ' ' . $apartment_number[0]['value'];
      }
   }

should work.


Making a Content Type the subpage of a Views page for the sake of Breadcrumbs

For this you will have to use Menu Breadcrumb and Path module

Define your view's path as cars and define path for your Cars type nodes as cars/sample-car

Menu Breadcrumb will do the magic for you to arrange hierarchy of your view and nodes in bread crumb


Displaying only what's entered on the page

On the far right, Under Advanced, for Contextual Filters click add

Add Content ID, select provide default value, select content ID from URL.