# Question
Title: Saving additional node fields programmatically
I have the following content type called `stars` with the following fields:

```
Title
Body
Distance (this is an added text field)

```

Here's what I have to save the node, but how do I add the distance field?

```
$node = new stdClass();
$node->type = "stars";
$node->status = 0;
$node->uid = $user->uid;
$node->title = 'This is the title';
$node->sticky = 0;
$node->language = 'en';

// Let's add standard body field
$node->body['und'][0]['format'] = 'filtered_html';
$node->body['und'][0]['value'] = 'Body info';

$node->revision = 0;

node_save($node);

```

# Answer
> 4 votes
You'd need to set the value for the *Distance* field just like you have already for the *Body* field. Lets assume that the name of your *Distance* field is `field_star_distance`. (To find the name of your field, check if you have the `Field UI` module enabled and head over to the *Manage fields* page for your content type)

```
// Your code
$node->{'field_star_distance'}[LANGUAGE_NONE][0]['value'] = 100;
// Your code

```

The general skeleton for setting the value for a field of an entity is:

```
$entity->{$field_name}[$language][$delta][$field_property] = $value

```

To understand the different field properties for a given field (like `value` in our example here), you need to look up its schema (see `hook_field_schema()` and see `text_field_schema()`)

To see if `$delta` can be `> 1`, you need to check the cardinality of the field instance.

# Answer
> -1 votes
$node-\>field\_name\[LANGUAGE\_NONE\]\[0\]\['value'\]= $name;

where 'field\_name\[LANGUAGE\_NONE\]\[0\]\['value'\] 'is the name of the extra added node field.you can get this name by inspect property of browser.

---
Tags: 7
---


title: openlog() and syslog() warning

text:
# Question
Title: openlog() and syslog() warning
After Cron ran and clean all cashes in drupal 8 I get this:

Warning: openlog() has been disabled for security reasons in /home/inatcent/public\_html/core/modules/syslog/src/Logger/SysLog.php on line 59

Warning: syslog() has been disabled for security reasons in /home/inatcent/public\_html/core/modules/syslog/src/Logger/SysLog.php on line 88

Warning: openlog() has been disabled for security reasons in /home/inatcent/public\_html/core/modules/syslog/src/Logger/SysLog.php on line 59

Warning: syslog() has been disabled for security reasons in /home/inatcent/public\_html/core/modules/syslog/src/Logger/SysLog.php on line 88

Does somebody know why this is happen?

# Answer
The error messages couldn't really be much clearer:

> openlog() **has been disabled** for security reasons

Emphasis mine.

So the functions have been disabled in your PHP config. To use them, you'll need to change your PHP config and remove `openlog` and `syslog` from the `disable_functions` directive.

If you're on shared hosting, you probably don't have this kind of access. In that case you should contact your host to ask them what their solution is, or move the site to a host that hasn't disabled those functions.

You could also obviously just disable the core Syslog module, and that will remove the errors; but, as yo'd expect, you won't be able to log to the syslog any more.
> 2 votes

---
Tags: 8
---


# Question
Title: How to process a multiple values field (comma separated) in a Rules Action?
I am using modules "SMS Framework",Clickatell for sending message and I have configured all the settings which was required. I have also created a rule where node (Article) be saved and send a message.

It is working good when I use single mobile number but unfortunately it is not working when I use multiple mobile number with comma separated.

# Answer
The rules action calls `sms_send`, whose first argument is:

> The destination number.

i.e. singular. So the module doesn't have support for sending to multiple, comma-separated numbers in one go through rules. It is in alpha to be fair, so it's not likely to be fully-featured yet.

Two ways you could get around this limitation (there are probably more):

1. Create a custom rules action which splits the incoming string by comma, then loops over and calls `sms_send` on each. If you choose this method, contributing the code back to the project would I'm sure be greatly appreciated.
2. Restructure your workflow so the existing rule is invoked once, in a loop, for each phone number.
> 0 votes

# Answer
### Step 1: Transform your data into a list

The Rules Data Transforms module (***DEV*** version only!) may help to solve your issue. It supports the transformation of a string of values separated by some separator (such as a comma) into a list. So you should be able to transform your "*multiple mobile number with comma separated*" (as in your question) into a list. There doesn't seem to be any documentation available about this module, except:

### Step 2: Typical list processing with Rules

After you succeeded in transforming your mobile numbers into a list, you should be able to perform the typical list processing using Rules. If you're not familiar with that, have a look at the tutorial titled "Lists and loops". Starting from about 7:00, it shows how in a Rules Action you can access the 1st, or 2nd, or ... value of a multiple value field, provided you also included a Rules Condition like "Content is of type" (related to the multi value field). If you consider the `field_tags` in this video as the equivalent of your field containing the mobile numbers, it's pretty similar to your case. Have a look at this video from the beginning to understand how this rule works.

Specific to your case, all you'd have to do is to adapt the Rules Action in the rule you already have, i.e. by adding an appropriate loop, and then add a action for each list item in that loop (which is similar to the Rules Action you already have).
> 0 votes

---
Tags: 7, commerce, rules
---


title: Altering the breadcrumb contents

text:
# Question
Title: Altering the breadcrumb contents
I'm trying to use this hook in order to alter a breadcrumb link :

```
hook_menu_breadcrumb_alter(&$active_trail, $item)

```

The hook don't seem to be called.

I've tried :

* Using the hook on a theme
* Using the hook on a custom module (breadcrumb\_finder\_fix)
* Clearing all caches using Drush

I have the Devel module installed and activated, and the following doesn't produce any output.

```
function breadcrumb_finder_fix_menu_breadcrumb_alter(&$active_trail, $item) {
    drupal_set_message(krumo($active_trail));
}

```

Any ideas ? Directions ? Please advise.

OBS : I've read this answer : https://drupal.stackexchange.com/a/7659/12647

# Answer
> 5 votes
Here is a snippet to show how you can alter breadcrumbs.

Keep in mind the following:

* This method changes breadcrumbs at theme level, which is the last place to change any thing before it reaches to template files, so changing here will not allow other module to change the breadcrumbs later.
* Consider this way as the last option to alter your breadcrumbs.
* Add this snippet to template.php file of your theme.

```
function THEME_NAME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  // check to ensure this is the one you want to alter
  // Custom rebuild process of breadcrumb with custom links.
  if ($breadcrumb[1] == 'your_breadcrumb_id') {
    // linking to home page
    $links[0] = l(t('Home'), '<front>');

    // Keeping the trail/current page as non linked
    $links[1] = ('your desired breadcrumb');
    drupal_set_breadcrumb($links);
  }
}

```

# Answer
> 13 votes
Probably a little late to respond, but I came across this thread this morning whilst looking for a way to override the breadcrumb in Drupal 7, it helped a little so I thought I would add my solution.

This creates extra crumbs based on content types and adds the current page to the crumb. I'm using this to add a crumb to a filtering view seen before the given node.

```
function MYMODULE_menu_breadcrumb_alter(&$active_trail, $item) {

    //STORE THE LAST ITEM
    $end = end($active_trail);

    foreach ($active_trail as $key => $crumb){

        //CHECK AGAINST NODE TYPE
        if($crumb['map'][1]->type == 'NODE_MACHINE_NAME'){

            //INSERT THE REPLACEMENT CRUMB
            $active_trail[$key] = array(
                'title' => t("Title"),
                'href' => 'PATH',
                'link_path' => 'PATH',
                'localized_options' => array(),
                'type' => 0
            );
            //RECREATE ITEM
            $active_trail[] = $crumb;
        }

    }

    //SHOW CURRENT PAGE IN BREADCRUMB BY DUPLICATING THE LAST ARRAY ITEM IN ACTIVE_TRAIL

    if (!drupal_is_front_page()) {
        if ($item['href'] == $end['href']) {
            $active_trail[] = $end;
        }
    }

}

```

# Answer
> 9 votes
hook\_menu\_breadcrumb\_alter() does *not work* on pages where drupal\_set\_breadcrumb() has been called before.

hook\_menu\_breadcrumb\_alter() is invoked from menu\_get\_active\_breadcrumb(). This is called from drupal\_get\_breadcrumb(), but *only if* no breadcrumb has been previously set with drupal\_set\_breadcrumb().

It does not look like drupal\_set\_breadcrumb() is called from the user page. But maybe there is a contrib module which does that. You could put a dpm() or ddebug\_backtrace() in drupal\_set\_breadcrumb() to see if this is the case (needs the devel module to be enabled, and you having permission to see devel information).

You can use hook\_preprocess\_breadcrumb() instead, but this requires to parse the breadcrumb link you want to alter. Because in this hook the breadcrumb links are already rendered as html, so you need regular expressions (preg\_match()) or similar to determine e.g. the url.

A much better solution is to use one of the various breadcrumb-customizing modules that are available for Drupal.

# Answer
> 2 votes
this may not be the most efficient way, but try:

`function THEME_breadcrumb($variables)`

and then read the variables.

... also my god I hate breadcrumbs. so much.

# Answer
> 1 votes
If you only need to alter the breadcrumb on a specific page maybe the following solution can help you. The example updates the breadcrumb for a edit form.

```
$breadcrumb = array();
$breadcrumb[] = l(t('Home'), '<front>');
$breadcrumb[] = l(t('Nodes listing'), 'nodes/listing');
# Update breadcrumb on the edit form
if (isset($form['nid']) && (is_numeric($form['nid']['#value']))) {
    $breadcrumb[] = l($form['#node']->title, 'node/' . $node->nid);
}

drupal_set_breadcrumb($breadcrumb);

```

Another Drupal way is to user `hook_menu_breadcrumb_alter` but make sure to name it `YOUR_MODULE_menu_breadcrumb_alter` and clear the cache after adding the function.

Or also `theme_breadcrumb` is a Drupal way to update the breadcrumb but in this hook you should only change the breadcrumb's markup, not links.

# Answer
> 1 votes
the `THEME_NAME_breadcrumb` did not work for me. However, I did manage to override breadcrumb with this function:

```
function MODULE_node_view_alter(&$build) {
  $node = $build['#node'];
  if ($build['#view_mode'] == 'full' && $node->type == 'CONTENT_TYPE') {
    $breadcrumb = array();
    $breadcrumb[] = l('Home', '<front>');
    $breadcrumb[] = l('People', 'group/node/' . arg(2) . '/people');
    $breadcrumb[] = l('Attendance', 'group/node/' . arg(2) . '/people/attendance');
    drupal_set_breadcrumb($breadcrumb);
  }
}

```

credit goes to: https://stackoverflow.com/questions/10087168/how-to-add-breadcrumb

# Answer
> 0 votes
```
function MODULE_menu_breadcrumb_alter(&$active_trail, $item) {
  // Store the last item
  $end = end($active_trail);
  foreach ($active_trail as $key => $crumb){
    // Check against the node type
    if ($crumb['map'][1]->type == 'CONTENT_TYPE' && $crumb['link_path'] == 'node/%') {
      // Replace the breadcrumb
      $active_trail[$key] = array(
        'title' => t("Title"),
        'href' => 'PATH',
        'link_path' => 'PATH',
        'localized_options' => array(),
        'type' => 0
      );
    }
  }
}

```

this much code is sufficient to modify breadcrumb url.

---
Tags: 7, hooks, breadcrumbs
---


title: Change UID for watchdog message

text:
# Question
Title: Change UID for watchdog message
In Drupal 8 with DbLog logger, I am trying to log some audit messages to a different user than the currently logged-in user. Unfortunately, it looks like something is overwriting my context.

I tried `\Drupal::logger("proreos")->info("bla", ['uid' => 5]);` and `\Drupal::logger("proreos")->info("bla", ['user' => User::load(5)]);`, but neither of them worked. In both the cases, the current user ID was instead used.

How can I use a different user ID?

To clarify: This is not about logging another uid, it is about assigning the row in watchdog to a different user.

# Answer
Logger will always log for the current user, except you provide your own logging service.

The context is used to replace placeholders in the message, see here, so to get the userid in the message, use this:

```
\Drupal::logger("proreos")->info("bla @uid", array('@uid' => 5));

```
> 1 votes

# Answer
The correct code is the following one.

```
\Drupal::logger("proreos")->info("bla %uid", ['%uid' => 5]);

```

This is similar to what Drupal does in `user_cancel()`.

```
  if (!$account) {
    drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
    \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', array('%id' => $uid));
    return;
  }

```

Consider the first and the second argument of `error()` or `info()` as the first two arguments of `t()`.
> 0 votes

# Answer
Thanks to you all. I appreciate that watchdog is not the correct table for my needs. I have created my own audit table and logging service now.
> 0 votes

---
Tags: 8, log-messages
---


# Question
Title: In Drupal 8 can a developer inject Full HTML Pages?
I have done a lot of work in WordPress but want to develop a new site in Drupal 8. I have two specific questions before I start on my site.

1. Is it possible to inject full HTML pages via PHP into a Drupal 8 environment? I have full HTML content being served from an API for SEO purposes.

If the answer to #1 is NO:

2. Is it possible to change header and footer based on specific paths? So everything at /articles will get a certain header or footer? In this case I would want to pass an incomplete tag and have the API call close the head tag and provide the body.

# Answer
> 1 votes
Usually you will not inject full HTML pages to Drupal, more likely you will inject your content as node-content. Then use a convenient theme for your needs.

Drupal has - like wordpress - themes. These are nested pieces of HTML code with TWIG syntax for dynamic content.

Unlike, wordpress, you can specify different themes for different URI paths (look for keyword theme\_negotiator). I.e., you may configure to use an "article-theme" on path /articles.

But this is only the beginning of a very long story...

# Answer
> 1 votes
The problem is that you are trying to think in WP categories when you approach Drupal. If you persist like this, you may succeed, but the result will be very unprofessional and sub-standard.

While the answer is YES, you can serve full custom html pages, by creating them as templates for corresponding end pages, that is almost never a good idea.

In Drupal, header and footer are just regions, into which you can assign blocks. You can create different blocks with different content, assign them to the header and footer, and then set in their block visibility conditions settings to show then on specific pages (there are more settings there as you will see). Then, you will do it right.

Just spend some time to learn the basic Drupal architecture. After having worked on a number of WP projects, I have noticed, that a lot of things that you would do in WP in code, you can architecture in Drupal via the UIs.

Here is a link to the Drupal concepts documentation: https://www.drupal.org/documentation/concepts

---
Tags: hooks
---


title: Merge menus for mobile menu

text:
# Question
Title: Merge menus for mobile menu
Hi I have 3 menus on my site and for display on mobile/tablet I would like to merge these menus to only 1 menu. Do you know how to do it. I tried to use menu\_tree\_all\_data

and then merge them but I get Call to undefined function menu\_tree\_all\_data. I'am confused that the function doesn't exist.

# Answer
> 1 votes
As I'm also looking for a solution to this issue I've come a bit further and maybe it will get you in the right direction.

To load a menu in Drupal 8 you can put this in a `theme_preprocess_page` in your `.theme`-file.

```
  $menu_tree = \Drupal::menuTree();
  $menu_name = 'main';

  // Build the typical default set of menu tree parameters.
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

  // Load the tree based on this set of parameters.
  $tree = $menu_tree->load($menu_name, $parameters);

  // Transform the tree using the manipulators you want.
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree->build($tree);
  $menu_html = \Drupal::service('renderer')->renderPlain($menu);

```

I have not yet worked out how to merge different menus into one big menu but I will let you know if I come up with a solution. You can find out more about the code above at Drupal 8.2.x » menu.api.php which is where I found it.

Ok, I now have found the solution which I found in the module Responsive and off-canvas menu

```
  $menus = array("main-menu","footer-menu","utility-menu");

  $combined_tree = array();
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters(trim($menus[0]));
  $manipulators = array(
    // Show links to nodes that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkNodeAccess'),
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  // Force the entire tree to be build by setting expandParents to an
  // empty array.
  $parameters->expandedParents = array();
  // Iterate over the menus and merge them together.
  foreach($menus as $menu_name) {
    $tree_items = $menu_tree->load(trim($menu_name), $parameters);
    $tree_manipulated = $menu_tree->transform($tree_items, $manipulators);
    $combined_tree = array_merge($combined_tree, $tree_manipulated);
  }

  $menu = $menu_tree->build($combined_tree);

  $vars['mobile_menu'] = array(
    '#prefix' => '<div class="off-canvas-wrapper"><div id="off-canvas">',
    '#suffix' => '</div></div>',
    '#markup' => \Drupal::service("renderer")->renderRoot($menu),
  );

```

If you put this in your `theme_preprocess_page` in your `.theme`-file you could then in your `page.html.twig` print the twig variable `{{ mobile_menu }}`.

---
Tags: 8, navigation
---


# Question
Title: How can I make a node title input form in a block?
Im on d7. I want to have a block on the landing page of my site that has a "enter your title here" input field. When a user enters something in it and clicks continue, they are directed to the node submission form and the title field should be populated with what they had just entered. How would I put something like his together? Thanks?

# Answer
> 1 votes
Use the Prepopulate module, there is an example on the docs for pre-populating the title field. All you need is to have a simple form that appends your `$data` to this path:

```
/node/add/yourcontenttype?edit[title]='.'$data'

```

# Answer
> 0 votes
Figured it out. Using the prepopulate module for anyone wanting to do the same thing, here is what my simple form looks like:

```
<form id="my_form" method="get" action="/node/add/content">
<input name="edit[title]=" type="text">
<button class="submit" type="submit">Go!</button>
</form>

```

This gets the value of the input and after hitting the submit button, populates the title field of my content type. Im giving credit to @ipwa for directing me to the prepopulate module. Thanks.

# Answer
> 0 votes
You can create a panel page with arguments and add field panes or custom plugins.

For example create panel page (`/admin/structure/pages`) and set the Path to like `/confirmation/%node`, where `%node` is your context argument loaded from the URL. Then in Panel Content you can add content panes which will use these substitutions (like `%submission:field-some`). The page title you can set up either using *Substitutions* as well, or load it from the *pane*. You can also code custom ctools plugin, for example:

```
/**
 * @file
 * CTools plugin to provide render a submission page.
 */

/**
 * Defines the Plugin.
 *
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'single' => TRUE,
  'title' => t('Submission page'),
  'description' => t('Displays the submission form'),
  'edit form' => 'foo_submission_page_edit_form',
  'render callback' => 'foo_submission_page',
  'defaults' => array('foo_field' => ''),
  'all contexts' => TRUE,
);

/**
 * Implements pane render callback.
 */
function foo_submission_page($subtype, $conf, $panel_args, $contexts) {
  $block = new stdClass();
  $block->title = $conf['override_title'] ? $conf['override_title_text'] : '';
  $block->content = '';
  if (empty($contexts)) {
    return $block;
  }
  if (isset($conf['foo_field'])) {
    $text = ctools_context_keyword_substitute($conf['foo_field'], array(), $contexts);
    if ($text['value']) {
      $block->content = theme('foo_submission_page', array(
        'text' => check_markup($text['value'], $text['format']),
      ));
    }
    else {
      $block->content = '';
    }
  }

  return $block;
}

/**
 * Implements pane edit callback.
 */
function foo_submission_page_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];
  $form['foo_field'] = array(
    '#title' => t('Some field'),
    '#description' => t('Please provide extra info'),
    '#type' => 'textfield',
    '#default_value' => isset($conf['foo_field']) ? $conf['foo_field'] : '',
  );
  return $form;
}

/**
 * Submit handler for the pane edit form.
 */
function foo_submission_page_edit_form_submit($form, &$form_state) {
  foreach (array_keys($form_state['plugin']['defaults']) as $key) {
    if (isset($form_state['values'][$key])) {
      $form_state['conf'][$key] = $form_state['values'][$key];
    }
  }
}

```

---
Tags: 7, entities
---


# Question
Title: Possible to use tags/buttons as exposed filters?
I have a view that will be a grid of a dozen content types. I would like to have a tag-like button or text link above the view of content to allow the user to toggle / filter between what content type they wish to see. I know that exposed filters allows you to use a dropdown or auto-complete, but is this possible with using tags as buttons?

# Answer
It sounds like you want to have something like this, what is provided by the Facet API module (Drupal 7) or Facets For Drupal 8.

Image copied from: https://www.webwash.net/drupal/tutorials/intro-search-api-part-2-faceted-search (explanation of Facet API combined with Search API). It should however also work with the Drupal core search system. (I only used it with Search API)

> The Facet API module allows site builders to easily create and manage faceted search interfaces. In addition to the UI components that come out of the box, themers and module developers can build their own widgets that can optionally be contributed back to Drupal.org. Facet API works with the core Search, Search API, and Apache Solr Search Integration modules (including Acquia Search) meaning that code and configuration can be reused as-is with the most popular search solutions available to Drupal. Refer to the documentation for more details.

Each facet will be exposed as a block, that you can place anywhere in your site from the block administration page.
> 2 votes

# Answer
If you want an easier option than setting up the Search API, you could just use Views Better Exposed Filters. https://www.drupal.org/project/better\_exposed\_filters
> 0 votes

---
Tags: views
---


# Question
Title: How to alter text filters conditionally based on content type?
How can I get the content type of the current node from within a text filter, so I can use it to conditionally alter how the filter is applied?

Getting the node ID from the `arg()` function and using it to load a node object does not work because the text filter is run multiple (30+) times and exhausts the available memory.

```
$node = menu_get_object();
if ( !empty($node) ) {
  dd('Have a node, do something');
}

```

The same is true with the following method of getting the content type: `$node = menu_get_object();`

# Answer
> 1 votes
You could go with the following code inside your filter's callback function:

```
if(arg(0) == 'node' && arg(1) > 0){
  $result = db_select('node', 'n')
  ->fields('n', array('type'))
  ->condition('nid', arg(1),'=')
  ->execute()
  ->fetchAssoc();
  dsm($result['type']);
}

```

Good luck!

# Answer
> 0 votes
```
check this  replace $user with node  condition node_type = "YOUR_NODE_TYPE_MACHINE_NAME"; // can find this on the node type's "edit" screen in the Drupal admin section.

$result = db_query("SELECT nid FROM node WHERE type = :nodeType ", array(':nodeType'=>$node_type));

$nids = array();

    function hide_formats_permission() {
      return array(
        'show text format dropdown' => array(
          'title' => t('Show text format dropdown'),
          'description' => t('Show the text format dropdowns where more than one text format is available. If a user does not have this permission then the text format dropdown will be displayed in a collapsed fieldset.'),
        ),
      );
    }

    /**
     * Implements hook_element_info_alter().
     *
     * We are using the implementation of better_formats module to intercept the display of input formats and
     * display this with our own function
     *
     */
    function hide_formats_element_info_alter(&$type) {
      // Change text format processing on elements to our version.
      if (isset($type['text_format']['#process'])) {
        foreach ($type['text_format']['#process'] as &$callback) {
          if ($callback === 'filter_process_format') {
          $callback = 'hide_formats_filter_process_format';
          }
        }
      }
    }

    /*
     * Started as a direct copy of filter_process_format from core filter.module
     */
    function hide_formats_filter_process_format($element) {
      global $user;

      // Ensure that children appear as subkeys of this element.
      $element['#tree'] = TRUE;
      $blacklist = array(
        // Make form_builder() regenerate child properties.
        '#parents',
        '#id',
        '#name',
        // Do not copy this #process function to prevent form_builder() from
        // recursing infinitely.
        '#process',
        // Description is handled by theme_text_format_wrapper().
        '#description',
        // Ensure proper ordering of children.
        '#weight',
        // Properties already processed for the parent element.
        '#prefix',
        '#suffix',
        '#attached',
        '#processed',
        '#theme_wrappers',
      );
      // Move this element into sub-element 'value'.
      unset($element['value']);
      foreach (element_properties($element) as $key) {
        if (!in_array($key, $blacklist)) {
          $element['value'][$key] = $element[$key];
        }
      }

      $element['value']['#type'] = $element['#base_type'];
      $element['value'] += element_info($element['#base_type']);

      // Turn original element into a text format wrapper.
      $path = drupal_get_path('module', 'filter');
      $element['#attached']['js'][] = $path . '/filter.js';
      $element['#attached']['css'][] = $path . '/filter.css';

      // Setup child container for the text format widget.
      $element['format'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('filter-wrapper')),
      );

      /*
       * Add custom display.
       */
      if (user_access('show text format dropdown')) {
        $element['format']['#title'] = "Text formats options";  // Title is needed in our theme or you can't expand the fieldset
        $element['format']['#collapsible'] = TRUE;
        $element['format']['#collapsed'] = TRUE;

        // Add custom CSS to fix overlap in fieldsets for seven theme. #17892227
        global $theme;
        if ($theme == 'seven') {
          $custom_css = 'fieldset.filter-wrapper { padding-bottom: 20px;} fieldset.filter-wrapper div.fieldset-wrapper { padding-top: 20px;}';
          drupal_add_css($custom_css, 'inline');
        }
      }

      // Prepare text format guidelines.
      $element['format']['guidelines'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('filter-guidelines')),
        '#weight' => 20,
      );
      // Get a list of formats that the current user has access to.
      $formats = filter_formats($user);
      foreach ($formats as $format) {
        $options[$format->format] = $format->name;
        $element['format']['guidelines'][$format->format] = array(
          '#theme' => 'filter_guidelines',
          '#format' => $format,
        );
      }

      // Use the default format for this user if none was selected.
      if (!isset($element['#format'])) {
        $element['#format'] = filter_default_format($user);
      }

      $element['format']['format'] = array(
        '#type' => 'select',
        '#title' => t('Text format'),
        '#options' => $options,
        '#default_value' => $element['#format'],
        '#access' => count($formats) > 1,
        '#weight' => 10,
        '#attributes' => array('class' => array('filter-list')),
        '#parents' => array_merge($element['#parents'], array('format')),
      );

      $element['format']['help'] = array(
        '#type' => 'container',
        '#theme' => 'filter_tips_more_info',
        '#attributes' => array('class' => array('filter-help')),
        '#weight' => 0,
      );

      $all_formats = filter_formats();
      $format_exists = isset($all_formats[$element['#format']]);
      $user_has_access = isset($formats[$element['#format']]);
      $user_is_admin = user_access('administer filters');

      // If the stored format does not exist, administrators have to assign a new
      // format.
      if (!$format_exists && $user_is_admin) {
        $element['format']['format']['#required'] = TRUE;
        $element['format']['format']['#default_value'] = NULL;
        // Force access to the format selector (it may have been denied above if
        // the user only has access to a single format).
        $element['format']['format']['#access'] = TRUE;
      }
      // Disable this widget, if the fieldset .fieldset-wrapperuser is not allowed to use the stored format,
      // or if the stored format does not exist. The 'administer filters' permission
      // only grants access to the filter administration, not to all formats.
      elseif (!$user_has_access || !$format_exists) {
        // Overload default values into #value to make them unalterable.
        $element['value']['#value'] = $element['value']['#default_value'];
        $element['format']['format']['#value'] = $element['format']['format']['#default_value'];

        // Prepend #pre_render callback to replace field value with user notice
        // prior to rendering.
        $element['value'] += array('#pre_render' => array());
        array_unshift($element['value']['#pre_render'], 'filter_form_access_denied');

        // Cosmetic adjustments.
        if (isset($element['value']['#rows'])) {
          $element['value']['#rows'] = 3;
        }
        $element['value']['#disabled'] = TRUE;
        $element['value']['#resizable'] = FALSE;

        // Hide the text format selector and any other child element (such as text
        // field's summary).
        foreach (element_children($element) as $key) {
          if ($key != 'value') {
            $element[$key]['#access'] = FALSE;
          }
        }
      }

      return $element;
    }

```

# Answer
> 0 votes
If the problem is just calling the same function over and over, you could use the following code.

```
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['node'] = &drupal_static(__FUNCTION__);
  }
  $node = &$drupal_static_fast['node'];
  if (empty($node)) {
    // The function was not called earlier.
    $node = menu_get_object();
    // …
  }

```

Generally speaking, an input filter should never try to understand in which context it is being called, if not from the given parameters. In fact, an input filter could be called:

* In a page listing different nodes, which is what happens for the front page, for example
* For each of the comments for a node, which could be show in the same page together the node itself
* In every context a module calls `check_markup()`

---
Tags: input-formats
---


# Question
Title: How to store/manage/display data sets in Drupal without using the node/entity systems?
I need to store some straight forward data rows (similar to the JSON objects that can be stored in MongoDB), where all the data associated with one object is found on the same row and not scattered over several database tables.

What is the best approach to do this in Drupal?

**Notes**:

* I am considering storing them on database (MySQL/Postgres or MongoDB). I have no data yet (I am at the project planning stage).
* I'll be using some API code (server side - does not need to have anything to do with Drupal) and I will be creating/updating the data via JSON post requests from a c# application. I need Drupal only to display the data.

# Answer
> 1 votes
Have a look at the Forena module which can be used to display (= query, not update) data stored in databases external to Drupal. It comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgres or any PDO compliant variation.

For more details about Forena, 2 types of documentation are available:

The Sample reports and graphs are fully functional, such as the drill downs available on the Master Summary with drill down. To filter data (by the users), you'd typically use "report parameters", which you can see in the sample report "Users in cities". On top of that, using Forena "skins", you can also use the amazing "dataTables" (and its widgets, such as sorting by selected columns).

It also includes a UI for either creating your reports (the **WYSIWYG Report Editor**) and/or for creating your SQL queries (the **WYSIWYG Query Builder**).

Disclosure: I'm a co-maintainer of Forena.

# Answer
> 1 votes
You could store your objects in the Drupal-DB in one table with just an id and a text field. Put your objects as JSON-Strings into the text field. De-serialize (json\_decode) the data to display it in Drupal (build your own theme #type and twig-template or just put it into a #table).

You can access your table with the `Drupal\Core\Database\Connection` object just with straight forward SQL (query) or with PDO like (select) etc.

```
$stm = \Drupal::database()->select('my_simpletable', 't')
      ->fields('t', ['text'])
      ->condition('t.id', $needed_id)
      ->execute()->fetchAll(\PDO::FETCH_ASSOC);

```

You can create your simple table in the hook\_schema() function of your module.install file. Like this:

```
$schema['my_simpletable'] = array(
      'description' => 'Table to json objects',
      'fields' => array(
          'id' => array(
              'type' => 'serial',
              'unsigned' => TRUE,
              'not null' => TRUE,
          ),
          'text' => array(
              'type' => 'text',
              'not null' => true,
              'size' => 'big',
              'description' => 'JSON string of objects.',
          )
       )
    )

```

That's all, no need for full blown entities here :-)

---
Tags: 7, database
---


# Question
Title: How to change the field type of existing fields?
Here is my case.

1. I've created a content type with few fields (all fields had type: 'text').
2. I've exported this content type using feature and then used feature on PROD website for few weeks.
3. Recently we decided to change type of 2 fields to: 'email' and 'link' (first we deleted these 2 fields, and then created them with new type), I've updated feature with my content type again (since we did changes to these 2 fields).
4. Now when I do deploy to my website it says that it can't convert fields form current type to new type (and I can understand that). However I also believe it is something that everybody does, so there must be a normal solution to this.

Here is a message from my terminal:

> WD php: FieldException: Cannot change an existing field's type. in field\_update\_field() (line 234 of /Users/aaa/git/drupal/http/modules/field/field.crud.inc).
> \[error\] Drush command terminated abnormally due to an unrecoverable error.
> \[error\] FieldException: Cannot change an existing field's type. in field\_update\_field() (line 234 of /Users/aaa/git/drupal/http/modules/field/field.crud.inc).

Please advise what is the good approach to solve my issue (change type of field that is used already).

# Answer
A possible approach to avoid running into this commonly known challenge, is to perform a mini-migration for each of both of your fields, on your PROD website.

Here are the highlights of such approach:

1. For your eMail field:

* Assume your existing field (with type text) has machine name `field_email`.
    * Create a new field with type eMail (instead of text), say with machine name `field_email_new`.
2. For your Link field:

* Assume your existing field (with type text) has machine name `field_link`.
    * Create a new field with type eMail (instead of text), say with machine name `field_link_new`.
3. Deploy both fields `field_email_new` and `field_link_new` to your PROD site, using Features (similar to what you tried to use, but which failed). Since these are new fields, that should not cause similar problems. Obviously, at that point the values of these fields will be empty.
4. For each of both fields, use an approach similar to what I described in my answer to "How do I move content from one field to another?", which (only) uses modules Rules and Views Bulk Operations. You should be able to reuse the Rules Component included there, after adapting the machine names of the used fields.
5. To the extend that would be needed, don't forget to adapt custom Rules, Views, etc to reference the new (instead of old) machine names of both fields.
6. Delete the original (old) eMail field and Link field.
7. Double check your custom Rules, Views, etc that you (should have) modified in 'Step 5' above, to ensure you don't have any of the typically "*integrity*" error messages (because you forget or skipped some of them). If any such errors show up, adapt the machine names to the new ones to fix them.

Obviously, steps 5, 6 and 7 can be refined by creating a clone from your PROD site, and prepare that kind of work in some none-PROD equivalent. Possibly combined with using a Features based deployment procedure to migrate your changes from that clone to your PROD site afterwards.

**Note**: NO custom coding, only some (rather basic) admin stuff, using robust contributed modules (and which can be uninstalled again afterwards).
> 1 votes

---
Tags: entities, nodes, features
---


title: Is it possible to add style plugins?

text:
# Question
Title: Is it possible to add style plugins?
I would like to allow users to choose a style for each pane and choose options such as margin and font size. It is clear how to do this in Drupal 7. But I can't seem to figure out whether it's possible in Drupal 8.

Note: It could be an issue where the stylizer module isn't running properly. I see that the styles plugin is in the directory under the panels module. But even though panels are enabled I don't see any style options on the panes when I attempt to configure them.

# Answer
It appears that the functionality does not yet exist for Drupal 8

https://www.drupal.org/node/2296437
> 0 votes

---
Tags: 8, panels
---


# Question
Title: replace template with other when conditions are met
I want to add a record do theme\_hook\_suggestions variable but only when specific conditions are met, especially when system is going to use a specific template in theme. In effect I want to replace one template with other.

I.e. - when user sees node with id = 50 and view mode == teaser and user has set some specific parameters system should use template node-special.tpl.php. In any other condition system should use base template node-50.tpl.php

I cannot do this, as far as I understand, in any \*preprocess or \*process functions basing on variables because there is no information available about what template are candidate for use.

How can I achieve this?

EDIT, more detailed explanation:

I'm trying to build a A/B testing system for e-commerce site I run. I want to set a A/B test where for selected base template a new variant will be defined and for chosen group of users this new variant will be used. I want to have a universal solution where I could configure this just by one line of code. It should work both for nodes, fields, blocks, pages templates. I just simply need to substitute one template field with another.

ie I want to have a universal config:

```
$ABconfig = array(
        'ABbigrelated' => array( //test name
                'basetemplate' => 'related-nodes', //base template
                'newtemplate' => 'related-nodes-bigimages', //new template
                'GAdimensions'  =>  'dimension2' //config for googleanalitics

        )
);

```

# Answer
> 1 votes
You can alter the list of template suggestions in your `preprocess` hook:

```
function drop_preprocess(&$variables) {
  $variant = drop_get_variant_for_current_user($variables);
  if ($variant) {
    $suggestions = array();
    foreach ($variables['theme_hook_suggestions'] as $suggestion) {
      $suggestions[] = $suggestion
      $suggestions[] = $suggestion . '--' . $variant;
    }
    $variables['theme_hook_suggestions'] = $suggestions;
  }
}

```

This will add templates variants for all theme hook. So for instance, this allow you to override the `node.tpl.php` and `page.tpl.php` templates with `node--special.tpl.php` and `page--special.tpl.php` ones (when `drop_get_variant_for_current_user()` returns `'special'`. If the template for a variant does not exists, it will simply be ignored.

Note that the order of suggestions is preserved. If you have three specialized node templates: `node.tpl.php`, `node--special.tpl.php` and `node-article.tpl.php` (the default one, the 'special' variant and the template for article nodes), when rendering an `article` node, the 'node-article.tpl.php' will be used since `'node_article'` will be after both `'node'` and `'node__special'` in `$variables['theme_hook_suggestions']`.

Because it will run for all templates used on the page, the use a static cache in `get_variant_for_current_user()` so the actual variant won't be computed again and again for the same request/template.

*Update:*

* The exact used template with be the last one in `$variables['theme_hook_suggestions']` for which a template file exits. For instance if `$variables['theme_hook_suggestions'] == array('node', 'node--special', 'node-article', 'node-article--special')`, but only the `node.tpl.php`, `node-article.tpl.php` and `node--special.tpl.php` files exist, then `node--special.tpl.php` will be used.
* The `drop_get_variant_template()` function is the one where you put your variant selection logic (and that has to be written).

---
Tags: theming
---


# Question
Title: How to diagnose an undefined index in a fresh install of Drupal 7?
**Question**:

How do I begin to explore what is causing this error? If this were reporting errors from a contrib module, I would submit a bug report on drupal.org. However, I'm not really sure where I should begin to submit an issue.

**Set up**:

I installed a Drupal 7 instance installed via Quick Drupal

```
drush qd -y d7-mysite
cd mysite/drupal
php -S localhost:8080

```

And immediately installed needed modules via `drush en -y field_collection_tabs workbench workbench_moderation`

**Then the errors:**

After a modicum of configuration to get work bench going and adding a `writer` user, I begin to see these error messages:

> Notice: Undefined index: #contextual\_links in contextual\_pre\_render\_links() (line 140 of /drupal/modules/contextual/contextual.module).
>
> Warning: Invalid argument supplied for foreach() in contextual\_pre\_render\_links() (line 140 of /drupal/modules/contextual/contextual.module).
>
> Notice: Undefined index: #contextual\_links in contextual\_pre\_render\_links() (line 140 of /drupal/modules/contextual/contextual.module).
>
> Warning: Invalid argument supplied for foreach() in contextual\_pre\_render\_links() (line 140 of /drupal/modules/contextual/contextual.module).
>
> Notice: Undefined index: #contextual\_links in contextual\_pre\_render\_links() (line 140 of /drupal/modules/contextual/contextual.module).
>
> Warning: Invalid argument supplied for foreach() in contextual\_pre\_render\_links() (line 140 of /drupal/modules/contextual/contextual.module).

**Location:**

This is coming from a function called `contextual_pre_render_links($element)`

**Other Tidbits**:

* This only happens when the *Authenticated User* creates new node. *Administrator* can create a node with out an error message displaying.
* I'm trying to implement a work-flow system using Workbench *on an inherited site*. I'm trying to understand this process so that I can teach others.

# Answer
In this development copy I've turned off Contextual (`drush dis contextual`) which of course gets ride of the error message.

I welcome any other answers that might offer a bit of enlightenment to me on this matter. We can live without the Contextual module's functionality but it does add some additional clicks to accomplish certain task.
> 0 votes

---
Tags: 7, entities, workbench
---


title: Why entity autoloading doesn't work?

text:
# Question
Title: Why entity autoloading doesn't work?
I'm trying to set up entity autoloading using `hook_menu` like this:

```
    $menu['e-shop/produkt/detail/%commerce_datasheet'] = array(
    'title' => t('Products'),
    'page_callback' => 'commerce_products_datasheet_detail',
    'page_arguments' => array(3),
    'access callback' => TRUE,
     );

function commerce_datasheet_load($datasheet_id) {
  return entity_load_single('commerce_datasheet',$datasheet_id);
}

function commerce_products_datasheet_detail($entity, $view_mode='full') {
    dpm($entity);
}

```

`dpm()` function doesn't return anything, so I assume, that `$entity` is empty.

I am using latest versions on Drupal 7 and Entity API module.

# Answer
> 1 votes
It was my mistake. I was using another module, which provided `page callback` with higher priority. For the next time - it's advisable to install `devel` module and go to `devel/menu/item?path=<uri>` where used page callback can be clearly seen.

---
Tags: entities
---


# Question
Title: How to reverse engineer a section of a Drupal Page
Sorry if this is a beginner or inappropriate question, but I'm trying to work on modifying a complex Drupal site and I have no idea how to find out how it's built.

At the top of the home page there's a bunch of content (specifically an image that moves and zooms like a google map) but I can't find anything about how to edit or control this area.

Where should I look? Views, Blocks, or in the Theme files? I've tried looking through all of these as best as I know but I'm hitting dead ends.

Thanks!

# Answer
Your question could use more specifics, but I think I understand what you are experiencing.

I've been there. If you cannot find it anywhere, a good bet is that it is part of the theme tpl pages. If you want to confirm this, you should go to the sites/all/themes/whatever-theme-you-are-using and search for files ending in .tpl.php, which are the files that control the theme you are currently using.

Frequently, any special effect or non-drupal configurable behaviour is likely inserted directly into these files. If your intention is to re-use whatever you are seeing at the top of the page, look for js (javascript) files: it is likely that dynamic pages are using some library, and that by googling the js filenames you can find a reference that might be useful.

At least, it has worked for me.
> 0 votes

---
Tags: views, theming, blocks, media
---


# Question
Title: Filter nodes by currently logged-in user
I want a view which shows nodes authored by the currently logged-in user. I can't figure out how to do this in Drupal 7.

# Answer
> 3 votes
Ok I finally figured it out. Had to add a contextual filter of "Content: User posted or commented" with the default value of "user ID from logged in user".

# Answer
> 4 votes
just add a view for all your nodes. Then add a "relationship" for "Content: Author". Now add a "contextual filter" for the field "user: uid" with a default argument for "userid of logged in user" to filter the view.

# Answer
> 2 votes
I believe it should be the same as in Drupal 6. Add a filter of `User: Current` to the view

# Answer
> 0 votes
Adding the Content:Author relationship or contextual filter didn't work in for me because it joins the node's author field to the user table. In my case I created a field called "active" and I only wanted to display it on a view if it was active or if the current user's role is admin or custom admin.

The Current user has roles filter provided by the Views Published or Roles module solved this issue for me.

---
Tags: 7, views
---


# Question
Title: How to not print a Menu Block if a Menu Block exists
I've been using a whitelist/blacklist PHP script to control the display of 2 different menu blocks, and its becoming bloated.

Menu\_block 1 is the primary menu. Menu\_block 2 is the supplementary menu.

I'm trying set the block visibility for Menu\_block 1 via PHP - IF Menu\_block 2 exists return FALSE, else return TRUE. Print Menu\_block 1 unless Menu\_block 2 exists.

PHP visibility for Menu\_block 1

```
<?php
  if(isset($block = module_exists('menu_block', 'block', '2')) {
    return FALSE;
  }
  return TRUE;
?>

```

I'm not even sure if this is actually possible.

# Answer
> 1 votes
I had the same issue and resolved it by removing one of the blocks by calling template\_preprocess\_page() in a custom module or in your theme's template.php. What I do is check to see if both blocks exist on the page, and if so, call unset() on the block I want to remove:

```
function mymodule_preprocess_page(&$variables) {
//Remove secondary menu block if tertiary menu block is on the page
if(!empty($variables['page']['sidebar_first']['menu_block_tertiary']) && !empty($variables['page']['sidebar_first']['menu_block_secondary'])) {
    unset($variables['page']['sidebar_first']['menu_block_secondary']);
}

```

The indexes in your $variables array will most likely be different. On my site, 'sidebar\_first' is the region in my theme where my menu blocks (menu\_block\_primary and menu\_block\_secondary) are placed. If you're not sure what your variables are, you can use a call to dpm($variables) to find them (Make sure you you have the devel module enabled) like so:

```
function mymodule_preprocess_page(&$variables) {
  dpm($variables);
}

```

# Answer
> 0 votes
As per your last phrase in your question, the Bean module is a potential alternative you might want to consider. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

There are quite a few other modules that integrate with the Bean module also.

# Answer
> 0 votes
Check if the block content menu items exist, then show the block.

```
<?php
    $block1 = module_invoke('menu_block', 'block_view', '1');
    $block2 = module_invoke('menu_block', 'block_view', '2');
    if ($block1['content']['#content'] == null ) {
        print render($block2['content']);
    } else {
        print render($block1['content']);
    }
    //dpm($block1)
?>

```

---
Tags: 7, blocks
---


title: How to print sid value in webform?

text:
# Question
Title: How to print sid value in webform?
I have created a form using webform module, and alter form In D7

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  global $user;

  if('webform_client_form_1' == $form_id) {

    $form['#validate'][] = 'mymodule_check_email';

  }

}

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

.............

.............

}

```

I write `print_r($form_state);` in **mymodule\_check\_email** function.

Get all variables but **sid** value is empty but in database sid insert proper.

My question how to get **sid** value.

# Answer
The sid won't be available from a validation handler; validation handlers are called before form submission, thus a valid sid for your submission doesn't exist at time of execution.

If you need to call a post-submit webform hander, the webform module provides `hook_webform_submission_insert()`:

```
function mymodule_webform_submission_insert($node, $submission) {
  // The submission object contains $submission->sid, the submission id.
  print_r($submission);
}

```
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Change contact form to email based on selection?
I am attempting to change the email a custom contact form is sent to based on what selection the user makes when filling out the form. Is there a way to do this in Drupal 8?

# Answer
> 1 votes
There isn't a way to make behave like its D7 incarnation without some custom code. You might, however, find this issue on d.o. useful; it contains a patch that adds a customizable block which lets you select a contact form (and thus recipient) to use.

---
Tags: forms, emails
---


title: Checking caller of a hook

text:
# Question
Title: Checking caller of a hook
Is it possible to know which code called a hook? I have two cases--one where I want to return, one where I want to continue.

1. Anonymous user views a page, thus firing hook\_entity\_load() (I want to deny this--return)
2. Cron creates page as anonymous user, thus firing hook\_entity\_load() (I want to accept this--continue)

If I can check to see if cron called the hook, I'll continue. Is there a way to do this?

# Answer
> 0 votes
I don't know of a "drupal" way to do this but The calling function will be in the backtrace. I have two helpers I use strictly for debugging. It's not a pretty solution but you might be able to check calling function.

Calling function:

```
// Returns the name of the calling function.
// Since this function call adds to the stack [0]
// The function calling this adds to the stack [1]
// That means [2] is the desired function name.
function getCallingFunction()
{
  $callers = debug_backtrace();
  return $callers[2]['function'];
}

```

Full stack:

```
// Returns the full stack.
function getCallingFunctionStack()
{
  $callers = debug_backtrace();
  $stack = array();
  foreach ($callers as $caller)
  {
    $stack[] = $caller['function'];
  }

  return implode('->', $stack);
}

```

I do not see a way to prove you are in a cron run but You can check if cron is running with:

```
if (!lock_acquire('cron', 0)) {
  // cron is running.
}

```

But this does not mean you are a cron user. It just means cron is running during this access attempt.

You could do something like store the cron session id in a variable on `hook_cron_queue_info` then check if that is the current session id. Kind of dirty but pretty much guarantees you are in cron.

Several other ideas can be found on this question.

---
Tags: 7, hooks, users
---


# Question
Title: Regarding menus for authenticated users only
Using **Structures/Menus/User Menu** in DRUPAL 7 i am adding a custom menu link under it and providing a path to it as node/whatever\_my\_nid. It is working fine. I have cleared all cache. However this menu link is being displayed for all users. I want it to be displayed only for authenticated users and admin. This should be a simple thing to figure out but apparently i cannot. I thought it would have been a permission issues but i don't think so. Would appreciate any help. Thanks

Edit: I found that this code may help:

```
<?php
global $user;
if ($user->uid) {
if ($menu = theme_menu_tree()) {
   $menu = "<div class=\"menu\">". $menu . "</div>";
   return $menu;
}
}
else {return;}
?>

```

But where do i place this code...In my page.tpl.php or somewhere else like in template.php in my themes?

I tried placing the above function in my theme's preprocess function as:

```
function ypwb_preprocess_block(&$variables, $hook) {
     if ($user->uid) {
        if ($menu = theme_menu_tree()) {
           $menu = "<div class=\"menu\">". $menu . "</div>";
           return $menu;
        }
      }
        else {return;}
    }

```

However, the menu is still showing for anonymous user as well.

# Answer
What I usually do is:

1. Install and enable Taxonomy Access
2. Create a vocabulary called **Access**
3. Create 2 terms in the new **Access** vocabulary: **Public** and **Private**
4. Attach the term reference fields for **Access** vocabulary to each node type you wish to protect. You may want to set the default value to "Public".
5. Go to Taxonomy Access configuration page and set **D** (deny) View access to Anonymous users on **Private** term. Leave the rest of the options (update delete view tag etc) **I** (ignore).
6. Configure the access control for Authenticated users and set **A** (allow) View access to Authenticated users on **Private** term, and set **I** (ignore) for all else.
7. Now all you need to do is set Private on nodes you wish to protect, and set Public for all else.
> 3 votes

# Answer
thanks to @Indrock, i got a very simple and effective answer Menu per role is the way to do so.

> This module allows you to restrict access to menu items based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.
> 1 votes

# Answer
If you are putting it in a block, then create 2 menus.

Then create 2 menu blocks, linking to these 2 menus.

Restrict the 'logged in' version to authenticated roles and the anonymous user menu block to the *anonymous user* role.
> 0 votes

---
Tags: 7, users, routes
---


title: what is the purpose of site_key?

text:
# Question
Title: what is the purpose of site_key?
In ROOT/modules/update/update.fetch.inc, there is the following code.

```
$site_key = drupal_hmac_base64($base_url, drupal_get_private_key());
$url = _update_build_fetch_url($project, $site_key);

```

`_update_build_fetch_url()` contains the following code.

```
  // Only append usage information if we have a site key and the project is
  // enabled. We do not want to record usage statistics for disabled projects.
  if (!empty($site_key) && (strpos($project['project_type'], 'disabled') === FALSE)) {
    // Append the site key.
    $url .= (strpos($url, '?') !== FALSE) ? '&' : '?';
    $url .= 'site_key=';
    $url .= rawurlencode($site_key);

    // Append the version.
    if (!empty($project['info']['version'])) {
      $url .= '&version=';
      $url .= rawurlencode($project['info']['version']);
    }

    // Append the list of modules or themes enabled.
    $list = array_keys($project['includes']);
    $url .= '&list=';
    $url .= rawurlencode(implode(',', $list));
  }

```

This function generates the URL to fetch information about project updates, returning a URL like http://updates.drupal.org/release-history/examples/7.x?site\_key=FuSSIDdX3JtCJQV7F1hWK6WopklCLf0jjHFDC1Nevys&version=7.x-1.x-dev&list=ajax\_example%2Cexamples.

Why does Drupal need site\_key? How do I know the value of `$base_url` from site\_key?

# Answer
It's a unique value that allows to identify the site asking for updates. It is used on Drupal.org when giving the number of site using a module, which is shown in every project page.

>

Without that value, Drupal.org could not report the number of sites using a module, since it could not understand which site is asking for updates.

Since site\_key is a crypted hash derived from `$base_url`, you cannot get the value of `$base_url` from its hash; that is how hash works. Hashes are used to save the passwords in the database; nobody can get the value of the password from the hash saved in the database.
> 3 votes

# Answer
I believe this is a unique token for each site, that Drupal reports when checking for updates. So the statistics (below the releases there is a 'view usage statistics' link) are checked against a token. Otherwise if you would check for updates 100 times, there would be in increased usage for all your modules.

So it enhances accuracy on Drupal.org backed.
> 1 votes

---
Tags: updating
---


# Question
Title: Is there a core method in views that can pad numbers with leading zeros?
# Setup

I am building a view that outputs human usable id's. These ids would look best if padded to 3 characters. For example the episodes of a tv show may look best if they are formated:

01-01 (Season 1 episode 1) 10-05 (Season 10 Episode 5) 03-22 (Season 03 Episode 22)

# Problem

In my node I'm storing a simple integer (1-100). I want to keep the value as an integer not a string. How do I pad the integer with leading zeros on output.

Using simple php would be a simple `str_pad($value, 2, '0', STR_PAD_LEFT);` but I do not want to execute php in my views or even enable the php module/filter.

# Solution

The solution must:

* Use a core ability of views
* Not require me to execute php stored in the database (not enable php module or anything equivalent)
* Must allow me to maintain the field as an integer input/storage

I could probably write the views plugin for this but I was hoping their was already something available like a views integer format or something like that.

# Answer
Go to `/sites/all/themes/yourtheme/` folder and in **template.php** add the following code:

```
function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $vars['fields']['field_example']->content = str_pad($vars['fields']['field_example']->raw, 2, 0, STR_PAD_LEFT);
  }

}

```
* replace **yourtheme** with the actual name of your theme
* replace **view\_name** with the name of your view.
* replace **block\_1** with the machine name of your view.
* replace **example** with the name of your field (2 replacements).

Lastly, in Drupal, clear/flush your cache to see the changes.
> 1 votes

---
Tags: 7, views, entities
---


title: Receiving an error when uninstall

text:
# Question
Title: Receiving an error when uninstall
I am getting a WSOD after attempting to uninstall the Drupal Commerce module on Drupal 8.1.1 Has anyone seen this error before, and possibly point me a direction? Lost trying to fix this.

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "commerce\_product" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager-\>getDefinition() (line 125 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

# Answer
Commerce for Drupal 8 must be considered unusable at this stage and very unstable as it is still in alpha version.

No stable version has been released yet, therefore it is advised not to try to build anything yet with it, and installation shall be considered for development purpose only.
> 0 votes

---
Tags: commerce, 8
---


# Question
Title: How to display a block if a user does NOT have a selected role?
I am thinking this has been solved elsewhere, but I haven't found anything.

I am looking for a way to display a block if the current user ***doesn't*** have a role. So, whilst the typical permissions allow a block to be displayed to everyone (by not selecting anyone) or to users with specific roles (by selecting a role), I need the inverse, displaying where the user *doesn't* have a selected role.

DO you have any ideas?

# Answer
In global variable `$user` are stored all roles that current user has. So in template.php or template suggestion files you can check if your targeted role is in `$user->roles` and display block if not.
> 4 votes

# Answer
in block configure page and in "Page specific visibility settings" section you can enter php code which should return TRUE or FALSE.

global variable $user is still available there.
> 1 votes

# Answer
you can edit it in the "permissions" setting is the "configurations" tab. find that block, and deselect "admin" and "user" and only select "visitor" (or whatever similar option is there, it might not actually say the word visitor)
> 1 votes

# Answer
Below is an answer for users who do NOT have a role with `rid` = 5 (change to whatever `rid` fits for your case).

# Part 1: Rules block visibility

You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the actual user who's using the site, i.e. if it is **YES** or **NO** (a boolean, right?) a user with `rid = 5`.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the **K**eep**I**t**S**uper**S**imple concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_block_for_user_without_some role" : {
    "LABEL" : "Hide block for users without some role",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "5" : "5" } }
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user has YES or NO a role with `rid` equal to `5`.

With that, we're coming close to an actual answer to your question.

# Part 3:

Head over to the "Block" settings for the block you want to hide for the user without the role with `rid = 5`. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.
> 0 votes

---
Tags: blocks, users
---


# Question
Title: Acquia Dev Desktop, PHP 5.6 and SSL certificate issue on local MacOSX
I am having problems authenticating to SalesForce using the Drupal SalesForce Suite module https://www.drupal.org/project/salesforce

> Error opening socket ssl://ap2.salesforce.com:443

I am running Drupal using DevDesktop 2 (Built: Nov 22 2015 12:34:41) on my local MacOSX machine with PHP 5.6 with SSL turned on. On a Ubuntu server I can get the salesforce module to authenticate without an issue using the exact same settings as what I have on the Mac.

When I run this additional test on the Mac I get a similar error:

```
fsockopen('ssl://google.com',443,$errno,$errstr) ? print("UP") : print("DOWN:".$errstr);

```

> Warning: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3\_GET\_SERVER\_CERTIFICATE:certificate verify failed in test.php on line 2
>
> Warning: fsockopen(): Failed to enable crypto in test.php on line 2
>
> Warning: fsockopen(): unable to connect to ssl://google.com:443 (Unknown error) in test.php on line 2 DOWN:

When I view phpinfo() I can see that the setting for "Openssl default config" is /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/openssl.cnf

This version of Dev Desktop is supposed to support SSL for local development. From the DevDesktop documentation: https://docs.acquia.com/dev-desktop/sites#https

> Using HTTPS (SSL) with local sites The Local site URL link for local websites provides a Use https check box. When you select the Use https check box, Acquia Dev Desktop serves your site using the HTTPS protocol and uses a self-signed SSL certificate to simulate secure traffic. This enables you to develop and test secure websites locally without requiring you to duplicate the SSL certificates you use on your production site.

Has anyone encountered this before and how do we get DevDesktop to point to the self-signed SSL certificate that is mentioned?

# Answer
> 1 votes
After looking around I found kenorb's reply on a similar issue: https://drupal.stackexchange.com/a/149456/62500

and after poking around the DevDesktop installed files on my Mac I managed to solve it.

The problem is the certificate file does not exist at the default location.

```
print_r(openssl_get_cert_locations());

```

Returns

```
Array (
    [default_cert_file] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/cert.pem
    [default_cert_file_env] => SSL_CERT_FILE
    [default_cert_dir] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/certs
    [default_cert_dir_env] => SSL_CERT_DIR
    [default_private_dir] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/private
    [default_default_cert_area] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl
    [ini_cafile] => [ini_capath] => )

```

So it is looking for cert.pem in the non existent directory "/Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/"

To solve this, edit /Applications/\[Dev desktop folder\]/php5\_6/bin/php.ini

and add these lines:

```
[openssl]
openssl.cafile="/Applications/[Dev desktop folder]/common/cert/cacert.pem"
openssl.capath="/Applications/[Dev desktop folder]/common/cert/"

```

where is \[Dev desktop folder\] is the name of your Dev Desktop folder.

---
Tags: acquia-dev-desktop
---


# Question
Title: Cannot Disable User Programmatically With user_cancel()
I want to disable user using `user_cancel` method.

```
//A function that disables a user.
function myid_admin_disable_user(){
    try{
        $edit = array(
            'user_cancel_notify' => true,
        );

        $method = 'user_cancel_block';
        //5 is the user id of the account I want to disable.
        user_cancel($edit, 5, $method);
        echo true;
    }catch(Exception $e){
        echo false;
    }
}

```

After running the function above, I can still use the account which is supposed to be disabled. Why? Whats wrong in my code above?

# Answer
> 3 votes
Per the docs in `user_cancel()`:

> Since the user cancellation process needs to be run in a batch, either Form API will invoke it, or batch\_process() needs to be invoked after calling this function and should define the path to redirect to.

You need to invoke the batch API in order to trigger the result.

```
// Set the notify and cancel type options.
user_cancel(array(
  'user_cancel_notify' => TRUE,
  'user_cancel_method' => 'user_cancel_delete',
), 5, 'user_cancel_delete');

// Invoke the Batch API, disable drupal_goto(), and execute.
$batch = &batch_get();
$batch['progressive'] = FALSE;
batch_process();

```

# Answer
> 1 votes
Since the method you want to use would block the user account, you can simply use the following code, to achieve what you want.

```
if ($account = user_load(5)) {
  _user_mail_notify('status_blocked', $account);
  user_save($account, array('status' => 0));
}

```

If you prefer not calling `_user_mail_notify()`, as a module should not depend on a function whose name starts with an underscore (which is a way to mark the function as private), you can use the following code.

```
if ($account = user_load(5)) {
  $notify = variable_get('user_mail_status_blocked_notify', TRUE);
  if ($notify) {
    $params['account'] = $account;
    drupal_mail('user', 'status_blocked', $account->mail, user_preferred_language($account), $params);
  }
  user_save($account, array('status' => 0));
}

```

`user_cancel()` is thought to be called in form submission handlers; plus, since you don't need to delete more accounts, you don't even need the batch API, for this task.

If you want to make the code even more complete, you could change it as follows.

```
$edit = array('status' => 0);
if ($account = user_load(5)) {
  module_invoke_all('user_cancel', $edit, $account, 'user_cancel_block');
  $notify = variable_get('user_mail_status_blocked_notify', TRUE);
  if ($notify) {
    $params['account'] = $account;
    drupal_mail('user', 'status_blocked', $account->mail, user_preferred_language($account), $params);
  }
  user_save($account, $edit);
}

```

In this way, you notify other modules when a user account is blocked.

---
Tags: 7, forms, users
---


# Question
Title: How to hide a block or text if user can edit node?
In a block there's a flag where users can ask for permission to edit the node. The admin gets a mail when the node is flagged. Admin can grant acces with node-acces to a particular user. This part is working.

However, when the user *can* edit the node, this block (or snippet; could use if else statement) should be hidden. I'm looking for (and can't find it) a snippet like

```
if user can edit
    {'you can edit'}
else
    {show flag}

```

How should I do the first part?

# Answer
> 1 votes
Seems it can be done via this PoC

```
if (node_access('edit', $node, $user)) {
  {'you can edit'}
}
else {
  {show flag}
}

```

# Answer
> 0 votes
You should be able to get this to work using the Rules block visibility module, using a Rules Component that is pretty similar to what I described in my answer to "How to display a block if a user does NOT have a selected role?".

All you'd have to do is to adapt the Rules condition to make it check if "*admin has granted acces with node-acces*" (as in your question) to the current user.

---
Tags: blocks, users
---


# Question
Title: How to display a Views block based on the current page?
I've created a new content type "banner" (title,description, image, price) that I would like to display on certain pages (limited to parent pages). I'm using the Views module and was looking for a contextual filter or something like that but I'm a noob at Drupal and can't figure out my way.

For example, I have 2 content types: rooms and activities, 2 page listings respectively my rooms and my activities and finally I've created two banners, banner-rooms and banner-activities.

How can I create a Views block which displays the right instance according to the current page ? How can I limit it to the parent page (ie: do not display the banner on rooms/roomA, only on rooms)?

# Answer
> 2 votes
Suppose there are two views

views 1 url is - http://example.com/my-rooms

views 2 url is - http://example.com/my-activities

There are two blocks -

a) banner-rooms

b) banner-activities

On the block configuration page, You need to set the visibility setting of the block for specific pages.

=\>Under Visibility setting, Select the tab "Pages"

=\>Select the option - "only on the listed pages"

In the text-area, fill the urls e.g- banner-rooms

# Answer
> 0 votes
You should be able to get this to work using the Rules block visibility module, using a Rules Component that is pretty similar to what I described in my answer to "How to display a block if a user does NOT have a selected role?". All you'd have to do is to adapt the Rules condition to make it check if the path of the current page is "`rooms`".

---
Tags: views, blocks
---


# Question
Title: How to create HTML Tooltips using the Charts module's API with Google Charts?
I'm using the Charts module and I've been trying to set up a simple pie chart that has HTML in the tooltips. We would like the HTML to be menu links, but they can just be manually coded into the chart code. However, I have not been able to get this working. Looking at the API (http://cgit.drupalcode.org/charts/tree/charts.module#n46) it seems there is an option to set: `'#tooltips_use_html' => TRUE`

But I haven't been able to get it to work. I've tried the following code in the body of a node:

```
$chart = array(
    '#type' => 'chart',
    '#title' => t('Pie Chart with tooltips (no data labels)'),
    '#chart_type' => 'pie',
    '#chart_library' => 'google', // Allowed values: 'google' or 'highcharts'
    '#legend_position' => 'right',
    '#data_labels' => FALSE,
     '#tooltips' => TRUE,
     '#tooltips_use_html' => TRUE
  );
  $chart['pie_data'] = array(
    '#type' => 'chart_data',
    '#title' => t('Gender'),
    '#labels' => array('<a href="http://localhost:8888/node/246095/edit">Male</a>', 'Female'),
    '#data' => array(10, 20),
  );

/*
$chart['pie_data_item'] = array(
    '#data' => 10,
    '#color' => 'NULL',
    '#title' =>'<a href="http://localhost:8888/node/246095/edit">Male</a>',
  );

$chart['pie_data_item'] = array(
    '#data' => 20,
    '#color' => 'NULL',
    '#title' =>'Female',
  );
*/

  $example['chart'] = $chart;

```

In place of `$chart['pie_data']` I've also tried the commented out code `$chart['pie_data_item']`. With the first approach I do get a result, but the HTML is not rendered correctly, and labels are being treated as the tooltips? Is there anyway to tell what HTML goes into each tooltip?

EDIT: Using the patch in https://www.drupal.org/files/issues/2209467-9--raw\_options.patch as recommended by Pierre.Vriens I was able to enable the #raw\_options array. I've looked around and haven't found any clear documentation what that array is supposed to look like though. How would I use #raw\_options to generate HTML tooltips?

# Answer
The most recent Charts version does not yet support "tooltips" as such. However, have a look at Pass library-specific options via existing #raw\_options, which provides an alternative (using **#raw\_options**) to what you're trying to get to work. For charting engine *Highcharts* it's already supported (and committed to the most recent dev version), while for charting engine *Google Charts* you'd need to apply the **RTBC**-patch attached to comment nr 9 (from about 6 months ago). Obviously, after that patch is committed, my recommendation here to use the *#raw\_options* will continue to work (for either charting engine). And rest assured, this patch ***will*** make it (so it's not a patch that ***might*** make it).

With this **#raw\_options** solution, we have a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

Disclosure: I'm a co-maintainer of the Charts module.
> 1 votes

---
Tags: 7, charts
---


# Question
Title: how to load 2 services (or more) through dependency injection
if i have 1 service, i can load my service through dependency injection like:

```
class MyForm extends FormBase {

  protected $coreService;

  /**
   * Class constructor.
   */
  public function __construct($coreService) {
    $this->coreService = $coreService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static( $container->get('arm_core.core_service') );
  }

```

but now let say i have 2 services, how i load the service through dependency injection rather than globally?

```
class MyForm extends FormBase {

  protected $coreService
  protected $mainService;

  //then...?

```

Thank you

# Answer
The key idea here is that if the class you are using implements the ContainerInjectionInterface, you get passed a container object from which you can get any service you like. Since FormBase implements this, your form will already be able to do this.

Here's some code from D8's file example, from the Example Module, as an example:

```

  /**
   * Constructs a new FileExampleReadWriteForm page.
   *
   * @param StateInterface $state
   *   Storage interface for state data.
   * @param FileSystemInterface $file_system
   *   Interface for common file system operations.
   * @param StreamWrapperManagerInterface $stream_wrapper_manager
   *   Interface to obtain stream wrappers used to manipulate a given file
   *   scheme.
   * @param ModuleHandlerInterface $module_handler
   *   Interface to get information about the status of modules and other
   *   extensions.
   * @param RequestStack $request_stack
   *   Access to the current request, including to session objects.
   */
  public function __construct(
    StateInterface $state,
    FileSystemInterface $file_system,
    StreamWrapperManagerInterface $stream_wrapper_manager,
    ModuleHandlerInterface $module_handler,
    RequestStack $request_stack
  ) {
    $this->state = $state;
    $this->fileSystem = $file_system;
    $this->moduleHandler = $module_handler;
    $this->requestStack = $request_stack;
    $this->streamWrapperManager = $stream_wrapper_manager;
    $this->sessionSchemeEnabled = $this->moduleHandler->moduleExists('stream_wrapper_example');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $state = $container->get('state');
    $file_system = $container->get('file_system');
    $module_handler = $container->get('module_handler');
    $request_stack = $container->get('request_stack');
    $stream_wrapper_manager = $container->get('stream_wrapper_manager');
    return new static($state, $file_system, $stream_wrapper_manager, $module_handler, $request_stack);
  }

```

Your create() function calls your constructor, and since you've received a services container, you can ask for whatever and however many services you want.
> 3 votes

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: Redirect after comment submit according to value of query string in comment form URL?
For redirecting user to some page after comment submit my below code is working fine :

```
function my_module_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "comment_node_link_form") {
      $form['#submit'][] = 'my_module_submit';
  }
}

function my_module_submit($form, &$form_state) {
    $form_state['redirect'] = 'newsroom/en';
}

```

For Comment links I am sending some query string in comment form URL and want to redirect to user to page after comment according to query string value, How can we fetch the query string value to pass it to redirect on `hook_submit`

```
http://www.example.com/comment/reply/208943?destination=newsroom#comment-form

http://www.example.com/comment/reply/208943?destination=sections#comment-form

```

How can we fetch value of **destination** and pass it to **redirect** in **hook\_submit**

Please suggest ! Thanks!

**UPDATE :** I have tried adding hidden field but not able to access it in hook\_submit it shows null :

```
function my_module_form_alter(&$form, $form_state, $form_id) {
       if ($form_id == "comment_node_link_form") {

           $form['redirect_to'] = array(
             '#type' => 'hidden',
             '#value' => $_GET['destination'],
           );

          $form['#submit'][] = 'my_module_submit';
      }
    }

```

# Answer
After More deep debugging I found that **action** of comment from is set to

> comment/reply/nodeid

So with below URL's:

> http://www.example.com/comment/reply/208943?destination=newsroom#comment-form
>
> http://www.example.com/comment/reply/208943?destination=sections#comment-form

My query string variable **destination** is lost or either at form submit it shows null because from moves to action URL where no query string was set.

To solve this I have added query string in action URL which works very well :

```
function my_module_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "comment_node_link_form") {
      $form['#action'] = $form['#action'] . '?destination=' . $_GET['destination'];
  }
}

```

ie: All I have to do is add required query string to `$form['#action']`

Hope this will help any one who is trying similar solution.
> 1 votes

# Answer
```
function module_menu() {
  $items = array();

  $items['redirect_query_string'] = array(
    'page callback' => 'YourRedirectpagecallbackfunction',
    'access callback' => 'user_access',
    //'access argument' =>  array('Download CSV'),
    'type'  => MENU_CALLBACK,
  );
  return $items;
}

In your form submit write:

if(isset($_GET["redirect_query_string"])){
    return YourRedirectpagecallbackfunction();
  }

function YourRedirectpagecallbackfunction(){
......your redirect url......
}

```
> 0 votes

---
Tags: 7, hooks, redirection
---


# Question
Title: How to display Youtube video duration, likes, views
How to extract and display YouTube data like video duration, likes, views in D7 site ?

# Answer
> 1 votes
Seems the following modules is what you're looking for

YouTube Pull

> YouTube Pull is a simple module to pull YouTube feed for latest video listing. Support any video query parameters by the Youtube API (Atom output format).

```
/**
 * Available variables in the theme is
 * An array of $videos, where each video object has:
 *   $video->title
 *   $video->description
 *   $video->watchURL
 *   $video->thumbnailFull
 *   $video->thumbnailDefault
 *   $video->thumbnailMQ
 *   $video->thumbnailHQ
 *   $video->thumbnailStart
 *   $video->thumbnailMiddle
 *   $video->thumbnailEnd
 *   $video->length
 *   $video->viewCount
 *   $video->rating
 *   $video->commentsURL
 *   $video->commentsCount
 *   $video->responsesURL
 *   $video->relatedURL
 */

```

Feeds: YouTube Parser

> Supported data from imported feeds:
>
> Currently the module supports the following data from imported videos:
>
> * Feed title
> * Video ID
> * Video title
> * Author
> * Updated on (Datetime)
> * Published on (Datetime)
> * Description
> * Thumbnail
> * Category (Can be imported seamlessly with Taxonomy module)
> * Tags (Can be imported seamlessly with Taxonomy module)
> * Watch page URL (Can be imported seamlessly with Embedded Media Field module)
> * Duration (Formatted hh:mm:ss)
> * Favorite count
> * View count
> * Rating

---
Tags: 7, files
---


title: slick carousel append Dots

text:
# Question
Title: slick carousel append Dots
I am using slick and slick views modules. I want the dots to be under the images.. How can achieve this style: " o o o " in Append dots?? The information window (next to Append dots box) suggests to try .slick\__arrow, but i can't understand where to put it.

Thank you.

# Answer
> 0 votes
Go to the Slick carousel page at `admin/config/media/slick`, then either add your own optionset or edit the default one provided.

Inside of these option sets, under the "Settings" tab, you will find a checkbox for Dots. Once checked, you'll see more options such as "Dot class" and "Append dots".

Then save your optionset, and make sure that your carousel uses that one, as opposed to a different set.

**Edit:** I actually just ran into this problem on my own. I had to download Slick library 1.5.9, and then in the Slick settings (inside the view), I selected Skin: "Default" and it came up for me. Hope it works for you!

# Answer
> 0 votes
Inside the slick option set, under the "Settings" tab, i checked the box "Arrows" and i changed the code for Previous and Next arrows from the tabs were available there.

---
Tags: 7, views
---


# Question
Title: Views trying show term node count/comment count/latest post
I got a taxonomy called forum and several terms. I crated a view to show the terms http://missioncity.ca/forums In the display I'm trying to show Term Name | Content Count | Comment Count | Latest Topic.

I got all of that data cells showing but I can't get the proper Comment Count (I want to show a total of all comments from all posts) and to show the latest posted topic.

I'm trying this to not have to use the forums module and be able to use different content types in this pseduo forum.

This is my view

```
    $view = new view();
$view->name = 'forums';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Forums';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Forums';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['row_class'] = '.col-xs-12';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'name_1' => 'name_1',
  'name' => 'name',
  'title' => 'title',
  'comment_count' => 'comment_count',
  'nothing' => 'nothing',
);
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'node';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['relationship'] = 'nid';
$handler->display->display_options['fields']['title_1']['exclude'] = TRUE;
/* Field: COUNT(DISTINCT Content: Nid) */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count_distinct';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['exclude'] = TRUE;
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
$handler->display->display_options['fields']['name_1']['label'] = '';
$handler->display->display_options['fields']['name_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name_1']['link_to_taxonomy'] = TRUE;
/* Field: COUNT(Taxonomy term: Name) */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['group_type'] = 'count';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['empty'] = '(0)';
$handler->display->display_options['fields']['name']['hide_alter_empty'] = FALSE;
/* Field: COUNT(Content: Title) */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'nid';
$handler->display->display_options['fields']['title']['group_type'] = 'count';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['path'] = 'business-pages/%1/[name_1]';
$handler->display->display_options['fields']['title']['alter']['path_case'] = 'lower';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['prefix'] = 'Posts ';
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['relationship'] = 'nid';
$handler->display->display_options['fields']['comment_count']['label'] = 'Comments ';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = '';
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'Latest Topic: [title_1]';
$handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count_1']['id'] = 'comment_count_1';
$handler->display->display_options['fields']['comment_count_1']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count_1']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count_1']['relationship'] = 'nid';
$handler->display->display_options['fields']['comment_count_1']['exclude'] = TRUE;
/* Sort criterion: Taxonomy term: Name */
$handler->display->display_options['sorts']['name']['id'] = 'name';
$handler->display->display_options['sorts']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['sorts']['name']['field'] = 'name';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'forum' => 'forum',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_forum');
$handler->display->display_options['path'] = 'forums';

```

This is my view. Any help would be appreciated.

# Answer
Comment counter

> This is a tiny module that basically extends Drupal's comment statistics module by adding comment counts for day, week, month and year. It also integrates with Views and you can use it to select, filter, order the content as well.
> 0 votes

---
Tags: 7, views
---