Best approach for [back][next] form submitting

You should always use the Form API for forms, unless you really wanted to use the Webform module. The learning curve it steeper but you gain more maintainability (everything is in code from the start) and flexibility. You can create multisteps form with the API. See form_example_wizard.inc and Drupal 7 multistep forms using variable functions (also with Drupal 6) for examples. Another solution, is to use the CTools' wizard API.


How to add some configuration option to vertical tab on content type edit page

Yes, you can add a fieldset to the content type edit form with hook_form_FORM_ID_alter.

e.g:

function MYMODULE_form_node_type_form_alter(&$form, &$form_state) {
    // Define field set in additional settings group
    $form['advanced'] = array(
      '#type' => 'fieldset',
      '#title' => t('Advanced settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#weight' => 10,
      '#group' => 'additional_settings',
    );
    // Add checkbox option
    $form['advanced']['special_option'] = array(
      '#type' => 'checkbox',
      '#title' => t('Use special option'),
    );
    // Set default value from automatically saved config variable
    $form['advanced']['special_option']['#default_value'] = variable_get('special_option_' . $form['#node']->type, 1);

}


How to make full text search case Insensitive

Please follow the below steps:

Click on Configuration > Search and metadata > Search API
Click on Index and go to Processors format . Enable the checkbox Ignore case Makes searches case-insensitive.

Clear the index and reindex the items


Since the date is not coming out as a timestamp, you can to use strtotime. Something like:

$date = strtotime($node->field_program_date[$node->language][0]['value']);
$program_date = format_date($date, 'custom', 'F j, Y');
print $program_date;


How do I use it in a system with 2 PHP-versions?

Drush has an environment variable DRUSH_PHP to set the php executable. You can set it in your .bashrc or directly on the command line:

env DRUSH_PHP=/opt/plesk/5.6/php drush status


How to translate plural strings with Drush?

Between the Drush functions that process text, there isn't such a function, but you can implement one using the code from format_plural(), replacing any call to t() with calls to dt().

function drush_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
  $args['@count'] = $count;
  if ($count == 1) {
    return dt($singular, $args, $options);
  }

  // Get the plural index through the gettext formula.
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
  // If the index cannot be computed, use the plural as a fallback (which
  // allows for most flexiblity with the replaceable @count value).
  if ($index < 0) {
    return dt($plural, $args, $options);
  }
  else {
    switch ($index) {
      case "0":
        return dt($singular, $args, $options);
      case "1":
        return dt($plural, $args, $options);
      default:
        unset($args['@count']);
        $args['@count[' . $index . ']'] = $count;
        return dt(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
    }
  }
}


The YG Agency theme has a link to the prepopulated database from the following page:

https://www.drupal.org/project/yg_agency

Just click on the link that says "Download Demo Site".

You can then import the database into MySQL or the like.


Autocomplete Field in View Exposed Filter

I think you are looking for the taxonomy autocomplete in exposed filter.

 Please find the settings


Git-like way of updating Drupal database

The Configuration module is also a way to store configuration in files rather then the DB. You can then sync configurations by importing the configurations to a new system and pressing a button in the admin area to sync configuration with the newly updated files. there also exists  a Drush command to invoke the update.

  The configuration management module enables the ability to keep track
  of specific configurations on a Drupal site, provides the ability to
  move these configurations between different environments (local, dev,
  qa, prod), and also move configurations between completely different
  sites (migrate configurations) without the use of modules with all
  configuration being owned by the site.

I prefer this approach over Features currently, as this way Features does not attempt to take ownership of any of my files -- or rather become a dependency in my system. I believe you can later uninstall the Configuration module for example and not loose your set configuration values.


Using confirm_form to lead into a batch process

I always do this with a simple submit handler on the form...works a treat:

function my_confirm_form($form, &$form_state) {
  return confirm_form($form, 'Are you sure you want to run this batch?');
}

function my_confirm_form_submit($form, &$form_state) {
  $batch = my_batch_function();
  batch_set($batch);
}


How to uninstall a text format created by a D8 module?

You need to add a dependency in your filter format to the module. Then when the module is uninstalled, the format should get deleted


How to implement stateless authentication

If you tag this as middleware and weight it in your service definition, you can control when this runs. If you search through core you will find the Session and Page Cache also run as middleware. The Ban module in core is also tagged as middleware.
Hopefully this will help point you in the right direction.


Any success using Vagrant + Samba for Drupal Projects?

The git project Druphpet is doing exactly what you want to achieve.
https://github.com/alehkot/druphpet

It's using a Samba server under your guest(Ubuntu) accessible via Windows explorer: "\192.168.9.10\data"

For sure you Drupal website becomes really fast, because your webserver is accessing files locally(inside Linux)

The only problem with this approach is that every modifications of your Drupal code inside your Windows text editor (themes, custom module...) become slower because not local.

The other problem is that when the vm is off or crashed, you can't access your Drupal files anymore.


What are the CSS classes for block instances?

After I created a second instance for a block, I saw that Drupal 8 doesn't create a class to mark it, but rather creates a similar, yet almost identical CSS id (#) name for it which is not zero-based index in this case, rather one-based-indexed.

For example, if the first instance' id is #block-contact-form, the second will be #block-contact-form-2.

If we want to hide only the first instance, we can now do:

media screen and (min-width: 768px) {

#block-contact-form {display: none}

}

If we wanted to hide the second one we would change #block-contact-form to #block-contact-form-2.


views_query_alter change to operator OR for contextual filters and normal filters

As a simple try to help, did you implement hook_views_query_alter(&$view, &$query) as following ?

First, call Views API in YOUR_MODULE.module :

/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'YOUR_MODULE_NAME'),
  );
}

Create a file YOUR_MODULE.views.inc. It seems that with Views, you don't need to put files[] = YOUR_MODULE.views.inc in your module's .info file, as you usually would.

Then implement hook_views_query_alter() in views.inc.

function YOUR_MODULE_views_query_alter(&$view, &$query) {

  if($view->name == 'VIEW_NAME') {

    dpm($query);
    //at this point find the right part to alter and adapt following line
    $query->where[0]['type'] = 'OR';

  }
}

EDIT: If for any reason, you can't override the View with hook_views_query_alter(), Views Filter Harmonizer might fit your need.

  Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering. This small module allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.

Last, check also Views arguments in filters sandbox, or test this patch. Both rely on the same logic, setting a "Global: Null" contextual filters and using it in regular filters. Many people report using it to solve the same And/Or contextual filters issue. Good luck !


How can I execute a custom code on node edit/add page during hook_page_build?

The request_path() function can lookup the current path to determine what page is being rendered.

  if (request_path() == 'node/add/object') {
    // @TODO: Add code
  }
  else if (preg_match('/node\/\d+\/edit/', request_path())) {
    $node = menu_get_object();
    if ($node->type == 'object') {
      // @TODO: Add code for editing node
    }
  }


Display/Print both full content and teaser in node.tpl

I think this would be worked for you.

for teaser use

$rendered_teaser = render(node_view(node_load($node->nid), 'teaser'));
print $rendered_teaser;

and for full use

$rendered_full = render(node_view(node_load($node->nid), 'full'));
print $rendered_full;


You shouldn't need to create a Views relationship plugin, although that might depend on any special cases with your relationship.

I've got two custom entities - a student and a school, which have been scaffolded using Drupal console. The Student has an entity reference field (school_id) which relates a Student to a School but the opposite relationship - Students belonging to a School - isn't generated by default. So to create the relationship that can be used in views, I built this hook method:

/**
 * Implements hook_views_data_alter().
 */
function school_student_views_data_alter(array &$data) {
  $data['school']['student']['relationship'] = [
    'title' => t('Student'),
    'label' => t('Student'),
    'group' => 'School',
    'help' => t('Reference to students of a school'),
    'id' => 'standard',
    'base' => 'student',
    'base field' => 'school_id',
    'field' => 'id',
  ];
}

If you examine the $data array, you'll see all the data for all your views tables. It's a big list with lots of array elements. It'll make sense when you look at it. Set a breakpoint in your views_data_alter hook to inspect it (or use dpr/kpr/dpm).

What we're doing is creating a relationship from one table to another, as this relationship currently doesn't exist. I believe that the array element names 'school' and 'student' should refer to the table names we are dealing with. We're creating a relationship data alter and so 'relationship' is the child array element we need to create. Below that is just configuration.

title refers to the relationship title in your "Add relationship" modal window

label is the default name of the relationship when you create it

group is the name of the relationship group your new relationship belongs to

help is helper text/description for the relationship

This next bit is important!

id refers to the the name of the views relationship plugin you are needing to use. Because I'm not creating a complex relationship (basically a simple inner join), I'm using the Standard views relationship plugin (found in Drupal\views\Plugin\views\relationship\Standard).

Finally, base is the base table we're creating the relationship from.

base field is the join field in our base table and finally field is the field in the school table we're creating our join to.

So in use, views will create a join that in SQL looks like:

INNER JOIN {student} student_school ON school.id = student_school.school_id

Hopefully this makes sense and helps you or others out.


Are node title & body instances update-able through the field API?

The Title is not a field unless you're using the Title module.
That's why your first call doesn't work.

Body should work, unless you've deleted the field (can you see it on admin/structure/types/manage/article/fields?)


Re-writing SQL statement in Drupal dynamic queries

Have you turned down the error_level? because if you get nothing back from Drupal then this typically means the query executed successfully but that no results were found. Perhaps check the Reports->Recent log messages for any SQL errors logged instead. This information should help you troubleshoot future Drupal SQL endeavours.

Anyway, looking over the code, I don't think this is correct:

$subquery->fields('loc.entity_id', array('eid'));

and should probably be:

$subquery->fields('loc', array('entity_id'));

or if you want to give the field an alias, use addField:

$subquery->addfield('loc', 'entity_id', 'eid');

I've just run a similar query on a fresh database (so no custom fields) and set that fields() call correctly, and this seems to get results back:

$bundles = array("page", "blog");

$query = db_select('node', 'n');
$query->addField('n', 'title', 'title');
$query->groupBy('n.nid');

$subquery = db_select('field_data_body', 'data');
$subquery->distinct();
$subquery = $subquery->fields('data', array('entity_id'));
$subquery = $subquery->condition('data.bundle', $bundles, 'IN');

$query->join('field_revision_body', 'rev', 'n.nid = rev.entity_id');
$query->addExpression('GROUP_CONCAT(rev.bundle)', 'mybundles');
$query->addJoin('INNER', $subquery, 'IDS', 'n.nid = IDS.entity_id');

$result = $query->execute();

dpq($query); // Let's look at the query
dpm($result->fetchAll()); // Let's see all the results

Note, you'll need the devel module installed to use the dpm() and dpq() functions. Hope that can help!


You can relatively easy do that by adding a views contextual filter for the node id (nid) with the following configuration:

When the filter value is NOT in the URL: Provide default value -> Content ID From URL
When the filter value is IN the URL or a default is provided: Specify validation criteria -> Your CTs list
Filter value format: Node ID
The flag relationship used should be: by any user

Of course you can use that view as a block and place it wherever you like.


Views: expose filter - filter out results between a specific set of dates

You should be able to add a view filter that uses the operator of "Is not between" when referencing a date.

You can have multiple filters for the same value, so you could allow people to search for dates, but have a second filter that removes results between X and Y


How to make a webform block specific template?

You need to copy (not move) sites/all/modules/webform/templates/webform-form.tpl.php to sites/all/themes/yourTheme/templates/webform-form-nid.tpl.php (obviously replace yourTheme and nid) and clear caches.


Move a taxonomy page field to a different region

You can approach this in UI, Twig or PHP:

UI

You can create a View (show Taxonomy Terms) with display "block" and add "Term ID" as Context Filter, see this example for Users: How to move the user account/Profile 2 information from the content region to a sidebar region

Twig

Install Twig Tweak and place the field in a twig template:

{{ drupal_field('field_name', 'taxonomy_term') }}

PHP

Prepare the taxonomy term entity in a preprocess hook, see print custom image field for taxonomy page (page--taxonomy.html.twig) template


Trying to get an "About the author" view to work on a multi user blog (contextual filters)

You don't need to create separate content types in D7, You are able to attach fields to the user directly (admin/config/people/accounts/fields). If you need more flexibility, use the Profile2 module.

If you just add fields to the user, you can create a new block view of users. Under "Contextual Filters" (which is under Advanced on the right side), add a filter of User: Uid, set it to Provide default value, with a type of User ID from URL, and check the checkbox for Also look for a node and use the node author.

Then add the fields normally as you see fit.


If no regions are specified in the theme, the core provides defaults itself.

From the docs page: https://www.drupal.org/docs/8/theming-drupal-8/adding-regions-to-a-theme

  Default Regions:

  page.header: Items for the header region.

  page.primary_menu: Items for the primary menu region.

  page.secondary_menu: Items for the secondary menu region.

  page.highlighted: Items for the highlighted content region.

  page.help: Dynamic help text, mostly for admin pages.

  page.content: The main content of the current page.

  page.sidebar_first: Items for the first sidebar.

  page.sidebar_second: Items for the second sidebar.

  page.footer: Items for the footer region.

  page.breadcrumb: Items for the breadcrumb region.

  If your theme does not declare any regions Drupal will assume this set
  of defaults. These regions correspond with what the default
  core/modules/system/templates/page.html.twig file expects, as well as
  two hidden regions, page_top, and page_bottom - you don't need to
  declare these final two if you override the defaults, however the {{
  page_top }} and {{ page_bottom }} Twig variables should be retained
  in the html.html.twig template.


How do I create additional fields in module.install?

Instead of creating the node type and fields by hand in code, you should use the features module which does the same thing, but has support for a bunch of other things as well, like reverting changes made to what is saved in code.


Single on/off checkbox default value not work

I tested it and worked for me:

$form['field_user_flag'][LANGUAGE_NONE]['#default_value'] = 1;

You can also set a default value of this field (in field settings in field managment).


Whenever in drupal documentation it says to use "hook_" it means to replace "hook_" with the name of your module or theme.  Often on this site, you'll see "mymodule_" used as an example.  When you see "ENTITY_TYPE" in a hook description that is usually going to be "node" "taxonomy_term", "user", etc., it is not the bundle, or subtype of an entity.  Drupal nodes are labelled as "Content Types", which is synonymous with bundle.  Bundle is the term used across many different entities and is a backend term, while they are labelled different things on the front-end for different entity types.  For nodes, they are "Content types", for taxonomy, they are "Vocabularies".

You wouldn't want to use the bundle in your hook if it's looking for "ENTITY_TYPE", so "persbericht" ("press release") isn't correct.  You'd want to use node.

Themes can only implement a small number of hooks, such as alter hooks.  They can't implement CRUD operations.  So you'd want to put this in a custom module.

use Drupal\node\Entity\Node;
/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function mymodule_node_insert(Node $node) {
  if ($node->bundle() == 'press_release') {
    $copy = Node::create([
      'title' => $node->getTitle() . ' copy!',
      'type' => 'article',
      'status' => 0,
    ]);
    foreach ($node as $key => $value) {
      // Copy values from all fields (fields start with "field_").
      if (strpos($key, 'field_') === 0) {
        if (isset($copy->{$key})) {
          $copy->{$key}->setValue($node->{$key}->getValue());
        }
      }
    }
    $copy->save();
  }
}


Render a custom module inside an existing node

You can implement hook_node_build() in a custom module to add or alter elements when a node's content is by assembled for viewing, right before rendering.

function MODULE_node_build($node, $view_mode, $langcode) {
  // Only do something if the node is rendered on its own page, in full.
  if ($node->type == 'MODULE_type' && $view_mode == 'full' && node_is_page($node)) {
    $node->content['MODULE_stuff'] = array(
      // Insert render array content here
    );
  }
}

For sorting, you can add a #weight property in the element(s) added to $node->content. But a nicer solution is to implement hook_field_extra_fields(), so you can position the added element(s) using the usual Field UI.


Views are disappearing randomly; always needing to flush caches

Thank you so much to kladria on IRC #drupal-support for helping me through this one!

After using a debugger to step through the code, I saw that my implementation of hook_views_default_views() was not being called. The problem I was having was that the function was in the wrong file. Originally, I had the function "MY_MODULE_views_default_views()" in the file "My_MODULE.views.inc", and it is supposed to go in "My_MODULE.views_default.inc". That "_default" made all the difference for it to be auto-loaded correctly.

So far, there has been no more needing to flush caches, and the views haven't disappeared. I'm pretty sure this did the trick.


I fixed it by changing the folder name test1 in sites to test1.ashokks.com, following what reported in this question.


Is adding indexes to a Drupal database safe?

Yes, it could result in problems.

If a module wants to do something with the column on which you have added an index, it will remove it's own indexes and then do whatever operation it intends to do.

What exactly will happen will depend on your database type and the actually executed operation. For example, a rename of the column will work fine with MySQL, but will fail on PostgreSQL. But if it tries to delete that column (maybe after migrating data to a different table/colun), it will fail.

The chances that this will happen are relatively low, at least for minor updates (does depend on the actual module however. I usually don't add any changes which could break something to minor releases), but it is possible.

My suggestion would be that you try to work together with the module maintainers. If the problematic query/ies are from the module itself, then the maintainers will probably happily add the indexes, if you provide a patch. Provide DESCRIBE output of the problematic query/ies before and after adding the index. Also provide a patch that updates the schema (include an update function to set it for existing installations).

Someone who is actively working on performance related things and does the above really well is catch, here is an example: http://drupal.org/node/983950


How do I assign a role after user clicks a link?

You can use Rules for that. The configuration can be({{}} are placeholders, do not use on the real values):

React on event "Content is viewed"
Condition: Data comparison (Parameter: Data to compare: [node:nid], Data value: {{NID from the node you're using to trigger this role activation}})
Action: Add user role (Parameter: User: [site:current-user], Roles: {{the role you want to add}})


Thumbnail preview not showing in Video Embed Field Module

Did you check the access permissions for your thumbnail images


How to show Search API search box? No block available, nothing from

Maybe not the best option, but to get a usable Search Block from the Views module (that includes the Search API Views submodule), you need to activate the "Expose Form >> Exposed form in block" option in your Views advanced configuration. This is what it looks like:

Good luck!


Should I activate feature modules on my dev site?

Features allows you to assure that the configuration that is described in code (in the features that you the module Features generates) is the current configuration in the DB. If you enable a feature that describes exactly the same configuration that you have in your site no changes are made.

Features is a powerfull way to move configuration between sites (dev, stg and live, between devs sites, etc). I don't understand exactly your setup, but I think you can enable them.

Features help you to know if some configuration change needs to be moved to producton. For example: you start with your features in a clean state (default state) in production and in your dev site. If you make a configuration change in your dev site implementing a new functionality you can see that the feature is in overwritten state: this means that you shold take this configuration change to production when new code is deployed. You can do it by hand, or regenerating the feature and deploying it to production.


So add relationship "your_flag"

and in Sort criteria delete default Content: Post date (desc)

and add Flags: Flagged time

PS maybe i don't understand you, why you need in views this show? not in teaser node?


In this link you will see that field method doesn't support alias. Instead supports,

$query = db_select('node', 'n');

But to have alias for fields follow this link which will be,

$query->addField('n', 'name', 'label');
$query->addField('n', 'name', 'value');


How can I get the Contact Form "Manage Display" Settings programmatically?

I was able to retrieve the order of the 'mail' display.
The secret was in the ->getComponets() function in this part:

$display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entityType . '.' . $bundle . '.' . $displayMode);
$displayFields = $display->getComponents();

the final code looks like this:

/**
 * Implements hook_mail_alter().
 */
function contact_plus_mail_alter(&$message) {
    if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
        $message['send'] = false;

        $siteName = \Drupal::config('system.site')->get('name');
        $siteMail = \Drupal::config('system.site')->get('mail');

        /** @var \Drupal\contact\Entity\Message $contactMessage */
        $contactMessage = $message['params']['contact_message'];
        $entityType = $contactMessage->getEntityType()->id();
        $bundle = $contactMessage->bundle();
        $contactForm = $contactMessage->getContactForm();
        $form_title = $contactForm->label();
        $recipients = implode(',', $contactForm->getRecipients());
        // Data for the email
        $data = [
            'title' => $form_title,
            'today' => (new \DateTime('now', new \DateTimeZone('UTC')))->format('m/d/Y'),
            'fields' => [],
        ];
        // get the 'mail' display mode if defined
        $viewModes = \Drupal::service('entity_display.repository')
            ->getViewModeOptionsByBundle(
                $entityType, $bundle
            );
        $displayMode = array_key_exists('mail', $viewModes) ? 'mail' : 'default';

        // get display field settings (weight, id, etc...)
        /** @var \Drupal\Core\Entity\Entity\EntityViewDisplay $display */
        $display = \Drupal::entityTypeManager()
            ->getStorage('entity_view_display')
            ->load($entityType . '.' . $bundle . '.' . $displayMode);
        $displayFields = $display->getComponents();

        // put the fields info in the email data
        foreach ($displayFields as $key => $fieldConfig) {
            $field = $contactMessage->get($key);
            $fieldDefinition = $field->getFieldDefinition();
            $data['fields'][$key] = [
                'label' => $fieldDefinition->getLabel(),
                'info' => $field->getValue(),
                'display_options' => $fieldDefinition->getDisplayOptions(),
                'weight' => $fieldConfig['weight'],
            ];
        }

        // order by weight
        function compare_weight($a, $b) {
            return strnatcmp($a['weight'], $b['weight']);
        }
        uasort($data['fields'], 'compare_weight');

        // send the email for the responsible
        $emailSender = new EmailSender($siteName . '<' . $siteMail . '>', $recipients, $form_title, 'my_theme', $data);
        $emailSender->createAndSendEmail();

        // send a copy to the person who filed the form
        if (isset($data['fields']['field_email'])) {
            $email = $data['fields']['field_email']['info'][0]['value'];
            $emailSender->to = $email;
        }
        $emailSender->createAndSendEmail();
    }
}

Hope it helps someone.


Theming views and overwriting the default file upload display

You don't need to use a template or get your hands dirty with code.

Just add the field to the view twice.  Hide the first field from display, but change the formatter to "URL to file".  Rewrite the output of the second field to "Download PDF".  On the second field, select output field as link and assuming your field is named 'pdf', make the path [field_pdf].


How to feature-ize multiple vocabularies applied to multiple content types?

An important thing to keep in mind is that things start getting messy when multiple features try to export the same thing. For example, have multiple features that export the same Taxonomy vocabulary. When this happens, best case scenario is that you have to update all the features every time you make a change to the vocabulary. Worst case is, well, worse than that. I've heard some horror stories, but never tried it personally; I do my best to keep proper separation.

In your case, I suggest separating the content types and vocabularies into separate Features. For the vocabularies, you can either put them all in one feature or split them up into separate features, whichever you prefer. I tend to keep all the vocabularies in a single feature, which I think makes sense for your situation as well. For the content type Features, you can now list as a dependency the Features module defining the vocabulary used by that content type.


In fact in Drupal 6 there is no need to select the parent from the drop box anymore: You drag your field under your fieldset and push it to its right.

As result, you get this.


Put link/button in email to reply to sender on website

I don't think you can do this from webform alone.  I would create a custom form (using Form API in a custom module) with a path that includes a parameter to identify the original webform submission.  Something like /quote-response/{webform-submission}.  The "response form" then queries the webform submission to get the email of the person who submitted the original quote request.  Keep in mind if this route doesn't require any authentication, you could be opening yourself up to bots / malicious users, so I recommend implementing some additional security / verification.


What am I doing wrong with accessing this array element?

Install the development module and do dpm($form, 'the form'); and dpm($form_state, 'my form state'); in your form alter function. I believe you'll see that $form_state is "flattened" to only the innermost values of your form array.

So, the saved array key exists, not [cookie][saved].

In general try to make use of this convention, or assumption by drupal. Usually your FAPI form has fieldset(s) as outer keys (not passed into $form_state at all, they only affect the appearence of the form) and input values as inner keys. So rename your 2nd key from saved to cookie_saved.

If you really (for some reason) want the ['cookie']['saved'] to be in $form_state just as-is -- perserving the hierarchy of information. You would want to set the #tree property of cookie in your FAPI array.

See these 2 resources of information:

Legacy drupal page talking about FAPI usage
current FAPI quickstart guide.

Both are relevant for background information how FAPI usage and how its evolved to meet our needs as developers. Search for #tree and #parents within the linked documentation pages.


1) When you are adding a new node, check the text format option under the Body field. Ensure that it has not been set to "Filtered HTML" (if you are using the Standard profile) or some other text format that will filter out HTML tags outside a preset whitelist. However, this doesn't explain as to how the image shows up on re-save.

2) Disable your custom module and try once. Ensure that it is not affecting anything. Because, Insert, by itself, seems to be okay. Just checked out this demo.


Show Filename of uploaded files in "Field Collection" Field

You can create a search display using Display Suite (https://drupal.org/project/ds). By enabling DS and DS Search you will get some search options done through DS.


Webform multipage - different page.tpl for different page

I don't think you can do this on page level. Can't you use form templates? In that case you could add your own theme functions. Here's an example:

/**
 * Implements hook_theme().
 */
function YOUR_TEMPLATE_OR_MODULE_theme() {
  // Add our own webform theme function, copied from
  // webform_form in webform.module.
  $theme = array(
    'webform_form_page' => array(
      'render element' => 'form',
      'template' => 'templates/webform-form',
      'pattern' => 'webform_form_[0-9]+_[0-9]+',
    ),
  );
  return $theme;
}

/**
 * Implements hook_webform_form_webform_client_form_alter().
 */
function YOUR_TEMPLATE_OR_MODULE_webform_form_webform_client_form_alter(&$form, &$form_state) {
  // Check if we are on another page then 1 in a webform.
  if (isset($form_state['storage']['page_num'])) {
    // Add our own theme including the page number.
    $form['#theme'][] = 'webform_form_' . $form['#node']->nid . '_' . $form_state['storage']['page_num'];
  }
}

You should now be able to create your own tpl file per form page. It would look something like this: webform-form-626-2.tpl where 626 is the node id and 2 is the page number. For the first page you should just use webform-form-626.tpl.php so it also functions as a fallback template.

I haven't tested this so you might need to tweak it a bit but I hope this puts you on the right way.


Forgot to do config ignore before building webform. How to correct it and ignore the webform from the export?

Thanks all for your reply and apologies for my late response. Yes, I am using config_ignore and config_split module. I just added webform to config_ignore and then deleted the files from the git repository so next time they will not be added to git. Worked.


Using Rules to Schedule Publishing/Unpublishing of Content

I've had a great experience using Scheduler to schedule publishing and unpublishing of nodes automatically.

Although this doesn't specifically answer your question because it doesnt involve rules, its worth mentioning :)


Should I put my site on maintenance mode before using "drush sql-dump"?

According to Moshe's answer in advantages of drush bam vs. drush sql-dump / drush sql-connect, the answer is no.  drush sql-dump does the right thing and will result in a consistent backup.


You can do this with the Drupal 8 Migrate API, which allows for setting up mappers from JSON: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview


Should I define all my variables in the module.settings.yml file?

Talking of the configuration file in config/install, its purpose is setting the default values for the configuration used from the module.

Deleting its content could probably not make much difference if the default values are FALSE, NULL, or an empty string. In the other cases, its content would make a difference.


That approach won't affect the column type or size as I get you need to make it store more chars.

You could do hook_update_N() that execute a sql query to change the field type and size.

Then yo have to change field settings see


Views slideshow - 3 items per slide - how to center them?

#views_slideshow_cycle_teaser_section_eunic_members-block {
margin: 0 auto;
}


How Specify the class name of our columns in Responsive Grid View?

For Wrapper do not use <div> you need to use a name. Ex: magazine_grid_wrapper


How to group li element via using Drupal.behaviors?

I am not completely sure I understand what you are trying to do - I am assuming the html is some kind of Drupal menu you are trying to add some kind of dropdown/flyout action to?

I am not sure whether you want to be doing all this DOM manipulation on mouseover/mouseout either? At least I think that's what you are doing from looking at that code snippet.

Taking your html example at face value, this bit of javascript should do the job of splitting it out into 'columns':

var $list = $('ul'),
    $items = $('li', $list),
    column_counter = 1,
    $current_list,
    items_to_column=6;

$items.each(function(index,item){
  if (index%items_to_column==0){
    var new_column = $("

").appendTo($list);
    $current_list = $('ul', new_column);
    column_counter ++;
  }
  $current_list.append( $(item).detach());
});


Workflow, Multistep, and "Save" vs. "Done"

You could use the Button Field module and rules.


Can't change default settings in foundation theme

Sorry about the noise... after a couple of hours of struggling I removed these lines in the info file:

stylesheets[all][] = css/foundation/foundation.css
stylesheets[all][] = css/foundation/normalize.css

... and everything began to work. So never mind this question.


How do I convert a Drush make commit-level dependency into Composer?

The location you're defining it at is wrong. When defining your own packages, the version tag is used to target branches or tags. If you want specify a commit-level project requirement, do it in require object where you're specifying your requirement in the  dev-${BRANCH}#${COMMIT_HASH} format.

In repositories:

{
  "type": "package",
  "package": {
    "name": "hybridauth/hybridauth",
    "version": "master",
    "type": "drupal-library",
    "source": {
      "url": "https://github.com/hybridauth/hybridauth",
      "type": "git",
      "reference": "master"
    }
  }

In require:

"hybridauth/hybridauth": "dev-master#38f0735",


Circular dependency on base fields' module

Since the dependency is purely on the reference field, we could add the target_type later. For example, setting the target_type at the bundleFieldDefinition wouldn't throw the install's error and set the right target_type.
So the baseFieldDefinitions would be
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  ...
  $fields['store'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Store'))
    ->setDescription(t('Select the store the contact is part of.'))
    ...
}

And the bundleFieldDefinitions would be
public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  $fields = parent::bundleFieldDefinitions($entity_type, $bundle, $base_field_definitions);
  $fields['store'] = clone $base_field_definitions['store'];
  $fields['store']->setSetting('target_type', 'custom_store')
  ...
  return $fields;
}


May be because of cache that might cause

Check if you installed jquery_update module
in themes info check if there you have declared jquery

3.check if in any module hook_init() you are adding your js with weight.

if you install jquery update module you dont need to add jquery plugin in info file

if you have any clarification regarding the js weight and so on read the following links will be helpful

https://www.drupal.org/node/756722

https://www.drupal.org/node/304255


How should I implement an alternative file upload?

If you want it to use http://filepicker.io's storage, it will definitely be link field. It's your own design decision if you will just add a widget (that's what I would do) or clone it and add that widget to a clone. However, don't expect seamless work from images on your own domain and images stored away of it - you can't really resize, rotate, crop, generate thumbnails, and service may become paid one with only short notice (and unavailable without any notice at all).


How to see Database logs in Devel module

You need to give Devel permissions to the user from which, you are logged in, and want to view logs.Go to People >> Permissions and give Devel permissions to the role you want to.

However, giving Devel permissions to anonymous user is a security risk. So, avoid that.


I Uninstalled the expire module and the Cron cache module returns to work as usual


Using Contextual Filters to Filter "Content: Published"

Out of the box I don't believe this is available. I have a similar use case however I am also using Workbench Moderation. I'm using the moderation state as the contextual filter and using setting a standard filter of current revision as true. This allows you to target a specific moderation state in your view, published being one of them. It could get irritating if you end up with a lot of moderation states and have to target each of them specifically but my use case requires me to get either just published, or all content regardless of published or not.


A cronjob should not have to be run by a specific drupal user. It sounds just like a maintenance task that should run sometimes to do something (send a part of a  mail queue, clear some part of cache or whatever).

In some installs (all of mine, for example) run crons via drush/linux cronjob. cron_safe_threshold is set to 0 (never).

  Typical tasks managed by hook_cron() are database maintenance,
  backups, recalculation of settings or parameters, automated mailing,
  and retrieving remote data.


You can do by using these modules:

Custom Breadcrumbs

  Many new features have been added including support for Views, Panels,
  Taxonomy vocabularies and terms, paths, and a simple API that allows
  contributed modules to enable custom breadcrumbs for module pages and
  theme templates. These are implemented using optional, independent
  submodules that depend on the main Custom Breadcrumbs module.

Path Breadcrumbs

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path Breadcrumbs module helps you to create breadcrumbs for any
  page with any selection rules and load any entity from the
  URL!


The Read more link is added by node_build_content(), while Add new comment is added by comment_node_view(); other links like those can be added by any module implementing hook_node_view().

So, to answer your question, there aren't theme regions you could use to add links where you see Add new comment, and you don't add them in page.tpl.php. You need a module implementing hook_node_view(), for example using the following code.

function mymodule_node_view($node, $view_mode, $langcode) {
  $links['socialmedia_twitter'] = array(
    // Depending on what the token returns, you need to use one of these lines.
    'title' => token_replace(' [socialmedia:sm-twitter_username]'),
    'href' => token_replace(' [socialmedia:sm-twitter_username]'),

    'attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => format_username($node)))),
  );

  $node->content['links']['mymodule'] = array(
    '#theme' => 'links__node',
    '#links' => $links,
    '#attributes' => array('class' => array('links', 'inline')),
  );
}

Rather than calling token_replace(), I would look at the module code, and see which function generates the token, and use it instead of calling token_replace(), since you are replacing a single, static, token you already know which one it is.
In any case, you need to check the code implemented by that module, as some token require an extra parameter passed as $data; without that, they don't work, or they don't produce the expected output.

In a theme, you would implement hook_node_view_alter().


Can't install modules in a sub site --- Seeing Ajax error

Here is a list of items to check:

Clear all caches (it doesn't hurt, and occasionally helps solving various issues): if you get a WSOD while doing so, it indicates memory shortage.
Try running update.php (by typing an URL like http://www.yourdomain.com/update.php): if you get a Fatal error like "Allow memory size of ... bytes exhausted", it indicates memory shortage.
Verify if it is a memory shortage issue by increasing the memory a bit to check if there is any difference.

Assuming this is NOT a multi site, consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

ini_set('memory_limit', '100M');

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

If needed, refer to https://www.drupal.org/node/207036 for more details, eg if such 'ini_set' is not yet included in your settings.php file. As mentioned in that link: "Locate the PHP settings section and add that line at the end of that section".


Node's teaser view mode has extra "panels-default" markup/wrapper/classes

Copy bootstrap-panel.tpl.php from base to main and configure it per requirements.


Autocomplete term widget (tagging) - Insert as child

I have done some research on this as we use the Autocomplete Deluxe module for our client's sites. Unfortunately I see no preexisting solution and I think you will have to create your own.

This could be quite visually problematical. How do you display this in a auto complete field: Prefixed with all its parents? with a parent attribute type key?

I agree that this could be quite useful as this would eliminate the need to give a non-technical user admin access to taxonomy more and more. But I think this would be better achieved with a custom coded mix of Autocomplete Deluxe and Hierarchical select


Takes too long to render a product display with 6000+ variations

Didn't find a proper solution to increase the performance or, at least a clean solution. So I decided to create a module that basically holds an alternative view formatter to the "Add to cart" that comes with Drupal Commerce.

You can find the module here: https://www.drupal.org/sandbox/marcofernandes/2705035

Basically it's a "clone" of "Add to cart" view formatter but it avoids iterations over all variations and field options. It's not perfect but it fits my needs (variations for all possible combinations). I'll keep it as a sandbox until it reaches a more mature state (it lacks some validations and, probably it misses some code styling).


8.4.4 CKEditor Link & Unlink Buttons suddenly missing

I figured out the issue.  Apparently something changed in the Drupal 8.4.4 update that caused the scripts related to the link/unlink buttons to work longer than usual, which was causing a PHP timeout exception (when checking the browser console it gave an HTTP Result Code: 200 error, which apparently happens regularly with Drupal).  So in my settings.php file I increased the timeout by adding the line:

ini_set('MAX_EXECUTION_TIME', 7200);

You can also configure this in your host settings.


Unit price showing in purchased entity (Item) field

Workaround fix: In structure/views/view/commerce_cart_form Change to hidden field: (order_items: Order Item) Order item: Purchased entity (Item) [hidden]

Add field (order_items: Order Item) Order item: Title (Item) for line item display.

Still researching Purchased entity problem.


There's a lot of moving parts here. I'm going to make some assumptions. First, you have nodes. Each node has 1 image on it (through a file / image field).

You then want to display the nodes in some sequence order (maybe through a slideshow or something).

Each time you look at the view, you should only look at one "flip book" at a time.

For this you need to use a Views "Contextual Filter" (or "argument" in the older language). You would build your page view to pull in all the images of all the nodes. You would probably set your views to display as a views_slideshow or something.

The first "contextual filter" your view will have is the term (I'm assuming from taxonomy) that you want to build the flip book from. So, you might go and view yoursite.com/flipbook/37 (where 37 is the term id that all the image nodes are tagged with for this book).


drupal_system_listing() is the function that handles this.

According to its inline documentation:

// Duplicate files found in later search directories take precedence over
// earlier ones, so we want them to overwrite keys in our resulting
// $files array.
// The exception to this is if the later file is from a module or theme not
// compatible with Drupal core. This may occur during upgrades of Drupal
// core when new modules exist in core while older contrib modules with the
// same name exist in a directory such as sites/all/modules/.

And as far as I can tell from the function, it searches directories in the following order:

/profiles
/sites/all
/sites/[domain]

So each directory in the list above would override matches from previous directories.

Having modules in the /sites/default directory is not normal, so I'm not sure what the expected behavior would be. My guess is that it depends alphabetically on your [domain] directory name.


How to have CCK "Select list" field on my content type?

You have to enabled Option Widgets, as well as Number and/or Text.

Create a new field by going to admin/content/node-type/%content-type%/fields  (where %content-type% is the machine name of your content type)

Create a new field.  If you enabled Text module, you have the option of Text.  If you enabled Number, then you have the option of Decimal, Float and Integer.

Select the Operations you want

Clicking Save will take to the Field setting page. Scroll down to the bottom and type in the allow values for your option widget.

And you are done.


If you make a checkbox required it should force the user to check it (if you have an up to date version of drupal core). See the issue here where that was fixed.

For older versions of drupal there was the checkbox validate module.

As for adding javascript in your info file. That will add it to every page.
So either the page it doesn't work on is using a different theme (and therefore a different info file), or there is a javascript error on the page that is preventing your code from running.

Check your page for javascript errors.

There is also the legal module, which allows you to set terms and conditions that the user has to agree to when signing up. The module handles the checkboxes.
It might not be right for you but it is another option.


I figure it out, I have to choose 'Current User's Language' for Field Language option and enable the language detection in the URL, and I added a filter for the field language and expose it, that way i passed the locale in the URL and passed my filter as query string and got my result.


How to include book traversal links on a custom twig template page

Alas, there is no block for this; the book navigation links are hacked on to the node view in core.

From core/modules/book/book.module:

/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $book_node = Node::load($node->book['bid']);
      if (!$book_node->access()) {
        return;
      }
      $build['book_navigation'] = [
        '#theme' => 'book_navigation',
        '#book_link' => $node->book,
        '#weight' => 100,
        // The book navigation is a listing of Node entities, so associate its
        // list cache tag for correct invalidation.
        '#cache' => [
          'tags' => $node->getEntityType()->getListCacheTags(),
        ],
      ];
    }
  }
}

The good news is that this should work with custom templates as long as you are using the full view mode.

I have a custom node template and I still get the navigation links on my books at the bottom of the content.  (Unfortunately, whether I want them there or not-- as per the above code, they are forcibly added and there is no UI to control them.)


Overriding the function of a module in another module

If you want to use a different menu callback, you can implement hook_menu_alter() to change the menu callback. Suppose you want to override the menu callback Drupal defines for search, you could use the following code.

function mymodule_menu_alter(&$items) {
  if (isset($items['search'])) {
    $items['search']['page callback'] = 'mymodule_search_view';
  }
}

From mymodule_search_view() you can call search_view() without first including the file containing it, as that is done from Drupal before calling the menu callback.

Similar code could be done if the menu callback is returning a form, with the exception that, instead of changing the page callback (which probably is drupal_get_form()), you would change the page arguments to use as first argument the callback name of the function returning the form array. Rather than doing this, you should implement hook_form_alter(), and to hide the not necessary form elements with $form['element']['#access'] = FALSE', and not withunset($form['element'])`.

As for replacing a function that is called from a hook, what can be done is removing the hook implementation that calls that function, and replacing it with a different implementation. It is possible only with Drupal 7, and it must be done carefully. (I will explain why right.)
Suppose you want to change the function called in menu_node_update() (the implementation of hook_node_update()) from menu_node_save() to mymodule_node_save(). You could use the following code.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    unset($implementations['menu']);

    $implementations = array('mymodule' => group) + $implementations;
  }
}

function mymodule_node_update($node) {
  mymodule_node_save();
}

In this way, menu_node_update() would not be invoked anymore, but mymodule_node_update() would.

Normally, modules that depend from a hook implemented by another module don't check if that hook is executed; they check the module is enabled (and assume the hook is invoked), or they add that module as their dependency. Avoiding a hook is executed could cause problems to other modules which could be difficult to track. If it is really necessary to avoid a hook implemented by another module is executed, you should first check on a test site that all is working as expecting. Bear in mind that future Drupal version could break your code, and the code you are writing should be tested on future Drupal version too (when they are available).


How to bypass CAPTCHA during Behat functional testing?

Using the API Driver you can, as you say, modify CAPTCHA After threshold and restore it at the end of test, but you need to execute tests in the same machine.

If you want to do it form another machine you have to set up a way to alter that variable from outside. You can define a hook menu that alters that variable, in a dev module that will not be enabled in production site. You can also set up a drush remote command that modifies the threshold in th remote machine and restores and the end of the test. You can add this drush command in the script that lauchhes behat tests or even inside behat in a behat hook.


How to sort the language detection methods

Well I think you are doing just fine, and don't get obsessive over this, it's ok!

the URL thing is the most important and should be always on top, I think session should be second since it can be generated via a request or parameter.

User I'm not sure since mostly users don't pay attention about their language preferences while registering on a webiste.

past these steps the rest doesn't really matter that much, but I'd put Browser the last one since it seems it can vary quite easy with plugins/extensions.


Create a simple custom REST resource in a custom module and within the resource you can return a list of views and other relevant information

Here is a get() function that returns views that are enabled and their displays

/**
 * Responds to entity GET requests.
 * @return \Drupal\rest\ResourceResponse
 */
public function get() {

    $entity_ids = \Drupal::service('entity.query')
        ->get('view')
        ->condition('status', TRUE)
        ->execute();

    $views = [];
    foreach (\Drupal::entityManager()
        ->getStorage('view')
        ->loadMultiple($entity_ids) as $view) {

        $displays = [];
        // Check each display to see if it meets the criteria and is enabled.
        foreach ($view->get('display') as $id => $display) {

            // If the key doesn't exist, enabled is assumed.
            $enabled = !empty($display['display_options']['enabled']) || !array_key_exists('enabled', $display['display_options']);
            if ($enabled ) {
                $displays[] = [
                    'id' => $display['id'],
                ];
            }
        }
        $views[] = [
            'view_id' => $view->id(),
            'displays' => $displays,
        ];
    }

    $response = new ResourceResponse($views);
    return $response;
}

You can modify the views array using the for loops to display any information that you find relevant to your task.

Here is a working demo module that I did for the sake of this exercise


By the sounds of it are you trying to display two different views on one page? if so have a look at panels, or you can do it manually by loading the views pragmatically in the template.
if not, please clarify.


How do I set the creation time of a node during a migration using the Migrate module?

I've been using prepareRow in my class to solve this kind of problem .

First of all I add a new Source Field to the MigrateSourceSQL

$source_fields = array(
  'created' => t('the created date'),

then in prepareRow I added the php for the timestamp and attached it to the row.

$row->changed = $nowtimestamp;

And then assign with addFieldMapping

$this->addFieldMapping('field_created_date', 'changed' );

This seems to work fine for me.


In Drupal 8: in Relationships, add a relationship to your image (mine looks like: Image, (field_image:target_id), Content, Appears in: image). In the next step select "Require this relationship". Now, in Fields, you have the filename field available.


Here is a brief list of template suggestions for Drupal 7: http://drupal.org/node/1089656

If you are looking to theme the user page, there are multiple templates located in modules/user that can be overridden. The template you should probably start with is user-profile.tpl.php.  Copy that file and paste it in your theme directory then edit it as you like and clear the cache and you should see the changes.


Pre-Populating a CCK Flexifield/Multigroup?


Default installation of D8 treatment of .gif accesses?

By default drupal serves a different 404 page to save computational effort if it  is matching the following regex:

'/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'

You can configure this in the settings.php (Fast 404 pages) or in the config('system.performance')->get('fast_404.paths');


Can I Run custom callback in site maitenance mode

If you want to test few menu item when Drupal site is in maintenance mode. You can use Maintenance Exempt module.
From this module's page:

Drupal allows you to set your site into maintenance mode in order to deploy code and database upgrades safely. However, access to the site during maintenance mode is by default controlled by a permission, which is generally only given to administrative users. It's not possible to test the site as a regular anonymous or authenticated user without giving all anonymous/authenticated users the "Use the site in maintenance mode" permission, so you generally have to test those things on the fly after moving the site back to "live" mode.
Until now, that is! This D7+ module (the necessary hook doesn't exist in D6 and below) allows specific people to perform the necessary testing on the site with all role combinations without opening the site up to all of your visitors.


One thing that can easily cause sudden big slowdowns like this is where a module or theme is removed from the code base without having been uninstalled in the database.  Drupal then goes searching for it by recursively searching though every possible folder that can contain a module on every page load.  This can easily add many seconds to page loads.

If you're synchronising code and DB with your windows environment then it's a possibility that this is the case.  you can confirm it by temporarily putting some kind of debugging in file_scan_directory() in includes/file.inc.  If it fires 100s (or 1000s) of times then that's probably the culprit.

If it is then re-syncing with your other environment may help.  Otherwise I'd recommend identifying the missing module, adding it to the code base again and if it's meant to not be there, disabling and then uninstalling it before deleting the files again.


There isn't a token that, given a user ID, would return data about that user account. current-user returns data about the currently logged-in user, while user returns data about the user account passed to the function (in Drupal 7, or the method in Drupal 8) that replaces tokens with their values: token_replace().

It would be possible, for a module, to implement a token that returns data about every user accounts. With such a module, for example, users:1:name could return the username for the user account #1, while users:2:name would do the same for the user #2.


Building a dynamic menu based on taxonomy terms

You are looking for Taxonomy Menu module. Here is an excerpt from its project page:

Transforms your taxonomy vocabularies into menus with ease!
Features

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules

I found these tutorials helpful to get started.
First Tutorial (youtube video).
Second Tutorial (youtube video).


How to check the value of a field within the current node?

I think you should be able to do this with the (https://www.drupal.org/project/rules_block_visibility) module.


Change the wording of the registration page

If you just want to add a few directions at the top/bottom, try creating a custom
 block.  Create a custom block with the instructions you want to add.  On the block configuration page, you can set the path to display only on certain pages.  Set that to user/register.  Then all you have to do is make sure the block is appearing in the appropriate region in your theme.


Menu CSS Names

  This is a very simple module that takes the link text of each drupal
  menu item and adds it as a css class name to the menu's element.
  Using these class names, each menu item can be styled separately with
  css. This is also very useful for css sprite techniques.

  There are no admin settings for this module, it starts doing its work
  once the module is enabled. All caches are automatically cleared at
  this time also. This module works with menus in blocks (including
  Primary Links) and menus in themes (menus that are enabled from the
  theme's configuration page).


Take a look at the Views Module.  It is the primary module used to select fields and display them. You can find out just about everything you need to know about using the module in this Video series


PDOStatement::execute takes 11s, what to do?

It could mean any of a bunch of things.  PDOStatement::execute() is just the final method that gets called for each and every database query Drupal makes (which can be quite a few).

First, make sure you Apache is configured properly, and that APC is installed and has enough memory.

Then, I would make sure your MySQL instance has a decent starting point.  Download, run, and follow the advice of mysqltuner.

Then, download/install/enable the Performance Logging and Monitoring module and play around with the reports.

Figure out what is slow, and fix it.

There are also bunches of posts with other profiling advice, too, as well as advice for performance improvements beyond basic configuration (eg, advanced caching strategies).


What if update.php fails due to code errors?

You could also rerun the update after you fixed your code.

See here:
reseting the hook_update_n status of a module


The [node-url] token is a real token define by the token module. I would make sure you have the latest version of the token module. I believe this token has changed names a couple of times but I think thats the correct token.

I would make sure you're running the latest version of the token module if not update and hopefully that would fix your problem.


How to change Views field settings programmatically?

UPDATED:

You can use this code snippet to change a view without views_alter:

$view = views_get_view($view_name, TRUE);
$view->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';
views_save_view($view);

Change default display ID if you want to use display other than the default.

If you have exported the view to code using hook_views_default_views() or the Features module, there is a hook to alter the views programmatically:

/**
 * Alter default views defined by other modules.
 *
 * This hook is called right before all default views are cached to the
 * database. It takes a keyed array of views by reference.
 *
 * Example usage to add a field to a view:
 * @code
 *   $handler =& $view->display['DISPLAY_ID']->handler;
 *   // Add the user name field to the view.
 *   $handler->display->display_options['fields']['name']['id'] = 'name';
 *   $handler->display->display_options['fields']['name']['table'] = 'users';
 *   $handler->display->display_options['fields']['name']['field'] = 'name';
 *   $handler->display->display_options['fields']['name']['label'] = 'Author';
 *   $handler->display->display_options['fields']['name']['link_to_user'] = 1;
 * @endcode
 */
function hook_views_default_views_alter(&$views) {
  if (isset($views['taxonomy_term'])) {
    $views['taxonomy_term']->display['default']->display_options['title'] = 'Categories';
  }
}

For example:

/**
 * Implements hook_views_default_views_alter()
 */
function MYMODULE_views_default_views_alter(&$views) {
  if (isset($views['VIEW_NAME'])) {
    $views['VIEW_NAME']->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';
  }
}

Remember to clear the cache and do revert of the view to apply changes.


How to use Webform's summed result in another node or block?

It is kind of confusing to create Webform Views with aggregation at first, I'll try to give a detailed explanation.
First, you would create a View of "Webform Submissions" - use unformatted list of fields as format.

Remove all fields that are placed in your View by default.

Add relationship to "Webform Submissions: Data" as shown the screenshot below. Adding relationship to webform submission data is crucial for Summing up your field values, because the added relationship gives you an option to add raw value of your field to the View (otherwise SUM aggregation doesnt work - see here). So, you would select your Webform node by typing its ID or the Name of your form, then in "Component Data" drop-down you'll select the field which stores the number that you need to sum up.

Add the field to the View scope:
Select "Webform submission data: Numeric value(raw)", or " *: Value(raw)". They both will produce the result that you want.  Make sure you select the relationship that you added previously in the field relationship drop-down.

Enable Aggregation for your View and set Aggregation to "SUM" on the your numeric field. Watch your field result summed up.

See if this approach works for you.


Views Image Field - Field Collection Show Only one Image

The Views module provides the option to select -in the field's settings- how many items you want to render for multi value fields. See the image below:


Displaying a single result out of three results

you can do it without preprocess, by using the Twig Tweak module, it gives you the possibility to render your view in twig with display filters and so on like the following:
{{ drupal_view_result('latest_products', 'block_1') }}

The drupal_view_result give you the array of result so you can get the first result with:
{{ drupal_view_result('latest_products', 'block_1')[0] }}

of type ResultRow and then get the entity with:
{{ drupal_view_result('latest_products', 'block_1')[0]._entity }}

For more information see the module Cheat sheet page


How to show a menu item for anonymous users only?

I think the simplest way would be to override the access callback for the path that your menu link will be pointing to. You can do this in a custom module with hook_menu_alter(), and use user_is_anonymous() as the callback function:

function MYMODULE_menu_alter(&$items) {
  $items['path/to/page']['access callback'] = 'user_is_anonymous';
}

If you add a menu link for this path, Drupal's menu system will respect the access callback, and the link won't be shown to anyone who's logged in.

Using this method will also make sure that logged in users can't access the page directly, which is probably a good thing.


A custom template file is not properly rendered

If you have path like contact then the page-contact.tpl.php will be automatically available (view the theming documentation).

You can also declare your own tpl with this code (put this in a custom.module):

function custom_menu() {
  $items = array();
  $items['contact'] = array(
    'title' => 'Contact us',
    'page callback' => 'custom_make_section',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function custom_make_section() {
  return;
}

Also a little bit easier is using the module Empty Page in order to create the custom paths you want and then these paths will provide the page-....tpl.php you need.


You can attach js only to your form. Use hook_form_alter()

function your_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form'){
  // Add JavaScript file
  $form['#attached']['js'] = array(drupal_get_path('module', 'your_module') . '/your_file.js');

  // Or for inline JavaScript
  $form['#attached']['js'] = array('/* some javascript here */' => array( 'type' => 'inline'));
  }
}


You don't need a new module as this functionality is built into core.  Go to (yoursite)/admin/structure/types and click "manage fields" for the content type you want to add your pdf's to.  Add a new field whose field type is "File".

Working with files in Drupal 7


CkEditor Toolbar not available/visible to Administrator when creating content

Sounds like you have a ckeditor plugin conflict.

Your symptoms are typical what happens if there are for example a js error on a added ckeditor plugin.

Quick way to confirm is using Firefox Console, it will in most cases flag the offending js for you. Armed with that you can google for a fix or patch.

Alternatively you can turn of the plugins off one by one, but you need to remember to clear your cache, else the offending js could still be there.

So try FF console first and post any extra info you get.


use hook_form_alter()

$form['field_name'] = array(
  '#type' => 'markup',
  '#markup' => $form['field_name'][#value]
);

or you can use prefix or suffix

$form['field_name']['#prefix'] = '
'.$form['field_name']['#value'] .'';


Using modules VBO, Rules and Rules Scheduler

About your approach using modules Views Bulk Operations (VBO), Rules and Rules scheduler (submodule of Rules), for which you wrote "it doesn't seem possible to schedule the Rule to run 3 times a day.": that appears to me "a" valid approach.

What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 8 hours (instead of just 1).

And as explained also in that tutorial: Initially execute the component manually. (from then on every other 8 hours the rule will be executed again).

Using modules Rules and Rules Once per Day

There is a fairly new module related to rules, i.e. the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

The way I understand/Read this (haven't experimented with it yet though) is like so:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

So by creating 3 similar rules, you could have 1 of them run around (say) 6 pm, another one around 2 pm and the ast one at 10 pm.

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


How to hide the link for creating certain content type?

In drupal 8, you can remove certain links from the /node/add page hook_preprocess_node_add_list():

function mymodule_preprocess_node_add_list(&$vars) {

  // Remove a few content types from /node/add page.
  $types_to_remove = [
    'dog',
    'cat',
    'fox',
    'rabbit',
  ];
  foreach ($types_to_remove as $type) {
    unset($vars['content'][$type]);
    unset($vars['types'][$type]);
  }
}

If you are using the admin_toolbar for drop-downs, you can remove links using hook_menu_links_discovered_alter().

function mymodule_menu_links_discovered_alter(&$links) {

  // Remove a few "node add" pages from admin menu.
  $types_to_remove = [
    'dog',
    'cat',
    'fox',
    'rabbit',
  ];
  foreach ($types_to_remove as $type) {
    unset($links['node.add.' . $type]);
  }
}


Twig template for two different instances of the system branding block

There's a few things you can do. Here's three.

Consider using a pure CSS approach. If you look at the body element for your page there may well be different classes you can use to make different selectors for styling the block. Modern CSS, particularly with the availability of :before and :after pseudo selectors, is incredibly powerful and you very often don't need custom HTML to adjust styling for different cases.
You can also implement hook_theme_suggestions_alter in your theme (in the file mytheme.theme) to supply alternative template suggestions based on the current path, for example.

Following this example, your code might look like:

function THEME_NAME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  $path_alias = trim($result, '/');
  $path_alias = str_replace('/', '-', $path_alias);
  $path_alias = str_replace('-', '_', $path_alias);
  $id = $variables['id'];

  $suggestions[] = 'block__path_alias__'.$path_alias;
  $suggestions[] = 'block__' . $id . '__path_alias__'.$path_alias;
}

Another option would be to create a second variant of the site branding block then use the option in Drupal's block system which lets you turn blocks on or off by content type.


How to show a content without creating node for it on Drupal site?

While not at all suggested or encouraged, if you really want to create a static page in drupal, you can fake it out by creating a page--PATH.tpl.php template, but just realize that while it will show up, behind the scenes drupal will be throwing 404 / not found errors.

See Drupal 7 Template Suggestions for more information.

What I would suggest instead, though, is to look into Drupal's Menu System and create a callback for the page in question.


D7 has this baked into the field formatters. You could look at how that is done and emulate it. But I suspect that would be quite a lot of work. How far off is D7 for you? It could be worth waiting till then to allow field settings.


Removing Divs of form elements with profile2 fields

You can use a theme_field override to adjust the field markup.

e.g, for body field on article content type:

Copy theme_field to template.php
Rename function to THEMENAME_field__body__article($variables)
Clear theme registry cache
Modify theme function markup to suit.

Note, the theme function naming convention required the "field_" prefix on field names, e.g THEMENAME_field__field_example__article()


You can do this with the Views Accordion module.

Add the Authored on field, choose the formatter that only shows the year of the created date. Then edit the Format settings to set the Grouping field Nr.1 field to your yearly Authored on field.

This way you get all the results split into groups by year.

Now you configure the Views Accordion to use the Grouping as accordion headings and the grouped results as accordion content.


drupal_find_theme_functions called on every page - is our theme registry being rebuilt?

Nice job on using XHProf to debug what's going on here. drupal_find_theme_functions() should get called once per registry rebuild for the core and installed modules, then once again as each installed theme is utilized.  Are you noticing it once per page load, many times per page load, etc?  I'm going to send you down a slightly different path on this as you should be more interested on what's causing the rebuild, not what happens when the rebuild occurs.

I'm assuming that you're working with a recent release of D7.  Use the devel module and put code below into drupal_theme_rebuild() at line 350 of includes/theme.inc to see what functions are being called on the way to the registry rebuild and that should give some clue as to what is triggering it.

dsm(debug_backtrace());

A quick note on what you should expect to see.  I've done some testing and with a mostly empty Drupal install with only a few popular modules installed.  The registry rebuild is only happening when I clear the theme cache or perform some action that causes it to be cleared.  If you look at the functions being called prior to the rebuild, you should see some indication as to what was responsible for causing it.

When I clear caches from the normal admin screen (admin/config/development/performance) my call stack is 9 functions deep and it passes through a form submission handler that triggers the process.  When I clear the cache from the admin_menu contributed module, my call stack is 5 functions deep and it passes through a page callback that initiates the cache clear.  Your case should be showing something a bit out of the ordinary.


Mapping or migrating path alias using using Migrate Source CSV

@Jigar's answer is close but not quite. Here is what I eventually figured out. It should be path/alias and not just path. Also, if you have pathauto module installed it will create the path based on the patterns. So, in order for our path to be imported from csv, the path auto needs to be disabled first. You set path/pathauto's default value to 0 to do that.

source:
...
 constants:
  slash: '/'
....
process:
...
 path/pathauto:
   plugin: default_value
   default_value: 0 # Disable pathauto
 path/alias:
   plugin: concat
   source:
     - constants/slash
     - url


How to check config setting in custom service class with dependency injection?

Make sure you inject config.factory and then you need to use:
$this->config
  ->get('my_custom_module.settings')
  ->get('display_debugging_info');

You can see that Drupal::config() is:
public static function config($name) {
  return static::getContainer()
    ->get('config.factory')
    ->get($name);
}

So after injecting your service, the equivalent of \Drupal::config('my_custom_module.settings') is:
$this->config->get('my_custom_module.settings');


Why to use hook_drush_help() when we have 'description' in hook_drush_command()?

The answer is context.

The command data pulled from hook_drush_command() is used when listing of all available drush commands with the command:

drush

So if a user is curious, "What drush commands do I have, and what do they do?" hook_drush_command() would provide that snippet. This could be useful for a short description in a directory of commands.

If a user is curious about a specific command:

drush help my_command

That's where hook_drush_help() would be more applicable as it can provide a detailed description that is only about that command queried.


How to use pjax module for batrik theme content?

It seems that the module is not maintained and importantly the module is still in unstable state.

So you shouldn't be relying on this module, unless you're ready to make it stable.

You can check the alternatives here,

How to use URL-based AJAX in Drupal 7 to serve all pages?

But AFAIK there is no module available as of now with the same feature.


An error which appears in Autocomplete taxonomy fields

In my case I get this exact error when using Views. It happens when I try to save changes in a given view and I click too quickly to start another action, while the ajax loader of the previous action hasn't gone away. Basically it's moaning that I should wait for one action to finish before starting another.

In your case, maybe the ajax request isn't fast enough to go and grab an existing match for the taxonomy term(s) you're adding in order to autocomplete it. Do you have enough memory allocated to Drupal in your machine/server?

If you're using the admin overlay, another trail to follow is comment #10 in this issue


Drupal 7 - Autoslave Master/Slave Failover Issue

For read-only mode to work properly you must apply the patch from https://drupal.org/node/1889328 (currently committed to 8.x but not backported yet).

The patch https://drupal.org/files/1889328-1-query-options_1.patch will work for 7.x, though it has not yet been cleaned up according to review comments.

I'm not sure I've mentioned this in the documentation, but you must ensure that you use a read-only user for the slave connection when utilising the read-only functionality. Otherwise you may end up writing to the slave-db which could cause inconsistencies and consequently the replication to fail.

The mt_rand() is possibly due to the result of no connections being available (both servers have status = FALSE in the invalidation file). Servers are only re-validated during cron. If you take down the slave to test that scenario, and then spin up the slave again and take down the master without running cron in between, you may end up with the kind of invalidation file you posted.


I am using POSTMAN to test my REST calls to server.

When i try http://mysite.com/api/endpoint/users/login.json

with parametes

Content-Type - application/json
username - A valid username on site
password - users password

I get a json looks like this

{
    "sessid": "6nRaPdlYfV4mDt0cgUHfGwNmWJZNvUfKM618DYY4unc",
    "session_name": "SESS4356595e5cb4b5df8f18058cfbd8d13a",
    "user": {
        "uid": "144",

From that i suspect you should pass sessid and session_name to get it work.

Try it and let me know whether its working if not we find some other solution which works :)


Hooks need to be written in . module file not in controller. Move your code to .module file and also it should be tabedit_menu_local_tasks_alter
tabedit.module
<?php

/**
 * Implements hook_menu_local_tasks_alter()
 */
function tabedit_menu_local_tasks_alter(&$data, $route_name) {
  unset($data['tabs'][0]['simplenews.newsletter_subscriptions_user']);
}

Clear flush all caches so hook gets pickedup.


How do I show the latest poll user hasn't voted on, yet?

I think I figured it out. I copied the hook_block_info and _view from the poll module to my own module and modified the query a bit. It basically now takes any poll that a user hasn't voted on or hasn't voted on during this session.
I don't have voting for anonymous enabled.

function mycustom_block_info() {
  $blocks['recent']['info'] = t('Most recent poll not voted on');
  $blocks['recent']['properties']['administrative'] = TRUE;
  return $blocks;
}

function mycustom_block_view($delta = '') {
  if (user_access('access content')) {
    // Retrieve the latest poll.
    $select = db_select('node', 'n');
    $select->join('poll', 'p', 'p.nid = n.nid');
    $select->leftjoin('poll_vote', 'pv', 'pv.nid = n.nid');
    $select->fields('n', array('nid'))
      ->condition('n.status', 1)
      ->condition('p.active', 1)
      ->condition(db_or()->condition('pv.chid', NULL)->condition('pv.timestamp', REQUEST_TIME - $lifetime, '<'))
      ->orderBy('pv.chid', 'ASC')
      ->orderBy('n.created', 'DESC')
      ->range(0, 1)
      ->addTag('node_access');

    $record = $select->execute()->fetchObject();
    if ($record) {
      $poll = node_load($record->nid);
      if ($poll->nid) {
        $poll = poll_block_latest_poll_view($poll);
        $block['subject'] = t('Poll');
        $block['content'] = $poll->content;
        return $block;
      }
    }
  }
}


Importing database: Duplicate entry 'X' for key 'PRIMARY'

but removed all "DROP TABLE" stuff to be able to import it to empty database

That's where you went wrong. Leave the database dump file exactly as it is, and then import it.

mysqldump adds DROP TABLE IF EXISTS by default, so unless you've specifically told it not to do that, the changes you're making are redundant, even incorrect.

It's a good idea to truncate the cache_* tables before running the data export. That way you don't get lots of ephemeral data in your backup, and exports/imports are quicker. I don't know if it will solve your current problem (if you have no duplicate errors elsewhere in the SQL script then it probably will), but either way it's a good habit to get into.


How to better distinguish answers from questions when using the Answers module?

Depending on your configuration, there are probably already classes supplied by default with Drupal.  Have you used Firebug to check the markup provided by Drupal by default?  (video tutorial on how to use Firebug)

If you do need to add a class, one quick way to add a class to a field is the Field Group module.  Navigate to the "Manage fields" page for the content type you wish to modify, create a new field group of type div, and then add the class and place the fields you wish to be "in" the class within it.


Custom packaged CKEditor: Make buttons available on profle configuration page

I found the solution myself.

Earlier I was using "CKEditor 4 Presets Builder" available at https://github.com/ckeditor/ckeditor-presets . That is not required. I just have to put copy of descriptionlist plugin within "plugins" directory of CKEditor library. Then those three buttons started to appear in CKEditor profile configuration page.


Put social Icons next to body field ($content['body'])

Try some thing like this in custom module and see it helps.

function modulename_page_alter(&$page) {
  $social=array(
    '#markup'=>'

',
  );
  array_unshift($page['content']['system_main']['nodes'][1],$social);

}


how to set up checkbox value while creating a node

Supposing the field can accept multiple values, the code should be similar to the following one.

    $node->field_operator['und'][0]['tid'] = 135;
    $node->field_operator['und'][1]['tid'] = 136;
    $node->field_operator['und'][2]['tid'] = 162;


views with different content types case studies

Views gives you enough power to maintain your custom styling. Please check for Views for theme information.

You can theme your different fields, rows, general theme.

You can style your node.tpl.php for general and for specific type node-[type].tpl.php


The way to join the entity to itself and use joined fields in UI

You'll need to change your starting approach; hook_views_pre_execute() is for modifying a View prior to execution, not for providing new table data to integrate into Views. You won't be able to plugin into the UI from this hook.

If you're wanting to plugin into D8 Views system so that it can be seen by the Views admin UI, you'll need to implement various plugins that the D8 Views modules will use to look up your table data, fields (columns) & relationships (joins) that Views can use to build queries on your data table.

Start by following tutorial examples like Building Views Query Plugins for Drupal 8 or by looking at a well-known module with Views integration (e.g. node, user) to understand & implement the various plugins that provide Views integration.


Unable to filter Views by a date field in the user profile

To create a view about Users, you start from admin/structure/views/add (of course).

However, below "Description" you need to select what type of data you want to "Show", and then optionally also select a "Type", etc).

By default (when you start creating a new view) it will suggest "Content" as value for "Show". But in your case you should have selected "Users" instead. If you do select "Users", you won't be able to select a "type" anymore. Because of the "... Fields of other types show up normally ..."
in your question I assume you used the default (Content) instead of "Users".

That's possibly the reason why you can't select the user related fields either ... To resolve this, just create a new view about "Users".


You can use the Field Permissions module according to module's page:

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

Then set permissions for your active/inactive field to be for admins only, then the field will not show for general users but admins will be able to change the status when they view each complaint.


How do you handle static HTML forms saved in a "Basic Page" in Drupal 7?

I think the reason you can't find any documentation is because doing this sort of thing is very much discouraged in Drupal.

Drupal's form API exists for a good reason:

It allows theme/module developers to build up a form very easily
It provides a unified approach for themes and modules to add elements/validation/logic to any form that exists in the system. A good example of this in action is the Captcha module, which has the capacity to hook into any form in the system and add CAPTCHA protection.
It provides automatic protection against Cross Site Request Forgeries (CSRF).

If you're not up for coding your forms you should instead check out the Webform module which has an easy to use UI allowing you to build up nodes with forms on them, and it has very powerful administration features.

If you really want to do it without using the Form API or Webform modules, though, you could probably try something like this in a custom module:

function MYMODULE_init() {
  if (isset($_POST['my_post_var'])) {
    // Do something with the $_POST data
  }
}

Be warned that your forms will not be protected from CSRF, nor will they have the ability to be changed by other parts of the system. It's also just not the 'Drupal' way to do things :)


Can't visit site after switching on Language Detection 'Session' in combination with Ip to locale

I solved it by entering ?language=en behind my URL. After this i was able to login and visit my site again.


Change background for authenticated user

I think your solution would be the class "logged-in" and the CSS property "background-position" to move the background image down 100px for logged-in users:

body {
  background: #fff url(../img/backgrounds/body-background.jpg);
  background-repeat: repeat-x;
}

body.logged-in {
  background-position: 0 100px;
}


How can I add or delete the front page's blocks?

1)First of all create a tpl file "page--front.tpl.php".

2)Suppose you want to place block  in sidebar second region use devel module to see the content of your page.

<?php dpm($page);
dpm($page['sidebar_second']);?>

3) Write following code after executing above code:

<?php print render($page['sidebar_second']['id_of_your_block']) ?>

for deleting/hide the front page block

1)Go to edit page at block/region setting/none


A mini panel acts like a block, except that it has subregions.  To add content, select the mini panel for editing and select the "content" editing display.  Next pick the gear in the upper right corner of the desired region in the mini panel and select 'add content'  The pop-up will give you the selection of available content that can be placed in the panel.

Once you have the mini panel configured, you place it in a theme region just as you would a block.  You select the mini panel from the admin/structure/blocks page for your theme.  It can be found in the list of disabled blocks at the bottom of the layout page form.


Remove an item from $form_state in an ajax callback

$form_state->setValues(['names_fieldset'], array_values($values));

setValues(array $values) only has 1 parameter

For 2 params, you need to use setValue($key, $value) without the "s"

$form_state->setValue('name', array_values($values));

Alternatively, you could do

$values = $form_state->getValues();
$values['name'] = array_values($values);
$form_state->setValues($values);


How should I fix an incorrect query in hook_update_N()?

Something similar happened with Panels, update 7301, a new field was added, and while the column creation happened, Drupal wouldn't accept the update as valid.

If you check the code in panels.install, you will see that the action taken by merlinofchaos, was to modify the 7301 to first check "Does this column already exists? Then smile and pretend we just created it, otherwise create it now."

If merlin does it that way, I would do it that way. Relevant issue here, maybe that will help further.

Since each of your scenarios above have potential for data loss, which is serious, and people dont actually take backups, and in your case, there is no, way to tell, then perhaps you will need to force the user to tell you. Refuse the update unless the variable module_name_has_1_1_content is set to either TRUE or FALSE. Then either you can add a form in the admin UI with an explanation and yes/no button that just sets the variable. Or just one "I have read the issue and understand the consequences, let me update" button.

Perhaps you can provide instructions for "How to export and import all content". That way the user can export, update, truncate the table, and import.


Users complain they can't "click on anything" on my Pressflow site

I fixed the issue (which was general): I was using a Microsoft CSS filter to scale the background image. It somehow made the whole page render incorrectly. I removed filter, and the problem was solved. I can live without a nice background on IE, for now.


Is there an error in Drupal with hook_views_post_execute?

You have to define the statement of ViewExecutable like use \Drupal\views\ViewExecutable

use \Drupal\views\ViewExecutable;

function nvgh_views_post_execute(ViewExecutable $view) {
  if ($view->total_rows > 12) {
    \Drupal::messenger()
      ->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}


How can I hide the label saying "URL*" from content creation form when using the link module?

Look at the Manage Display tab of your content type. On that page you can set how the label is displayed:

Above
Inline
Hidden

and how your link displays:

Title, as link (default)
Title, as plain text
URL, as link
URL, as plain text
URL, absolute
Domain, as link
Short, as link with title "Link"
Label, as link with label as title
Separate title and URL
Hidden


When 'cron_safe_threshold' is set to 0 in settings.php, should the dropdown value on admin/config/system/cron be "Never"? or is it irrelevant?

This setting is for Drupal 7. In Drupal 8, the equivalent is in the config management system as automated_cron.settings.interval. To override it, like in Drupal 7, you can add:

$config['automated_cron.settings']['interval'] = 0;

to your settings.php.

To address the other question, the relevance of automated_cron.settings.interval & cron_safe_threshold is the minimum amount of time (in seconds) since the last cron run that Drupal is allowed to run again. This value is checked (D7 & D8) for a 0 threshold which it will interpret as FALSE and thus never run cron.


How to get higher weight range for vocabulary

Remember to pass value by reference.

function <MYMODULE>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "taxonomy_overview_vocabularies") {
    foreach ($form as &$vocabulary) {
      if (isset($vocabulary['weight']['#delta'])) {
        $vocabulary['weight']['#delta'] = 20;
      }
    }
  }
}


Go to "admin/config/system/site-information" to set front page.

Bottom section of this page there is a option for set "Default front page".

Give the view link in "Default front page" textbox. You will not able to see that message.


Create node and node reference from URL at one time

Depending on which relationship module you're using there are different options.

If you're using Entity Reference there's the Inline Entity Form module:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.
  The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.

If you're using the References module there's References Dialog:

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

Both will allow you to create a referenced node at the same time as creating the referee.


What is the actions table for and can I delete orphaned actions?

There is no button or link or even an indication that orphans exist when going to /admin/config/system/actions.

I don't really get why, but when I visit /admin/config/system/actions/orphan the orphaned actions are removed.  I'm watching the Drupal log when I go to that path and it systematically removes all the orphans.


what is the difference between commerce order table and commerce line item table?

The commerce_order table stores data about an order. The commerce_line_item table stores line items (e.g. products, fees, misc charges) in that order.

If you need to track when the order was created, reference commerce_order.created. If you need to track when the line item was originally added to an order, reference commerce_line_item.created.


How to use negative number as argument value in a drush command?

It looks like it is not possible since the '-' is always picked up as an option being passed to the drush command.  I'd suggest evaluating why you need a negative value and if it could be handled with an absolute value and/or some other creative way of indicating a negative value.

If this is not an option, I found this work around in several different articles/blogs:

php -r "print json_encode("-1");" | drush vset --format=json some_var_name - --y

The drush command docs also suggest a technique using arrays for passing a complex data structure to the command: https://drushcommands.com/drush-7x/core/variable-set/ (See the last example).  This would let you pass in almost anything you wanted.


Sorry. It's not answer. But i try debug in function

function return_data_pcb() {
  watchdog("debug", '<pre>' . print_r( $_POST, true) . '</pre>');
  // But $_POST is empty array. It's show in admin/reports/dblog, when in website one // call function drupal_http_request.
}

I don't know my problem by when call drupl_http_request data post doesn't not send. Or problem with hook_menu in website two. Please help!