what does the 'debug mode' on Services actually do?

The debug mode is essential to test if your service is working correctly through posting the logs. You can see the logs in admin/reports/dblog.  These logs shows you if you are sending the appropiate format,  if there is any error, etc.  The logs  allow  you to see the output of the transactions. I have attached a image with some samples of the logs messages. As far as I understand that it is the only use for the debug mode in the services 3 modules. If it is not or this answer was not accquire please post a better explanation.

As you say it uses watchdog, so you can see internally what it is happening with your service. I have included the service code if you like to see the function yourself git service

.


Using php if else statement in display suite

If your need is simple, a "hide when empty" for example, you definitely need to look into Field formatter conditions module, it will allow you do simple conditions on your field formatters for a given view mode.

If that's not enough, Display Suite allows to have arbitrary fields added to the view modes, you need to look into hook_ds_fields_info and implement it in a custom module for your needs.

/**
 * Implements hook_ds_fields_info()
 */
function my_module_ds_fields_info($entity_type) {
  $fields = array();

  $fields['my_field'] = array(
    'title' => t('My field'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'ui_limit' => array('node_type|*'),
    'function' => 'my_module_callback_function',
  );

  return array('node' => $fields);
}

function my_module_callback_function(&$field) {
  // Here goes your code, the conditions to display or not another field
  // and return an array with the data.
}

Further examples in https://stackoverflow.com/questions/16253312/using-hook-ds-fields-info-is-there-a-way-to-use-standard-formatters-so-the-op and http://www.previousnext.com.au/blog/creating-custom-display-suite-fields-or-how-i-learned-stop-worrying-and-use-hookdsfieldsinfo


Panopoly WYSIWYG exclude buttons configurations

Since Panopoly WYSIWYG module does not provide this kind of configuration out of the box, you will need to add additional text formats and WYSIWYG profiles. When configured, export them to your own Features project. If you customize the WYSIWYG profile provided by Panopoly WYSIWYG, be sure to export those using Features Override module (provided in full distro and if using Panopoly Core I believe.)

WYSIWYG profiles merely build on top of existing text formats which have restrictions by roles.

The alternative, however, is to use hook_wysiwyg_editor_settings_alter() and possibly remove buttons based on role, that way.


Visit admin/config/system/statistics and enable the following settings.

These are the standard options I use for showing the node count. They some to work well in my case.


Using db_select, how can I select all nodes with any of an array of taxonomy terms and order by the number of terms it is associated with?

You should put count as alias name in the count(*) and then groupby clause can be used on that column.

$query = db_select('node', 'n')
      ->fields('n', array('nid'));
$query->addExpression('COUNT(n.nid)', 'count'); // addExpression
   $query->condition('n.type', 'post')
      ->condition('n.status', 1);
    $query->join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');
    $query->condition('tags.field_tags_tid', $tags, 'IN');
    $query->groupBy('count', 'DESC'); //count is column name given in the addExpression


As a workaround you could show a list of accepted challenges for each user and link them to node/add/blog with the title prefilled using the prepopulate module.

You could also create a node reference from blog to challenge, use a "select" widget and narrow the option with a view (that's a cool feature of the node reference module). In that view you limit the records to the current user and only the challenges they have flagged.


Don't duplicate the attach function.

(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}})(jQuery);

If you have used this for 1st JS

(function ($) {
Drupal.behaviors.test_module_2 = {
  attach: function(context) {
    console.log("test data");
  }
}})(jQuery);

Then you can use this for 2nd JS as the attach function should be used only once


Meta Tag are not display on some of pages

Finally i found reason behind it.

I haven't call <?php print render($page['content']); ?>.

After adding it , it is working superb.


Yes, then the best thing would be to follow the enforced config dependencies part above, if you create the content blocks with a fixed uuid then you can just put the block config entities in your config/install folder, with the config dependencies as explained there and it should be uninstalled automatically.

At least the config entities, if you want to delete the block_content entities too then load them by UUID with $block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', 'YOUR_UUID'); $block_content->delete()


Other than Migrate (which I have not tried yet), the only thing I have found was to use Feeds Import with the contributed patch for a Generic Entity Processor to import Entityforms.

https://drupal.org/node/1033202#comment-7710367

I currently have Drupal 7.23 and Feeds 7.x-2.x-dev (7/6/13) and I patched the feeds module successfully with the patch at comment #217.  This then gives you the option of having an entityform as a bundle.

I created a test entityform, a small test csv, and a new test feeds import.  The import completes successfully, but there's no content in the submissions.  Maybe you'll have better luck than I.  My next step is to checkout the latest from git and try again.  If that doesn't work, I guess I'm going to have to learn how to write a migrate module.

FYI, I have successfully used the Feeds Import module using the node processor that comes with the module for custom content types if you don't need it as an entityform.  There are several good Feeds videos out there is you're not familiar with the module.

Please reply if you find something else that works.


Attribute about not allowed on element article at this point

It looks like there is a markup error somewhere whereby you have an <article> tag with an about attribute (i.e. <article class="my-class" about="blah">).

I would imagine the site is working fine as the attribute will just be ignored if it's not applicable, so I'd find the page and line from the validator error and double check your markup.

You could also try running it past the newer HTML5 W3C validator at http://validator.w3.org/nu/ just in case.


Alternative for Node Gallery in Drupal 7?


Views Contextual Filter Match criteria with contains instead of equal to

Try using Views Argument Substitutions

  Contextual Filters allow a View to be filtered based on arguments
  passed via URL or other embedded method (e.g. the View Reference
  module), but contextual filters are inflexible compared with normal
  filters (which allow for "contains," "begins with," "ends with,"
  etc.).

  This module allows contextual filter arguments to be used as
  replacement tokens in filters and table arguments, so that passed-in
  arguments (such as from URLs or View Reference fields) can be used as
  values in normal View filters.


Use Menu attributes module. The module currently allows you to set the following attributes for each menu item:

Id
Name
Target
Rel
Class
Style
Accesskey


Drupal 7 Breaks CSS Rule Ordering Standards when CSS Aggregation is Turned On

Solved my own question. There were rules that came before the @import. So this wasn't a Drupal 7 issue, it was a CSS interpretation error.


Solved it using hook_menu_alter and adding custom module. I have modified the access callback function to suit my needs.

Here is my code, may help user having same task:

    function mymodule_tab_menu_alter(&$items) {
        $items['node/%node/workflow']['access callback'] =
        'custom_workflow_tab_node_access';
    }

    function custom_workflow_tab_node_access($node = NULL) {

    global $user;

    if ($workflow = workflow_get_workflow_type_map_by_type($node->type)) {
        if ($workflow = workflow_get_workflows_by_wid($workflow->wid)) {
            $roles = array_keys($user->roles);
            if ($node->uid == $user->uid) {
                $roles = array_merge(array('author'), $roles);
            }
            $allowed_roles = $workflow->tab_roles ?
            explode(',', $workflow->tab_roles) : array();

          if (user_access('administer nodes') || array_intersect($roles, $allowed_roles)) {

      /* This is additional Condition*/

      if ($node->type == "article") {
     $current_state = workflow_get_workflow_states_by_sid(workflow_node_current_state($node));
                    if ($current_state->state == "State_name") {
                        return FALSE;
                    } else {
                        return TRUE;
                    }
                } else /*End Additional Condition */{
                    return TRUE;
                }
            } else {
                return FALSE;
            }
        }
    }
    return FALSE;
}

As above in custom access callback, I have used the same code, just added the additional condition and it solved my issue. :)

-- Thanks


How to show forums even if you don't have access?

Implementing custom permissions in Drupal 8:

https://www.aram.cz/article/custom-permissions-drupal-8

You should be able to use static permissions, which are configured in a YAML file in your custom module. From the article:

  To declare static permisisons, you need to create a file in the root directory of your custom module and name it YOUR_MODULE.permissions.yml.

'sample permission 1':
  title: 'First level permission'
  description: 'Gives first level permission to the users.'

'sample permission 2':
  title: 'Second level permission'
  description: 'Gives second level permission to the users.'

'sample permission 3':
  title: 'Third level permission'
  description: 'Gives third level permission to the users.'
  restrict access: true

Then you can check for that permission in PHP code like so:

if (\Drupal::currentUser()->hasPermission('sample permission 1')) {
  // The "sample permission 1" has been granted to the current user.
}
else {
  // The "sample permission 1" has NOT been granted to the current user.
}

I'm not sure exactly how you'll use this technique in your situation to allow users to see only a summary of forum post titles without the ability to click through and see the individual forum posts, but hopefully it will set you on the right track.


How to programmatically delete taxonomies when a module is uninstalled?

I did not test it myself, but as far as I see in the documentation, Term is using Entity::delete(). You might try to load the terms you wish to delete and call this method directly on them:

$term->delete();


Drupal 7/Zen - How do you move the header (field_image) image above the title on a page?

If you want to change the page.tpl.php template file, but avoid it gets used for the front page, just:

Create the page--front.tpl.php file from the current page.tpl.php file
Edit the page.tpl.php file to move the image above the title

In this way, page--front.tpl.php will be used with the front page, and page.tpl.php will be used with the other pages.


How to theme markers bubble with Gmap module?

There's a actually a way to do this in Views UI.

Add all your fields in Views as per usual
On the bottom most field (ideally the one that's the bubble), edit it and click on "Rewrite results".  (Note you can drag / reorder fields to get the right one at the bottom.)
Check the box, "Rewrite the output of this field"
Below that once expanded, you will see "Replacement patterns"
Now add in all the tokens into the rewrite text box. e.g. [title] == Content: Title, [some_other-field] == Content: Some other field, etc...
Click apply.
Now go in and edit the other fields that you added in to the bottom field and check the box "Exclude from display"
Now go to "Format" probably something like "Gmap" and click on "settings". You will see a "grouping setting
select to group on that bottom most field that you added in all the tokens to.
Save this and now all those fields should be in the bubble.

Obviously without seeing your view, I was guessing at some of this so you will have to try to make sense of it as it in terms of your view.


Thanks 32i for your suggestion, i have managed my problem already.
it was a result of cache. when i flush all caches i get the content normally.
finally i found out the memcache is the caching level behind this problem, simply i excluded authenticated users from being served by memcache and this fixed my problem


Ajax form submit - how to recognize if form contains errors in ajax callback?

You can define the form status in $form_state and check the status during rebuilding form.

Example code:

function activit_registration_form($form, $state) {

  if (isset($state['submit_success'])) {
    $form['ajax_form']['message'] = array("#markup" => t('Thanks for your submission.'));
  }
  else {

    $form["ajax_form"] = array(
      "#prefix" => "
",
      "#suffix" => "
",
    );

    // define form elements under 'ajax_form', such as
    // $form["ajax_form"]["element_1"] = array( ... );

    $form['ajax_form']["submit"] = array(
      "#type" => "submit",
      "#value" => t("Odoslať"),
      "#ajax" => array(
        "callback" => "activit_registration_form_ajax",
        "wrapper" => "registration-form-ajax",
        "effect" => "fade",
      ),
    );
  }

  return $form;
}

function activit_registration_form_ajax($form, $state) {
     return $form['ajax_form'];
}

function activit_registration_form_validate($form, &$state) {
  $has_error = FALSE;

  if (!valid_email_address($state['input']['email'])) {
    form_set_error('email', 'email');
    $has_error = TRUE;
  }
  if (strlen(strval($state['input']['name']))<3) {
    form_set_error('name', 'meno');
    $has_error = TRUE;
  }
  if (strlen(strval($state['input']['tel']))<6) {
    form_set_error('tel', 'tel');
    $has_error = TRUE;
  }

  $state['submit_success'] = !$has_error;

  $state['rebuild'] = TRUE;
}


I believe you mean hook_query_alter() here by mentioning hasTag(), hasAllTags(), and hasAnyTag() not hook_views_query_alter().

You can understand more about these methods from this documentation.

By help of these methods you can specify the targeted query, when you apply this in your module. A example code has been given in answer at Stackoverflow question, which helped me long ago to modify a query of views.

function MY_MODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasAllTags('views', '[MY VIEW NAME]')) {
    $query->addJoin('INNER', 'taxonomy_index', 'ti', 'node.nid = ti.nid');
    $query->condition('ti.tid', '2,3', 'IN');
  }
}

If you are looking for the tags which you can use, just try to print $query inside the hook & see the result on the page where you are working. You will get what query you can target & the tags which you can use.

I hope it helps :)


How can I disable jquery_update when my admin theme is in use?

It should be noted the underline issue is really a core problem which is now fixed over at http://drupal.org/node/1480568

Anyways if people still need a fix for this this is what I have in place.

/**
 * Implements hook_module_implements_alter().
 */
function hook_module_implements_alter(&$implementations, $hook) {
  // Make sure to check if the module is enabled or this will cause fatal errors
  if ($hook == 'library_alter' && module_exists('jquery_update')) {
    // Move jquery update to the end. This will make sure our hook_library_alter
    // is always called before the jquery_update.
    $jquery_update = $implementations['jquery_update'];
    unset($implementations['jquery_update']);
    $implementations['jquery_update'] = $jquery_update;
  }
}

/**
 * Implements hook_library_alter().
 */
function hook_library_alter(&$libraries, $module) {
  // If it is an admin path all we want to do is change the global $conf
  // variable so when jquery_update runs right after us it will use 1.5.
  if (path_is_admin(current_path())) {
    // Modifying global $conf variable, can be dangerous. Be carefull.
    global $conf;
    $conf['jquery_update_jquery_version'] = '1.5';
  }
}

This changes the variable right before jquery_udpate uses it when is an admin path. Also this doesn't hard-code to checking the url 'admin' because and admin path can also be /node/1/edit etc..


Entering inner fields after attaching a field collection entity programmatically

Field collections are not stored in full with the Loaded node access via node_load(); only their entity ID.

The data does sometimes look like that, for example in a node form (because it actually has to create fields for them) and in a rendered node via node_view()(depending how you have set it in the view mode settings).

But you can load them easy enough and get the values that way.

Here is an example :

Dynamically creating a node with multiple field collections :

  global $user;
  $type = 'floor_staff_checklist';
  $event_id        = 12345;

  $chk_node        = new stdClass();
  $chk_node->type  = $type;
  $chk_node->title = '';
  node_object_prepare($chk_node);
  $chk_node->uid                           = $user->uid;
  $chk_node->nid                           = 0;
  $chk_node->status                        = 1;
  $chk_node->promote                       = 0;
  $chk_node->field_event[LANGUAGE_NONE][0] = array(
    'target_id'   => $event_id,
    'target_type' => 'node',
  );

  if ($type == 'floor_staff_checklist') {
    $time = strtotime("01-01-2000 19:30:00");
    for ($i = 0; $i < 22; $i++) {
      $strtime = date("H:i", $time);
      $time += 1800;
      $flrchhk_fc = entity_create('field_collection_item', array('field_name' => 'field_floor_check'));
      $flrchhk_fc->setHostEntity('node', $chk_node);
      $flrchhk_fc->field_check_time[LANGUAGE_NONE][0]['value'] = $strtime;
      $flrchhk_fc->save();
    }
  }

  $chk_node = node_submit($chk_node);
  node_save($chk_node);
  drupal_goto("node/$chk_node->nid");
}

In this situation, I am creating a node, and creating 24 field collections within it, one for every hour, then saving the node.

And if you want to view the data :

$entity = entity_load_single($chk_node->nid);
if (isset($entity->field_floor_check[LANGUAGE_NONE]) && !empty($entity->field_floor_check[LANGUAGE_NONE])) {
  $fcs = array_column($entity->field_floor_check[LANGUAGE_NONE], 'value');
  $items = entity_load('field_collection_item', $fcs);
  foreach ($items as $item) {
    dpm($item);
  }
}

This will load the node, access its references to the field collections, load them, and loop through them printing the contents through Krumo (Devel module).


Drupal 7 When a new user registers, where is the confirmation e-mail sent?

Set the new user account setting to "administrator approval is required" here:

Admin > Configuration > People > Account Settings


How to prevent a node from being saved/updated by using the Rules module?

I'm not aware of a way to do what you're asking for by only using the Rules module ... And the (old) issue about "Prevent Node from being saved" (with confusing status "Closed (fixed)" ...) somehow seems to confirm you'd need "a bit more" ...

You can try to make it work by ALSO using the Conditional Rules module for this. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Here is a screenprint of a rule with an action that uses Conditional Rules (though only with an "if"-part here, no "else"):


I think you can use the "Contextual Filter" for this. Choose the "Content: Created date" as the contextual filter. Then in the filter settings, choose "Display a summary" and save the view. Maybe this helps you to start with this.


I am not 100% sure but I would suggest you simply do the following:

Choose Format = Table
Then click on the settings for Table
Change the grouping field to the "hash" field

Then aggregate the results based on the destinations.

However, when you use the redirect module in Drupal 7 there is a field available called "Redirect: Clicks". I wonder if this may help you.

I hope this may helps.


How to set nodes to be excluded from a block view based in the url of current node?

What you could do if you could use either Views Filters and use the view Filter options to set which URL's to exclude based on tokens.

You could also maybe use Views Rule to try and do something similar.

I think the Views Filters may be an easier option. But if you want to do your suggestion (add a field to the node) then what you can do is pretty much exactly what you said, you would add a filter to the view based upon the available tokens and field data.


Workflow - Accepting/rejecting individual changes

I've had frustration with the Workflow module. You may want to try out the Workbench and Workbench Moderation modules. Throw in the Trigger module to send e-mail notifications when a document changes workflow state.


No, you only need to add the hostname patterns in settings.php for how the site is being accessed, which normally isn't by IP. settings.local.php shouldn't be involved, as that is typically just for local development (I never adjust trusted patterns for local dev, just staging and production).

Essentially, the portion of code that handles this looks at the HTTP Host header, which is the hostname portion of the URL you requested (unless your webserver does canonical Host normalization, which is different that the rewrite rule for canonical URL).  The IP address never comes into play, unless you browse directly to the a URL where the "hostname" portion is the IP.


How to use CURDATE() and INTERVAL in Drupal Database object syntax

Try db_query() function:
Solution -1

$query = 'SELECT node.nid as nid FROM node node INNER JOIN field_date field_date ON node.nid = field_date.entity_id WHERE from_unixtime(field_date.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()';
$result = db_query($query)->fetchAll();

Solution-2

$query = db_select('node', 'n');
$query->fields('n', array());
$query->innerJoin('field_date', 'fd', 'n.nid = fd.entity_id');
$query->where('FROM_UNIXTIME(fd.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()');
$result = $query->execute();


You need to attach the tag in hook_node_view() (which is derived from hook_ENTITY_TYPE_view(), when the view mode is full (which makes the assumption that the full view mode is only ever used on node pages).

You can do that as follows:

function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $mpde, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)
{
  // Check if the view mode is full
  if($view_mode == 'full')
  {
    // Create the tag. You can set the content of the
    // metatag from the node
    $tag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'name attribute of metatag',
        // Note that 'value' will differ depending on the
        // field type.
        'content' => $node->get('field_something')->value,
      ],
    ];

    // Attach the meta tag to the header.
    $build['#attached']['html_head'][] = [$tag, 'some_key_to_represent_tag'];
  }
}


How to open User registration in a pop up?

Probably your server's settings prevent opening registration pages within frames. This prevents embedding your registration form in 3rd party webpage to create spam users et cetera. That is usually a good thing, even if what happens to you is over-restrictive.

Now, why to reinvent the wheel? There is a Modal forms module ready.

  Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window.
  Supported forms

  Log in (modal_forms/nojs/login)
  Request new password (modal_forms/nojs/password)
  Create new account (modal_forms/nojs/register)
  Contact (modal_forms/nojs/contact)
  Comment (modal_forms/nojs/comment/reply/%node)
  Webform (modal_forms/nojs/webform/%node)

Emphasis mine.

It has some bugs, but for first 3 it works pretty well. Or at least it used to.


You can use context module and create two different contexts by adding conditions as path.

Enable the reactions as blocks and add same blocks in different sections using two context that you created !

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

Hope it solves the problem :-)


Best database collation for multilanguage site

utf8_general_ci is preferred over latin1_swedish_ci

The good news is that as a result of this issue Drupal now defaults to utf8 so no one should have to worry about this any longer. This fix has been backported to Drupal 6 so this answer should be applicable to Drupal 6, 7, and 8 (when it is released).


@citricguy exactly - seems that any URL you type after /news/ ends up showing your newsletter.

You probably have an index.html file there with that content.

Example:

http://www.signamic.co.uk/news/something-that-should-not-exist

Gives the same output as:

http://www.signamic.co.uk/news/full-time-pacourse-adminstrator-vacancy

Check your folder structure in root and .htaccess file.


Will I loose this content or the content will be saved?

No, you will not loose any content after upgrading the site. But before upgrading the site please take care of the following things.

Back up your database.
Back up your code.


Set up the relationship:

Under the Relationships section in advance settings. click + to add a relationship.
Under "Add relationships" you will see all fields listed.
Drop down the Groups menu and select "Content".
Locate your node reference field, for example 'Content: Reference question (field_reference_question)'. Check the box to the left of it.
Click the Add button.
Check the box labeled 'Require this relationship', and click the Update button.

Add a field:

Click + next to Fields. Under Groups, select Node, and choose Node: Title. Under Relationship, select your node reference field, e.g., Reference question, click Update.


Error throwing for user field populated through Views: Filter by an entity reference view

If you need to show the users from a particular role you don't need to rely on views filter option. Default method is enough, there will be an option to filter the users using roles. I know its the answer that you are seeking. But its a work around. But if you need to add other filter parameters this method will not be enough.


How do I display taxonomy content from taxonomy category?

Not sure of your full requirements as it is a bit confusing but it sounds like you are trying to output all the fields of a specific Taxonomy.

If you are using Drupal 7, just create a view of 'Show' Taxonomy Terms.

Then from there add the taxonomy fields that you require by searching from the 'add field' dropdown.

Finally create a filter for taxonomy term 'category'.

Hopefully that is what you are after.

Do you not see this filter when creating your view. What version of Drupal are you using?


How can I add a field to a view that is calculated using other fields?

You could create your own views field handler in a custom module.
Implement  hook_views_api and hook_views_data_alter(&$data) than you can write your own field handler.


There is drupal_is_front_page

Check if the current page is the front page.

Return value

Boolean value: TRUE if the current page is the front page; FALSE if otherwise.


Set value of field based on GET param for anonymous users

Have a look at this module Cache Exclude, it might help you.

And even have look at this link, it is having more details about your problem.


How can I hide the "day" in a date field?

Note that the day is required.

This means there are some difficulties:

You need to set the value for the day field (otherwise the form will fail validation).  In this example, we will set it to the 15th of the month.
You can't use unset() or #access: FALSE because this will cause the form to have no value and fail validation.

You can do this in an #after_build callback.

function MYMODULE_form_MYFORM_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#after_build'][] = 'MYMODULE_date_remove_day_after_build';
}

function MYMODULE_date_remove_day_after_build($form, &$form_state) {
  $form['field_MYFIELD']['widget'][0]['value']['day']['#value'] = '15';
  $form['field_MYFIELD']['widget'][0]['value']['day']['#attributes']['class'][] = 'element-hidden';
  return $form;
}

And then in your theme .css, add this class:

.element-hidden {
  display: none !important;
}


How can we define twig template based on checkout flow in Commerce 2.x?

I found out the answer. Share here if someone needed in the future.

I think if we want to define the twig template based on the checkout flow, we shouldn't create ones using the same plugin. (default is Multistep - Default)

Instead, we need to create a new plugin for the checkout flow. I followed the instruction here. https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-flow

After I finished the custom checkout flow plugin, we can create another flow based on the custom one.

Therefore, we can use Implements hook_theme_suggestions_HOOK_alter() to implement what we need.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function bootstrap_sass_theme_suggestions_commerce_checkout_form_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables["form"]["#form_id"];
}


Edit your view. and Under the "Advanced" settings of your Block details, click on "Theme: Information". A list of options of template files will be displayed.

for example, if your block has a name "posts listing", see possible names listed by "Theme Information" option:

* Display output: views-view.tpl.php, views-view--posts-listing.tpl.php, views-view--default.tpl.php, views-view--block.tpl.php, views-view--posts-listing--block.tpl.php
* Style output: views-view-unformatted.tpl.php, views-view-unformatted--posts-listing.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--block.tpl.php, views-view-unformatted--posts-listing--block.tpl.php
* Row style output: views-view-fields.tpl.php, views-view-fields--posts-listing.tpl.php, views-view-fields--default.tpl.php, views-view-fields--block.tpl.php, views-view-fields--posts-listing--block.tpl.php
* Field Content: Title (ID: title): views-view-field.tpl.php, views-view-field--title.tpl.php, views-view-field--posts-listing.tpl.php, views-view-field--posts-listing--title.tpl.php, views-view-field--block.tpl.php, views-view-field--block--title.tpl.php, views-view-field--posts-listing--block.tpl.php, views-view-field--posts-listing--block--title.tpl.php

for example: your block has the name posts listing, and has style unformatted, then "Theme Information" suggest the name views-view-unformatted--posts-listing--block.tpl.php (this is only one of several names).  you can copy the original views-view-unformatted.tpl.php template file (located in /modules/views/theme) to your current theme directory, and rename this file with the name suggested :views-view-unformatted--posts-listing--block.tpl.php. then make the changes inside your template file. If this template does not allow make your wanted changes, seek other templates according your needs.

In the end, if you add a new template, rescan template files list:

  Important! When adding, removing, or renaming template files, it is necessary to make Drupal aware of the changes by making it rescan the files on your system. By clicking "Rescan template Files" button you clear Drupal's theme registry and thereby trigger this rescanning process. The highlighted templates (in your template list above "Rescan template Files" button) will then reflect the new state of your system.

Also Theme Developer Module http://drupal.org/project/devel_themer suggested by Oswald could be useful to detect possible template/s to change specific elements according your criteria. I do not recomend this module enabled in productions enviroments (in my case, even I have disabled the module in test enviroments, because seems to have conflicts with views, but when it has been necessary, has been very useful)


how can i add billing information in invoice email

I've implemented similar functionality for a Drupal Commerce site I built using Commerce Kickstart 2. It's actually a Rule created by the commerce_email module which I'll break down for you below:

Rule is called "Send an order notification e-mail (Customers)"
Event: Completing the checkout process
Action: Send mail with variable (contains all default commerce_email variable settings)

Then if you navigate to the Commerce Email admin section: (/admin/commerce/config/email)

The token I use to display the customer address is:

[commerce-order:commerce-customer-shipping:commerce_customer_address]

Using that token everything prints out in my email template correctly as expected.

Hope this helps!


how to fix this Drupal\commerce\CommerceEntityViewsData' not found

Make sure you're using Drupal Commerce 8.x-2.6+
CommerceEntityViewsData was added in https://www.drupal.org/node/2882374


Preview option for entity registration form

I have one another option that i have used:

function your_Module_name_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'your_form_id') {
       $form['submit']['#attributes'] => array('class' => array('upersubmit'),'onclick' => 'if(!confirm_vil(this.id)){return false;}');
   }

}

/* Js Function in your js file */

function confirm_vil(val){
    /* Now here you can add popup code to view all data before submit */
}

i hope this is help you..


As far as I can tell your code is fine except for a small syntax error; you're missing a closing parenthesis on the end of the statement. It should be:

$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, array(':city' =>$search_term));

It's often handy to split the arguments out into a separate array so this sort of thing is easily avoidable:

$args = array(':city' => $search_term);
$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, $args);


During migration D6->D7 I get an error message "Integrity constraint violation"

The error message indicates that your underlying database is having a problem. It looks like you've tried the migration multiple times, and that parts of it were successful previously. What the error message is stating is that you are attempting to insert duplicate records into the database, or at least duplicate keys for an existing record. You need to reset/empty the NEW database prior to running migrate and migrate_d2d to remove the problem.


Nice question, but challenging. Basically you want to switch installation profiles (from commons to regular Drupal core). And that yielded some results on Google, including Profile switcher and This blog page. They might be of help during the process.

Before blindly installing modules, please read on, make sure you have proper backups (in fact try to verify your backup actually works) you might have to recover multiple times.
From what I understood these methods are usually from upgrading 'standard' Drupal to another profile, but it might work backwards.

I'd start by disabling and uninstalling (use the uninstall tab) all modules that come prepacked with your profile distribution. This will likely be the features, but there might be more. Then attempt the switch. See which method works best...


Does View UI restrict fields based on filters, etc

In Views 3 in Drupal 6, the UI does not enforce any restriction of fields. (And it does tell you what content type(s) the field exists when you want to select one).  About the only restriction I can think of is the initial View type, eg, a node View restricts you to nodes, taxonomy restricts you to terms, users to users, etc.


How can I add a class to a block with code (development)

Simply, you could use a preprocess function.

function YOURTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] ==  'ID-YOUR-BLOCK') {
    $vars['attributes_array']['class'][] = 'YOUR-CLASS';
  }
}


How to get the content type in the zone/region tpl files?

If you are visiting some node then arg(1) call would return node id.

$nid = arg(1);
$node = node_load($nid);
$node->type


You could create a custom module that looks for the children of that element, if returns 0, look for the parent of the element and print that parents children.

You could also try views, they have a function that helps to deal with results behavior when you don't find any elements related to you query.

Hope this helps.


you can try function themeName_preprocess_page(&$vars, $hook) to override theme theme_hook_suggestions.  More detail you will find here.


You can use the token [site:url] which includes the languages prefix:

Click


How to use both #anchor and ?destination parameter in a node/edit url?

Page fragment is always passed after the query string. Otherwise, the browser will recognize the query string as part of the fragment.

Here's how your URL should look like:

/node/12364/edit?destination=node/12360#anchor

However, if you were asking how to pass anchor to the destination page, you simply need to use encoded hashtag instead. Here's how the URL should look like in this case:

/node/12364/edit?destination=node/12360%23anchor

%23 is encoded # character. See this page for more info.


Product Variation as Thumbnail rather than Dropdown

Once i've got the same problem and I went through this issue Here there are different solution and suggestion.

I was looking for a module who shows the color instead of text so I have chosen this module Fancy Attribute . You can create a taxonomy with a field color and add the hex code of the color, then you can use it as a variation.


On our site, we're using the Language Dropdown module to display translation links.

When we want a language to be accessible to authenticated users only, so that they can translate the contents before showing them to site visitors, we hack the module this way, in lang_dropdown.module, line 192 :

  // @TODO TEMPORARY FIX TO DISABLE ITALIAN TO ANONYMOUS USERS
  global $user;
    if ($user->uid == 0) {
    unset($languages->links['it']);
  }
  // ENDTODO
  //
  // Now we iterate on $languages to build the needed options for the select element.
  foreach ($languages->links as $lang_code => $lang_options) {

Be aware that in this case, the italian contents are not really hidden for someone who would know their paths, but it's sufficient for us.


It was my sever setup after all. Thanks to this post: Is there a common nginx conf for Drupal 7 sites?, I was able to fix the issue. Image styles now work on all my sites.

My initial setup was

    location ~ ^/sites/.*/files/styles/ {
            try_files $uri @rewrite;
    }

The above setup worked for a while and was working for one of my sites but won't work after upgrade for the others for some reason.

I changed it to this

    # Image styles for D7
    location ~* /sites/.*/files/styles/ {
            access_log off;
            expires 30d;
            try_files $uri @rewrite;
    }

and it's working now.


Page not Found error when Views block containing node titles links placed on a specific content type

That link isn't correct. It should be relative to your web root ("/node/49610") and not the current page ("node/49610").


Displaying an image in a programmatically created block (Drupal 7)

Some code could help us help you. But as it is, why not creating the <img> tag yourself based on the file path found in the $nodevariable ?


Assuming that your $resultarray variable in the form actually has some data in it, this code will get you a list of the ids that have been selected:

function friendmodule_form_submit($form, &$form_state) {
  $friend_ids = array_filter($form_state['values']['friends']);
}

When a checkboxes element is submitted all of the original option keys will be in the $form_state['values']'friends'] array, but only the ones that have been selected will have a positive value; the rest will have a value of zero, so you need to use array_filter() to extract only the IDs for options that have been selected.

Also, at the moment you have a syntax error in your submit function (an extra closing )), maybe that's what is causing the error.


Is there any performance implications in calling a view programmatically and set necessary filters?

Definitely not an issue unless you overload the view (but you can do that with the UI also - so no difference there).

On our production architecture we have views UI disabled and all the views are in code under version control however we also have a content team that needs to build 'lightweight views' that pull data from a product catalog and displays it in a particular way. Unfortunately we don't want them running direct SQL or using views UI as they don't completely understand what it all means so we just programmatically create these views and expose a UI to them that they understand. Things like:

What design they want on it
How they want the sorting of the dataset
Whether they need 'no results' text
etc.

Some caveats to doing more complex versions of this are:

Looking out for timing issues. I.e. not having an option available at that call point
Ensuring the correct structure is used. Example: $view->use_ajax vs $view->display[$dispay_id]->filters['use_ajax'].

Neither the less, it is all definitely possible and scales without issues.


Wow do I feel stupid today. I've done this before, but just seemed to have a brain issue.

Very simple:

Add a relationship for "Taxonomy: Terms on node". Select the country vocabulary.
In the sort criteria, select "Taxonomy term: Name" (I believe this gets added by step 1) and make sure the correct relationship choice is selected.


If you're outputting this directly in a template file it would be as simple as:

<?php if (user_is_anonymous()) : ?>

login | register

<?php endif; ?>

If you're using a block then you most likely won't want to put PHP code directly into it as that would involve using the evil eval() function. Instead you could add a new menu and use the block that's automatically created for that menu to output the links.

Since the menu system respects permissions, and the logged in users don't have access to the register or login page, the links simply won't show when a user is logged in.


A module for migrating data from an SQL file only into a new site?

No, that makes no sense. Import it into a database and migrate it from there.


File upload error. Could not move uploaded file

Had a same problem. The best way to fix it is to:

Update the folder permissions on /sites/default to 777
Remove /sites/default/files folder
Go to /admin/config/media/file-system and click save so drupal re-creates the files folder.
Update the folder permissions back to 755 on /sites/default.

On my server when website creates a file or folder, the owner is set to nobody.nobody and since I already had a lot of files in my /sites/default/files folder all I had to do is update the ownership and permissions:

chown -R nobody.nobody ./sites/default/files
chmod -R 755 ./sites/default/files

Good luck!


Meta-Tag Module that can use existing fields

It appears to me that the solution currently being worked on in issue 1838554 is going to be a valid alternative to consider ... At least in the long run (and after the issue status reaches status fixed).


Making some Views Exposed Filters auto-submit but not others

Gonna add my 2 cents too on the topic, since I recently did my reading-into this topic (autosubmit for exposed filters).

Related:

This answer here answers a very similar problem => https://drupal.stackexchange.com/a/198274/57183.

Usefull things to know

The most important piece of relevant documentation lies inside the ctools/js/auto-submit.js file of CTools, at the top of that file.

Form API programming

Following that documentation, you should use the FAPI to programmatically do one of the following:

Exclude the specific filters that you don't want to be trigger an autosubmit (if you have autosubmit active, like in your case):

  If you want to exclude a field from the ctool-auto-submit-full-form
  auto submission, add the class ctools-auto-submit-exclude to the form
  element. With FAPI, add:

  '#attributes' => array('class' =>
  array('ctools-auto-submit-exclude')),

Include the filters that you want to trigger an autosubmit (if you have autosubmit deactivated, not your case)

  On gadgets you want to auto-submit when changed, add the
  ctools-auto-submit class. With FAPI, add:

  '#attributes' => array('class' => array('ctools-auto-submit')),

After that, you already have the functionality you need.

Example to the Example

Following your example here is some example code (with inline comments):

function somemodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // Assumption: Auto-submit is activated via the Views/BEF configuration for all filters
  // Therefore, we will exclude "the text boxes and some of the radio buttons..."

  $exposed_filters_to_deactivate = array(
    'full_text_search', // a text field
    'field_categories', // a radio button
  );

  foreach($exposed_filters_to_deactivate as $exposed_filter_name) {

    // This will disable auto-submitting the form for our filter element
    $form[$exposed_filter_name]['#attributes'] = array('class' => array('ctools-auto-submit-exclude'));

  }

}

This should do it, now the exposed filters full_text_search' and 'field_categories' will not trigger an autosubmit event, all other filters will.

Hope this helps!

Addendum (follow-up question):

To get specific checkboxes from a BEF-checkbox group to trigger a form submit, you need to do the following:

Modify you form_alter implementation:

function somemodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // Assumption: Auto-submit is activated via the Views/BEF configuration for all filters
  // Therefore, we will exclude "the text boxes and some of the radio buttons..."

  $exposed_filters_to_deactivate = array(
    'full_text_search', // a text field
    'field_categories', // a radio button
    'field_areas_of_interest_checkbox', // a BEF-checkboxes widget
  );

  foreach($exposed_filters_to_deactivate as $exposed_filter_name) {

    // This will disable auto-submitting the form for our filter element
    $form[$exposed_filter_name]['#attributes'] = array('class' => array('ctools-auto-submit-exclude'));

  }

  // This is the name of the select values and their target url
  $bef_checkboxes_autosubmit = array(
    '#area_of_interest_checkbox_1',
    '#area_of_interest_checkbox_3',
  );

  // This will attach a javascript to the checkboxes element
  $form['field_areas_of_interest_checkbox']['#attached']['js'][] = drupal_get_path('module', 'somemodule') . '/somemodule.js';
  $form['field_areas_of_interest_checkbox']['#attached']['js'][] = array(
    'data' => array(
      'bef_checkboxes_autosubmit' => array(
        'form_id' => $form['#id'],
        'checkboxes_ids' => $bef_checkboxes_autosubmit,
      )
    ),
    'type' => 'setting'
  );
}

Now, you also need a javascript file (somemodule.js) that will look sth like this:

(function($){

Drupal.behaviors.BEFCustomRedirect = {
  attach: function(context, settings) {
    $(settings.bef_checkboxes_autosubmit.checkboxes_ids).each( function( idx ) {
      $('.ctools-auto-submit-exclude.form-checkboxes input' + this).change(function() {
        $('#' + settings.bef_checkboxes_autosubmit.form_id).submit();
      });
    });
  }
}

})(jQuery);


Configuring drush alias for rsync with exclude paths and file patterns

Your subsequent 'exclude' items in the PHP array are overwriting their previous ones, so the example above only has --exclude=xls

drush help rsync does not explicitly document the syntax for --exclude but I assume that it's similar to --explude-path and that would mean you should do something like this:

'rsync' => array (
  'mode' => 'rlptDz',
  'exclude-paths' => 'css:imagecache:ctools:js:tmp::xmlsitemap',
  'exclude' => '*.tmp:*.doc*:*.zip:*.xls*',
),

EDIT: looking into the example.aliases.drushrc.php there is this tip included:

// if you need multiple exludes, use an rsync exclude file
'exclude-from' => "'/etc/rsync/exclude.rules'",

That's maybe the best way to go.


How to create pages with images in the content?

You should do something like this.

Have two regions, one with the content (ie the left blurry blob). And one called sidebar. The sidebar region would have a block that you would add the right image. And a block (which I assume would be something like a view or maybe it's manually added) to do the Related Links.

Then you could have a content header region for the top part.

So you would end up with

|  Content Header  |
| Content | Sidebar|

Or at least that is how I would do it.


How to strip html comments plus all tags inside it?

This is what theme_closure() does (in theme.inc):

function theme_closure($main = 0) {
  $footer = module_invoke_all('footer', $main);
  return implode("\n", $footer) . drupal_get_js('footer');
}

which means it's going to ask every module to run its footer hook plus get all the js to be put in the footer and return it:

$variables['closure'] = theme('closure');

to populate the closure variable.  So.... if you can't preg_replace() or regex() it out, why not just find what module is putting in there in the first place (seems pretty obvious) and kill it off there?

EDIT/ADDITION:  IF it's a bug, fix it here, otherwise if it's just something you want different, preprocess it.  But it seems to me that a node status check might be in order in the module's footer hook.


Sometimes CCK custom fields get lost although they appear normally in the database

Even though some fields appear correct in the DB, they don't always load up into the edit view, I've noticed similar oddness long ago when trying to replace some image assist tags in the database directly with a php script.

In our case, the edit view (node/edit) begun showing correct data after we purged all caches.

To solve your problem, read and understand how Memcached works from http://en.wikipedia.org/wiki/Memcached -- When making manual DB edits, you must let Memcached know that you've made modifications to tables, this functionality is built into Drupal database handling, hence you'll never notice it when working directly from Drupal, but if you are making custom update queries into the tables, you must let Memcached know there was a change. Was a bit of a surprise to me since I thought it just automaticly works in the background. :)

See the example code part from the wikipedia page how to do it.

..and if you don't use custom update queries to modify those CCK fields, I suspect there must be some sort of a bug in Pressflow itself. Do the changes propagate into the edit view after few hours? Apart from this, there's not really enough info to dig in deeper :/


Code to take quiz again on the next day after user is failed

I could find a solution. It's actually pretty simple. But I don't know whether this is the right way doing it.
Just change $taken like below. Then anybody can retake the test on the next day. Thanks to all for the support.

$taken = db_query("SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = :uid AND nid = :nid AND time_end > :time_end", array(':uid' => $user->uid, ':nid' => $quiz->nid, ':time_end' => strtotime('today')))->fetchField();


How do I add a dropdown field in the commerce form?

I think this is what you are looking for:
/admin/commerce/config/line-items/product/fields

This is where you can add fields to the product line item type.  Make sure you have the Line Item UI module enabled or you might not have access to that UI.


Call a function in one of the modules from a custom PHP file on my Drupal site

All php files inside drupal cannot be directly accessed by incoming request. You should create a endpoint for $.get which can be done by hook_menu

function mymodule_menu() {
  $items['mymodule/endpoint'] = array(
    'page callback' => 'mymodule_page_callback',
    'type' => MENU_CALLBACK
  );
  return $items;
}

function mymodule_page_callback() {
  module_load_includes('php', 'mymodule', 'set_session2');
  // call function here.
}

module_load_includes can include the php file you want from the module. So please place the php file inside the module folder.

In javascript, just update the url to the one you just defined.

...
...
inline:function(){
    $.get("/mymodule/endpoint");
    return $.urlParam('inline', $(this).attr('href'));
},
...
...


How to change field setting using on some condition based?

It looks like you are looking for Formatter Field:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

Emphasis mine.


Use hook_date_combo_process_alter(&$element, &$form_state, $context).

I have used it in commerce discount module: while adding discount.

Example :

  $current_path = current_path();
  if ($current_path == "admin/commerce/store/discounts/add") {
   $element["value"]['#datepicker_options'] = array(
     'minDate' => 0,
   );
   $element["value2"]['#datepicker_options'] = array(
    'minDate' => 0,
   );
  }


How to organise children menu links as tabs in D7?

Instead of OM Maximenu module I used Views Menu module as it easier and I used it only with purpose to attach views block to only one menu link.


How to enable jEditable to perform updates?

Consider looking at the Editable Views module for a possible alternative. Here is a quote about it from its project page:

... lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.
Currently, the following Views fields can be edited:

all FieldAPI fields
node title


You can created an administration page views with you custom entities and to sort it you can use use the DraggableViews module. You would have to create another view to display your entities.


Print taxonomy term field in views-view.tpl.php

For this you need to create the Row style output template file for the view.

For ex: views-view-fields--your_view_name--block.tpl.php.

In this file you get the row array and then you can print your field like:

$row->field_example_field[0]['raw']['value']


Best practice to alter the attributes variable in a Drupal 8 Twig template

If it is your theme then I would do it in a template. Drupal Core converted a lot of preprocess/template to work like that, e.g. the node template.

The advantage is that everything is together as you said and it's a lot easier change it later.

Also if you're a module that defines a template, then someone can just copy that, adjust it and have full control over the classes.


How to create a view that list all child nodes of current page?

Create a view of content type B. (View Type Block)
Create a relationship in that view to the content that contains the reference field by clicking on add a relationship, and search for the name of your reference field)
Create a contextual filter to filter by ID using that reference field. Choose "Provide default value" then "Content ID from URL".
Display your block on the appropriate pages.


I want to re-order the default fields on registration form

You will need to write a custom module for this, there is some good reading here. https://www.drupal.org/developing/modules/7.

You should create a folder like /sites/modules/<module_name>.

Create a <module_name>.info file

name = Custom order of fields
description = Customizes field orders
core = 7.x

Also create a <module_name>.module file an add the following code. The weights control the order, lower is higher on the page.

Please note that this might cause some problems with the field ordering if you add or change fields with the manage fields UI, so you might have to tweak the values a bit later on. You can go the the manage fields page and in the right top click Show row weights, this allows you to change the weights of the fields created with the UI.

function <module_name>_form_user_register_form_alter(&$form, &$form_state) {
  // Move the whole group.
  $form['account']['#weight'] = -10;

  // Move a single property within the group.
  $form['account']['name']['#weight'] = -10;
  $form['account']['mail']['#weight'] = 5;
  $form['account']['pass']['#weight'] = 15;

  // Move a value out of the group and order it.
  $form['name'] = $form['account']['name'];
  unset($form['account']['name']);
  $form['name']['#weight'] = -10;
}

Finally if you want the order to persist on the account edit page, copy all code again into a function named    <module_name>_form_user_account_form_alter(&$form, &$form_state)


How to force users to register with only email address?

Use hook_form_alter to hide the username field

/**
 * Implementation of hook_form_alter.
 */
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form['#form_id'] === 'user_register_form'){
    unset($form['account']['name']);
  }
}

Then you can use hook_user_presave to set the username using the convention you want (the md5 hash of the email is a good candidate):

/**
 * Implementation of hook_user_presave.
 */
function mymodule_user_presave(&$edit, $account, $category){
  $edit['name'] = md5($edit['mail']);
}


Can we use the same path for a different route?

The short answer is NO.
Your would ether make a different path to each function or send an argument to a single function through the url.
eg. different path:

function mymodule_menu() {

    $items['myUrl/dboperation/insert'] = array(
        'title' => 'some custom db operation for insert',
        'page callback' => 'mydboperation1',
        'access callback' => TRUE,
        'file' => 'my_dboperation.inc',
    );

    $items['myUrl/dboperation/delete'] = array(
        'title' => 'some custom db operation for delete',
        'page callback' => 'mydboperation2',
        'access callback' => TRUE,
        'file' => 'my_dboperation.inc',
    );

    return $items;
}

See the hook_menu docs for how to send an argument if you choose to do it that way.


What is the most drupally way to add a slide show (as a block? So I can reuse it in multiple places)

If the content you want to use is already in nodes then you could use Views and Views Slideshow (which uses the cylce plugin you linked to).

With views you can create a block which can be re-used wherever you want in the site.

Learning how to use Views is one of the best things a new user to Drupal can do, it'll provides a lot of nice tools in a point and click interface.


Additional actions when logging using watchdog

In Drupal 7, you would use hook_watchdog() to achieve the task, which is exactly the hook implemented by dblog.module, the module that shows in  admin/reports/dblog the messages added with watchdog().

In Drupal 8, you need to implement a service that is invoked everytime a message is logged, for example with the following code.

mylog.services.yml

services:

  logger.mylog:
    class: Drupal\mylog\Logger\MyLog
    tags:
      - { name: logger }

src/Logger/mylog.php

namespace Drupal\mylog\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

class MyLog implements LoggerInterface {
  use RfcLoggerTrait;

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = array()) {
    // Log the message, for example writing it in a file.
  }

}

The key is how the service is tagged. Without tags: [{ name: logger }], the service would not be used to log the message.

The example code is taken from hook_watchdog() and watchdog() removed. For an example of code implemented from Drupal core, see SysLog.php, which logs the messages in the Syslog server.

class SysLog implements LoggerInterface {
  use RfcLoggerTrait;

  /**
   * A configuration object containing syslog settings.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * The message's placeholders parser.
   *
   * @var \Drupal\Core\Logger\LogMessageParserInterface
   */
  protected $parser;

  /**
   * Stores whether there is a system logger connection opened or not.
   *
   * @var bool
   */
  protected $connectionOpened = FALSE;

  /**
   * Constructs a SysLog object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory object.
   * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
   *   The parser to use when extracting message variables.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LogMessageParserInterface $parser) {
    $this->config = $config_factory
      ->get('syslog.settings');
    $this->parser = $parser;
  }

  /**
   * Opens a connection to the system logger.
   */
  protected function openConnection() {
    if (!$this->connectionOpened) {
      $facility = $this->config
        ->get('facility');
      $this->connectionOpened = openlog($this->config
        ->get('identity'), LOG_NDELAY, $facility);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = []) {
    global $base_url;

    // Ensure we have a connection available.
    $this
      ->openConnection();

    // Populate the message placeholders and then replace them in the message.
    $message_placeholders = $this->parser
      ->parseMessagePlaceholders($message, $context);
    $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders);
    $entry = strtr($this->config
      ->get('format'), [
      '!base_url' => $base_url,
      '!timestamp' => $context['timestamp'],
      '!type' => $context['channel'],
      '!ip' => $context['ip'],
      '!request_uri' => $context['request_uri'],
      '!referer' => $context['referer'],
      '!severity' => $level,
      '!uid' => $context['uid'],
      '!link' => strip_tags($context['link']),
      '!message' => strip_tags($message),
    ]);
    $this
      ->syslogWrapper($level, $entry);
  }

  /**
   * A syslog wrapper to make syslog functionality testable.
   *
   * @param int $level
   *   The syslog priority.
   * @param string $entry
   *   The message to send to syslog function.
   */
  protected function syslogWrapper($level, $entry) {
    syslog($level, $entry);
  }

}

Notice that in Drupal 8, as in Drupal 7, it is possible to have different loggers active at the same time, so the log messages can be recorded in different ways at the same time.


Always set region (Until bug is fixed)

I believe this may be a bug in the code, it seems that is Status/region are toggled it causes problems, to guarantee that it shows for now make sure you set region

    function recentpost_block_info(){
      $blocks['recentpost'] = array(
        'info' => t('Recentpost'),
        'region' => BLOCK_REGION_NONE,
        'status' => true,
        'weight' => 0,
      );
      return $blocks;
    }

The bug seems to be in the function "_block_rehash()" where it checks for empty($block['status'])


How do I link Drush to my Drupal site on Pantheon?

Start off by installing Terminus. Terminus now supports machine tokens; once you set these, up you can authenticate automatically without a password simply by running terminus auth login <email address>.

Once you are authenticated with Terminus, terminus sites aliases will download Drush aliases for all of your Pantheon sites. Since this list can change over time (e.g. when you add or delete sites on Pantheon), you will want to periodically re-run this command.  You might even want to have Terminus log in and update your aliases in your shell startup script (e.g. .bashrc).

Once your aliases are up-to-date, you can use a remote site via:

drush @pantheon.mysitename.dev status


How do I add a non-exposed field to node programatically?

You can add field via structure->content types-> manage fields in your content type, add field that you want to hide.

to hide field in a edit-form/node you can use

function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'formtypename') {
hide($form['fieldmachinname']);
]


I believe Counter creates a block that you can then position. If you need to do it programmatically, see this question and answer: Programmatically printing a block


What happens to Webform data when a component is deleted? Can I change a component type?

When a Webform component is deleted, the submitted data for that component are deleted.  The data for the form's other components are preserved.  I've confirmed these by querying the webform_submitted_data MySQL table on Webform 7.x-3.23.

As user calebtr indicated, there's a "Private" checkbox for each component that can be used as an ersatz delete-but-save-the-data feature, except that logged-in users with the privilege to read results will still see the component on the form (not only in the results).  These fields could be hidden using a stylesheet or custom template, potentially after corralling them into a private fieldset.

The Webform UI does not allow the changing of component type.  I see this information stored in webform_component.fieldset, so you could probably modify it there.  You'd also want to update the component settings in the "extra" column.


How to insert the node comments form into quicktabs?

Here is a recipe for adding comments to a quicktab: http://www.katbailey.net/blog/go-forth-and-tabbify-quicktabs-30-drupal-7


display results from a form in theme-settings.php

When you upload a file it creates an file ID (fid) that we need to call back, then generate the URL and then insert it.
Place this in your template file.

$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
print '';

To print it out with an image style such as thumbnail:

$fid = theme_get_setting('background_file');
print 'uri) . '">';

Not tested.


If I understand correctly, you're looking at either the core blog module (which isn't that great), or a combination of content types and Views.

Start here for blog building information!

With regards to the second part, are you looking to have the user create a site, and then start blogging on it?  Wordpress.org style?  For that you'll firstly need to get a solid theme in place, as well as a working blog.  Secondly, look into Aegir which is a REALLY solid, powerful tool for creating Drupal sites off the back of another site (using a site as an installation profile almost...but not quite).

There are a couple of installation/demonstration videos here and here.


How to programatically add attachments to a user (securely)

You want to try and use the drupal api to move these files into drupal. Since you talk about private files, I assume you've enabled a private filesystem ... or else this discussion is pointless as all your files with be public :).

Once you've done that you could take your hundreds of files and put them in your server someplace and use file_move to place them into the drupal private filesystem using a small php script.

A module tutorial with a private file upload widget can be seen at this blog post and uses the drupal api to store a private file. Private files typically use hook_file_download which that blog post also shows to allow access to the file.


Users can rate product after their order status changed to completed

What I am suggesting is to create a new node type "review" and referenced this to product with references module. Create one view to display reviews or rating on product page. Create one permission or need to hook for permission to access already purchase of same product.


If you're coding up test cases -- not really. You could build the nodes programatically with some test account numbers, etc. But, you'd have to do that by hand. There are alot of tutorials for SimpleTest and creating nodes in drupal.

If you need a GUI to alter many node fields at once, take a look at Views Bulk Operations (VBO).


How to build my SQL statement to export all webform submissions using Forena?

Have a look at this example SQL, which is a so called "Data Block" I created using the Forena module (disclosure: I'm a co-maintainer), and starting from relative path admin/structure/forena/data:

SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

Some details about the example I'm using here:

5 in the WHERE-clause is the node id of the webform (which I can edit via node/5/edit). For this webform, I want to query some of its submissions (= results (which I can browse via node/5/webform-results).
3 in the WHERE-clause is the component id of the webform (which I can edit via node/5/webform/components/3). This particular component is configured as an eMail field, and these collected eMail IDs is what I want to export to a CSV file.

Adapt the hardcoded values 3 and 5 (in the WHERE clause) to fit your requirements. Or transform them in parameters contained in a data block (use this link if you wonder how to do that). Then save this data block with whatever name you want, eg drupal_cust/webform_submissions_data.

Use it as a prototype to build your custom report from it, using the Forena Report designer in which you select the webform_submissions_data data block mentioned above. Which just a few click you could create a report with a "layout" for which the design (in XHTML format) looks like so (also note the "tokens" shown within the td-tags):

          node
          submission
          component
          fieldvalue

          {node}
          {submission}
          {component}
          {fieldvalue}

Don't forget to select the "document types" you want to enable (to export the report), such as "CSV" (as in your question).

For the sake of completeness: the "layout" of a report is what is contained with the  and  tag. Similar to a regular HTML file, Forena will add an appropriate  and  tag in front of it, and surround everything with   and  tag (and also adds a few more lines at the beginning, to make it an XML file. So that when you save your report specifications, the entire file gets saved in your file system as a so called FRX file (FRX = Forena Report XML). For the above report layout, this is how the corresponding FRX file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>

<title>Webform Export</title>
<frx:category>Webform</frx:category>
<frx:options/>
<frx:parameters>
</frx:parameters>
<frx:docgen>
  <frx:doc type="csv"/>
  <frx:doc type="pdf"/>
</frx:docgen>
<frx:fields>
</frx:fields>
<frx:menu/>
<frx:cache/>


Can't log in to Drupal websites after upgrading to OSX Yosemite

That happen to me when I upgraded to OSX Yosemite. I had to reconfigure my apache to make it work. Make sure that the rewrite module in apache is enabled, that you are allowing override. I had a similar problem also with mysql. I had to reinstall again.


Adding users to organic groups in CiviCRM

As @Graham says in his comment, you may want to use the CiviCRM OG Sync module provided with CiviCRM. If your interest is more in coding this, check out how the module does it at https://github.com/civicrm/civicrm-drupal/blob/7.x-master/modules/civicrm_og_sync/civicrm_og_sync.module.


How do I rename Company field and remove Address2 field in a multiple value field in Addressfield module

There's a patch for this in the Addressfield issues queue but it's still under discussion and doesn't work with the latest dev.  You could look at the code in the patch though; it may provide you with insight on how to do what you want.


How to create Media entity and attach to user field

I've found the solution.
I don't need to create a Media entity and append it to the User entity, since the profile picture field type is Image, so I just need to add the file->id() to the specific field.
Here is the code:
$replaced = str_replace("\\", "", $user["picture"]);
$imageData = file_get_contents($replaced);
$fileName = basename($replaced);
$file = file_save_data(
      $imageData,
      "public://". $fileName,
      FileSystemInterface::EXISTS_RENAME
);

$values = array(
      'name' => $user["name"],
      'pass' => [
         'value' => $user["pass"],
         'pre_hashed' => TRUE,
      ],
      'field_user_picture' => array('target_id' =>$file->id()),
      'status' => $user["status"],
      'mail' => $user["mail"],
      'field_first_name' => $user["field_first_name"],
      'field_last_name' => $user["field_last_name"],
);

$userStorage = \Drupal::entityTypeManager()->getStorage('user');
$userEntity = $userStorage->create($values);

Then, if required, I can create the Media entity as following:
$media = Media::create([
          'bundle' => 'image',
          'uid' => $userEntity->id(),
          'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
          'field_media_image' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
          ],
          'thumbnail' => [
             'target_id' => $file->id(),
             'alt' => $file->getFilename(),
          ],
]);

$media->setName($fileName)->setPublished(TRUE)->save();


Superfish - how to integrate main & user menu together

Go to main menu and add My account with path user and add Log out with path user/logout

SO that links will appear as you expected


How do I override a view template in my theme folder properly?

Copy the content of the previous template used and start from there.
It is most likely that the variable you are trying to display are not available in that template.
Consider adding variables using hook_preprocess.


When a user goes from one page to another, how can I see where they came from and where they are going?

Drupal does not track this information, so you need to do it yourself, using sessions (*).

If your pages are not being cached, then the best place to track user progress would probably be in hook_init. This is called very early on in the process - so in effect you have the information of knowing where the user wanted to go before anything is displayed (you could redirect the page at that stage for instance).

If your pages are being cached, in particular using a cache mechanism that bypasses Drupal such as Boost or an external cache proxy, then you will need a Javascript based solution that sends the information back to your site. How to implement this is beyond the scope of this answer.

(*) Note however that Drupal implements it's own session handling, so you need to do some extra work to use session variables (the session variables you set are only available through $_SESSION on the next page load - in the mean time you need to keep track of them yourself. Some people have written example implementations, or you may want to try the session api module).


jQuery ajax request breaks drupal behaviours

I presume you need to add that code with in document ready. Some thing like give

// Code that uses jQuery's $ can follow here.

(function($) {
Drupal.behaviors.mymodule = {
    attach : function(context, settings) {
      jQuery(document).ready(function($) {
         var txtFullname = jQuery('input[id^=my_dynamic_id]');

         // do ajax request
         jQuery.ajax({
            type : "POST",
            url : 'http://example.com/retrieve_information',
            data : {
                'order' : settings.order_id
            },
            dataType : "json",
            success : function(data) {
                txtFullname.val(data.fullname);
            }
        });
      });
    }
};
}(jQuery));


programmatically add an existing entity reference autocomplete field in custom form

If you are using the references module's node_reference field, then, in your custom form, you'll want to create a field that uses the node_reference's autocomplete, like so:

$form['referenced_field'] = array(
  '#title' => 'Referenced field title',
  '#description' => t('Referenced field description.'),
  '#type' => 'textfield',
  '#autocomplete_path' => 'node_reference/autocomplete',
  '#required' => TRUE,  // Optional depending on your circumstance.
);

See node_reference.module line 892 for more details on parameters, etc.


How to find the right token to use in a rule for sending an email to the node author?

Sometimes, tokens aren't shown from the Rules module user interface.
Manually enter [node:author:mail]. If it's not an allowed token, the module would show an error message.


In the render pipeline placeholdering is used together with lazy building, see this example from the status messages:

\Drupal\Core\Render\Element\StatusMessages

  /**
   * #pre_render callback to generate a placeholder.
   *
   * @param array $element
   *   A renderable array.
   *
   * @return array
   *   The updated renderable array containing the placeholder.
   */
  public static function generatePlaceholder(array $element) {
    $element = [
      '#lazy_builder' => [get_class() . '::renderMessages', [$element['#display']]],
      '#create_placeholder' => TRUE,
    ];

    // Directly create a placeholder as we need this to be placeholdered
    // regardless if this is a POST or GET request.
    // @todo remove this when https://www.drupal.org/node/2367555 lands.
    return \Drupal::service('render_placeholder_generator')->createPlaceholder($element);
  }

Then, before caching, the renderer puts instead of the content a static placeholder, which will be, on delivery, replaced with the actual content from the lazy builder.

The placeholdering is done here right away, see the last comment in the code. Which is good for demonstration purpose. If you run this code the result will look like this:

<drupal-render-placeholder callback="Drupal\Core\Render\Element\StatusMessages::renderMessages" arguments="..." token="..."></drupal-render-placeholder>

By the way, the content of the placeholder tag in the markup is not important, it only has to be unique to be replaceable. The details are for debugging purpose only. The response event subscriber uses the information attached to ['#attached']['placeholders'].

A placeholder strategy is for example BigPipe, which uses another strategy to deliver the placeholder content after page load.


How to remove submitted & author information on Entityform submission view?

That value is a t() function call here http://cgit.drupalcode.org/entityform/tree/entityform.module#n1092

This is used by the custom EntityClass provided by the EntityForms module in the buildContent function:
http://cgit.drupalcode.org/entityform/tree/entityform.module#n1226

This is PHP class. You have many options:

See if there is a TPL file defined for this submission and alter the default output with your own.
Try to use String Overrides to and set the t() string to "" in the Admin interface for String Overrides. The string you'd look to replace is "Submitted by !name on !date". This may have un-desired affects for other content types and non-Anonymous users ...
Your other option is to replace the custom EntityForms class with 1 of your own using a database query to change the system table's entry for the EntityForms class to 1 you copy-paste of the same name and change the 1 line of code in it :/ (I don't really recommend this.
Lastly you can use hook_page_alter to scan for the string in the content array of the Node on the page and remove the text out.
Or really lastly, you can hide the text using CSS rules.


How to disable billing address in Drupal Commerce while using Paypal WPS

If you do not need Billing Address section at all, it should be as simple as dragging Billing Information under disabled from any of checkout/review step.
Go to page 'admin/commerce/config/checkout' in order to disable Billing Section.

If you want Billing Address section to vanish conditionally based on payment method opted(in case you have multiple way of payment) then it is already answered here by Ryan himself.


Conditionally display field based on comparison to other field

I finally solved the problem by adding a template for the content type. This allowed me to simplify the preprocess function:

function mytheme_preprocess_node__event(&$variables) {
  $startdate = $variables['content']['field_eventdate'][0]['#markup'];
  $enddate = $variables['content']['field_eventend'][0]['#markup'];

  if ($startdate === $enddate) {
    unset($variables['content']['field_eventend']);
  }
}

I then copied the node.html.twig template to node--event.html.twig. I only changed the main {{ content }} part into:

    {{ content.field_tags }}
    {{ content.field_eventlocation }}
    <div class="event_dates clearfix">
      {{ content.field_eventdate }}
      {% if content.field_eventend %}
        &nbsp;&ndash; {{ content.field_eventend }}
      {% endif %}
    </div>
    {{ content|without('field_tags', 'field_eventlocation', 'field_eventdate', 'field_eventend') }}

This replaced my attempt to create and modify field--field-eventdate.html.twig template.

Maybe this is not the best option, but at least it works.


Publisher and Editor only without publishing rights role possible?

What you want is a workflow, for example "Draft", "Requires Review" and "Published". The Editor can only take content to "requires review" while the publisher has permissions to change the workflow state to Published which is then visible to all users on the site.

http://drupal.org/project/workflow

If you want to get really fancy you could use Rules to automatically email the publisher when content goes into "requires review" so the Publisher gets a notification. or you could setup a view for them...


Here is the my solution inspired from:

http://www.webomelette.com/creating-custom-views-filter-drupal-8
http://www.sitepoint.com/drupal-8-version-entityfieldquery/

Thanks to Danny Sipos

I already had a dedicated custom module for this project where I added the following:

mymodule.views.inc

<?php
/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(array &$data)
{
    $data['node_field_data']['related_content_titles'] = array(
        'title' => t('Related content titles'),
        'filter' => array(
            'title' => t('Related content titles'),
            'help' => t('Specify a list of titles an content node can have.'),
            'field' => 'nid',
            'id' => 'mymodule_related_content_titles'
        ),
    );
}

src/Plugin/views/filter/RelatedContentTitles.php

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\ManyToOne;
use Drupal\views\ViewExecutable;

/**
 * Filters by given list of event title options.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("mymodule_related_content_titles")
 */
class RelatedContentTitles extends ManyToOne
{
    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL)
    {
        parent::init($view, $display, $options);
        $this->valueTitle = t('Allowed event titles');
        $this->definition['options callback'] = array($this, 'generateOptions');
    }

    /**
     * Helper function that generates the options.
     * @return array
     */
    public function generateOptions()
    {
        $storage = \Drupal::entityManager()->getStorage('node');

        $relatedContentQuery = \Drupal::entityQuery('node')
            ->condition('type', array('event', 'story'), 'IN')
            ->condition('status', 1);

        $relatedContentIds = $relatedContentQuery->execute();

        $res = array();
        foreach ($relatedContentIds as $contentId) {
            $res[$contentId] = $storage->load($contentId)->getTitle();
        }

        return $res;
    }
}

When ceating the view listing my articles where I want to expose the related event filter I had to :

add a relationship field_article_associated_event: Content
add a filter criteria of my type Related content titles, select the perviously cerated relationship for the field Relationshi, check Expose this filter to visitors, to allow them to change it


Displaying fields in entity_reference data

I'd recommend replacing program field with a custom View of Songs. That will allow you to pull any data that you'd need from the Song content type.

The least cumbersome (and I'd say flexible) way of doing involves two steps:

Create a View of Songs that will take a Node ID (NID as a contextual filter)
Override the field template for the Program field and instead of rendering the default template of the field - render a View crated in Step 1.

I'll detail each step, creating a View for this purpose can be somewhat complex, but that will give you great control over how you want to present the information.

STEP 1 - CREATE A VIEW

Create new View of "Content" of the type "Concert". Select Block instead of Page. Make it a view of "Unformatted List" of "Fields". In the number of items put 0 to display all items.
Add new "Contextual Filter" - "Content: NID". Provide default value: "content ID from URL"
Add new Relationship to "Entity Reference: field_program", which will give you a connection to each song selected in the filed Program for the particular node. Make relationship required.
Now remove all default fields that were placed in your View and add fields from the Songs content type (Title and Composer). Select the relationship that you added in previous step to each field (this is important, otherwise View won't work).
You can test your View by entering a Node Id from any existing Concert nodes into Views Preview placeholder for contextual filters. Without given contextual filter, preview will not show you any results (that's expected)

STEP 2 - OVERRIDE PROGRAM FIELD TEMPLATE

Copy field.tpl.php from modules/field/theme and place it into your current theme template folder.
Rename the file. Now here you need to decide if you wish to override the display of the field "Program" everywhere on your website or only when it is displayed in content type Concert.

field--field-name--content-type.tpl.php - Will target a specific field name within a specific content type.
field--field-name.tpl.php - Will target all fields of a specific machine name.

I'd recommend starting with the first choice - field--field-program--concert.tpl.php

Clear cache to let Drupal see your new template.

Now remove everything that was originally in that template, you can leave just the top comments for the sake of maintainability, etc. And add the code below - which will embed the view you create in the STEP 1.

<?php
print views_embed_view('machine_name_of_the_view', 'machine_name_of_the_block', $element['#object']->nid);
?>

$element['#object']->nid - is an argument that you can to your View. It is not absolutely necessary to place it here, because our View already has contextual filter that takes Content ID from Url by default. So additional argument just gives another chance to override that argument, or make sure that it will be passed appropriately.

That's it. Give it a whirl. Don't forget to test.


How to block Webform spam based on keyword strings?

Try Webform Validation module. It adds validation options for webforms. One of these extra options is "words blacklist", where you can specify the list of strings that should not appear in your field. The spammers will get validation error and will not be able to submit the form.


Most core (and contrib) modules make use of the system_settings_form() function which handily wraps around a form, and saves element values as variables automatically.

function MYMODULE_admin_settings() {
  $types = node_type_get_types();

  $form['content_types'] = array(
    '#type' => 'fieldset',
    '#title' => t('Content types'),
    '#description' => t('test'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  foreach ($types as $typename => $type) {
    $form['content_types']["MYMODULE_settings_$typename"] = array(
        '#type' => 'checkbox',
        '#title' => $type->name,,
        '#default_value' => variable_get("MYMODULE_settings_$typename", 0)
    );
  }
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
  );

  return system_settings_form($form);

}

You can then grab the value anywhere else in code like this (using the 'page' content type as an example):

$val = variable_get('MYMODULE_settings_page');

Which is a bit counter-intuitive. You might want to make use of a checkboxes type instead, e.g.

$options = array();
foreach ($types as $typename => $type) {
  $options[$typename] = $type->name;
}
$form['content_types']['MYMODULE_content_types'] = array(
  '#type' => 'checkboxes',
  '#title' => $type->name,
  '#options' => $options,
  '#default_value' => variable_get('MYMODULE_content_types', array())
);

Then you can get an array of all selected content types like this:

$selected_types = array_filter(variable_get('MYMODULE_content_types', array()));


How to show different delta of a multi-value token?

You can get to the delta values of multi-value fields with the help of Compound token (it doesn't have to be a compound token, it can be something like [node:field_test:und:1:value]).

As you've already figured out you need Token filter to evaluate tokens in Textarea fields, such as Views Headers or Footers.


How do I find the role id from role name?

Knowing the machine name of the role, it is enough to use user_role_load_by_name().

if ($role = user_role_load_by_name('Role Name')) {
  // The role ID is in $role->rid.
}

If the Role might not exist...

$role = user_role_load_by_name('Role Name');

$role_id = $role ? $role->rid : NULL;


Error entries in Watchdog duplicated dozen and hundreds of times

The best is to check what these entries are and try to fix them, e.g.:

when the warning/error comes from contrib module, consider searching for this specific error and find out what's the solution (sometimes it may be misconfigured module),
when warnings comes from your custom modules or themes, consider fixing it manually.

If you think you cannot fix the source of the issues, you should introduce caching mechanism to your site such as:

Redis/Memcached which will limit enormous number of inserts into cache tables.
Varnish to cache the front end pages.

or limit the entries by:

limiting watchdog entries to warnings only (ignoring PHP notices) or silence all of them.
disabling dblog (database logging) module completely and switch to syslog logging instead.

See also: How do you improve Drupal performance?


Getting AJAX 200 error when view with custom exposed filter has no results

See my third Edit to the OP.  The problem has magically been resolved by using a clone of the original block display.  I don't know why this is the case, but that did the trick.


The Domain Access module was created for exactly the sort of use-case you're describing.

  The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

It'll take a fair amount of work to convert 6 individual sites into a single Domain Access site, but if that's the workflow you're looking for, I don't think you'll find an easier or more complete existing solution.


Alter menu link path based on content type

wow I feel silly. You can still preprocess the menu template in Drupal 8. So by using hook_preprocess_menu__main() it looks like I will have access to everything I need and not have to do everything in the Twig template.


For Views 3 , the given answers are partially incorrect. Tokens are allowed in the header area of view blocks. The only tokens available are for the fields used in the view. So you can set the field that will be used only for its token to hide.

You have to select the Global: Text area option in Header, check Use replacement tokens from the first row and select the token from the Replacement Patterns dropdown.


This has to do with the CKeditor's javascript library rather than drupal. There are several sites and questions around on how to do this, for example this. I haven't tried this, but my guess is that you need to modify the config.js file that lives in your /sites/all/library/ckeditor folder of your drupal installation.


content administration page not found, and user manager page not found

Admin_views was turned on and not functioning causing the overridden admin url aliases it uses to throw this error.

After disabling, the admin screens returned to normal function.


Show custom content in Main Page Summary

You can find node.tpl.php inside your sites/all/themes/yourtheme folder. $content is generated in that file.


Admin pages including content edit are exremely slow

best answer: You need to profile the PHP code in order to see what is causing the slowdown. Also check firebug to see if anything is taking a long time to download. Go through all the slides  from my DIY Drupal 7 Performance presentation.

quick answer: You can try the first 4 patches listed in the Performance wiki as these are things that I identified on our setup as being slow.


Try making a function using hook_form() and calling it in your $block['content'] property?

$block['content'] = example_module_form($node);


I changed the "Browser and proxy cache maximum age" setting in Configuration > Development > Performance and it appeared to do the trick.  It was previously set to "no caching".


Filtering among Exposed Filters : Parent/Child relationship between two Exposed Filter in Drupal View

Look at my currently developing site's exposed filter(where 'Бренд' and 'Модель' fields): Link

If you want to achive this kind of functionality then you can achieve it like this. First you need to alter exposed filter function:

function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-VIEWS_NAME_VIEWS_DISPLAY') {
    if(!empty($form_state['values'])) {
      $form_state['input'] = array_merge($form_state['input'],$form_state['values']);
    }

    // Marks
    $mark_childs = populate_terms_by_vocab('transport_models', TRUE, FALSE);
    $form['field_adv_mark_tid']['#options'] = array('All' => t('--Выберите')) + $mark_childs;
    $form['field_adv_mark_tid']['#ajax'] = array(
      'callback' => 'adv_mark_callback',
      'wrapper' => 'model-wrapper',
      'effect' => 'none',
      'progress' => array(
        'type' => 'throbber',
        'message' => '',
      ),
    );
    // marks end

    // Models begin
    $selectedMark = isset($form_state['input']['field_adv_mark_tid']) ? $form_state['input']['field_adv_mark_tid'] : NULL;

    if($selectedMark != NULL || $selectedMark != FALSE) {
      $model_childs = populate_terms_by_vocab('transport_models', FALSE, $selectedMark);
    }
    elseif($selectedMark == NULL || $selectedMark == FALSE) {
      $model_childs = array();
    }

    $form['field_adv_model_tid']['#options'] = array('All' => t('--Выберите')) + $model_childs;
    $form['field_adv_model_tid']['#prefix'] = '
';
    $form['field_adv_model_tid']['#suffix'] = '
';
    // models end
  }
}

// This is an Ajax callback for $form['field_adv_mark_tid']['#ajax']
function adv_mark_callback($form, $form_state) {
  return $form['field_adv_model_tid'];
}

// This is a helper function which returns terms (suitable for form selectlist, checkboxes or radios..)
function populate_terms_by_vocab($vocabulary_machine_name, $only_parents = TRUE, $parent = FALSE) {
  $vocab = taxonomy_vocabulary_machine_name_load($vocabulary_machine_name);
  $terms = array();
  if($parent == FALSE) {
    $terms = taxonomy_get_tree($vocab->vid, 0, NULL, FALSE);
  }
  elseif($parent == TRUE) {
    $terms = taxonomy_get_tree($vocab->vid, $parent, NULL, FALSE);
  }

  $child_terms = array();
  foreach($terms as $key => $value) {
    if($only_parents && $terms[$key]->parents[0] == 0) {
      $child_terms[$terms[$key]->tid] = $terms[$key]->name;
    }
    elseif($only_parents == FALSE && $terms[$key]->parents[0] != 0) {
      $child_terms[$terms[$key]->tid] = $terms[$key]->name;
    }
  }

  return $child_terms;
}

I thinks the logic is the same.. In my case, I am adding to my entity type the two same term reference fields, and on content creation form I am displaying them as different parent field and child field (with pre-render function). By that, first field is holding the top level terms, the second field is holding child terms. And by views ui I am exposing them separately. And, that piece of code is displaying them as I want..


how to show node title when mouseover on image in the node by drupal views?

I don't think you can do that using views. However you can "hack" a way to add title element to a div, for instance.

go to your view config page

add a node: title field.

edit the node: title field.

tick "Exclude from display" and "strip HTML tags"

click save

move the title node to top of the fields.

edit your image field and tick "Rewrite the output of this field"

a textarea appears. write this code in the textarea

[image]

Note: the [fields] are tokens. If you already have a title field, you don't need to exlude it, you can re-use it.

if the image displays another title its because the module automatically sets a title tag to the image. You can either change this tag with javascript:

document.getElementById("idElement").setAttribute("Title", "title");

or edit your image module and set the page title to be your title tag.


you can use lightbox2 module.

And here is the description that how will you use it.