title: Feeds - Background process vs Batch API

text:
# Question
Title: Feeds - Background process vs Batch API
I've being using Feeds to import a medium sized amount of nodes in a daily basis. I'm using Elysia cron in order to get fine tuning cron settings.

Here's my flow :

1. Every day at 02 am a cron task is triggered
2. This task loads a list of files from its settings, and for each of these files, it triggers a feeds import by calling :

```
$myFeed->startImport()

```

If you take a look at this startImport method, you will see something like this :

```
public function startImport() {
    module_invoke_all('feeds_before_import', $this);
    $config = $this->importer->getConfig();
    if ($config['process_in_background']) {
      $this->startBackgroundJob('import');
    }
    else {
      $this->startBatchAPIJob(t('Importing'), 'import');
    }
}

```

So, we have two ways of calling the Feeds importer, either using the Background JOB api (which I suppose to be this : https://drupal.org/project/background\_process) or the Batch API (https://drupal.org/node/180528).

**Since I'm starting the feeds importer from a cron task, which one is more appropriate for this scenario ?**

*Can we see the Background process as an enhancement of the Batch API ?*

# Answer
> 10 votes
I've been digging through this code, and Feeds does not use Background Process.

It uses Job Scheduler

From **FeedsSource.inc**:

```
  /**
   * Background job helper. Starts a background job using Job Scheduler.
   *
   * Execute the first batch chunk of a background job on the current page load,
   * moves the rest of the job processing to a cron powered background job.
   *
   * Executing the first batch chunk is important, otherwise, when a user
   * submits a source for import or clearing, we will leave her without any
   * visual indicators of an ongoing job.
   *
   * @see FeedsSource::startImport().
   * @see FeedsSource::startClear().
   *
   * @param $method
   *   Method to execute on importer; one of 'import' or 'clear'.
   *
   * @throws Exception $e
   */
  protected function startBackgroundJob($method) {
    if (FEEDS_BATCH_COMPLETE != $this->$method()) {
      $job = array(
        'type' => $this->id,
        'id' => $this->feed_nid,
        'period' => 0,
        'periodic' => FALSE,
      );
      JobScheduler::get("feeds_source_{$method}")->set($job);
    }
  }

```

Job Scheduler in turn uses cron to complete jobs, so you're not really saving yourself anything if you are already calling this from cron.

The core Drupal Batch API uses AJAX to break up jobs into batches. You can't start a Batch API batch from cron. If you don't have JS and try to start a Batch with the core API, you'll still need to watch the progress bar move across the screen. If you abandon your browser during a batch, it will stop working.

Contrary to what the *previously* accepted answer above states, *the core Batch API **does not** use cron*

Background process is now a suite of modules, and it does now include a Batch API module. These are 2 separate modules, which are not related to the Job Schedule module. We can't refer to Background Job/Process as 1 thing. These are 2 unrelated modules.

The key differences are as follows:

**Drupal Batch API** uses your browser to make new requests to the server at regular intervals. This does not work from a cron job

**Job Scheduler** uses cron to call on a set of scheduled jobs during cron execution. There is a limit on how long the process can run during cron, so this is not ideal for long-running processes. It also is not good if you need your import to occur in a timely manner, when you have your cron job only running at night. Scheduling a new Job during cron is a bit backwards, since it might not be until the next cron run that the job is actually dispatched (depending on if your `hook_cron()` is called before or after `job_scheduler_cron()`)

**Background process / Background Batch** uses server-side http requests to chain steps of a process together. This is ideal for long-running processes that need to be started immediately. You can also start a long-running process from `hook_cron()` with this module, and it will run until finished.

I know you probably don't need this information now, but I did when I found this page from Google.

The information provided in the *previously* accepted answer is incorrect, and led me down the wrong path.

# Answer
> 1 votes
**My below response is incorrect, please refer to the accepted answer for an accurate outline.** I have left it there to show my thought process, where I got my information from and hopefully to stop others going wrong in the future.

**Kyle**

---

*My understanding is that the Background Job/Process is lightweight and can be easily run at peak times, as it will timeout if it runs for too long (predetermined), and interestingly is not actually a true background process module. However, the Batch API simply runs the jobs from the Cron as quickly as possible. I think it may be a case of semantics here, and that they both the the same job, however Background Job may be a little more convoluted in how it operates. Personally, at 0200 there is next to no activity on my site, so I would run my imports through Batch. If, however, you find you are under high stress (or have a low capacity server) at this time, then I would suggest Background Process/Jobs.*

*Hopefully this helps!*

---
Tags: 7, feeds, cron
---


title: Overriding theme_item_list in a context

text:
# Question
Title: Overriding theme_item_list in a context
I am using Views Tree plugin to render a taxonomy. I need to get rid of the surrounding `<div class="item-list"></div>` wrappers. While I could simply override the theme\_item\_list function in my template, I would like the override to only take place within a view. Otherwise the wrapper is just fine. What kind of 'if' should I use around it to apply a Views context?

# Answer
> 1 votes
You can to get rid of the surrounding wrappers by overriding theme\_item\_list($variables) function in you template.php or module and comment hardcoded lines:

```
    $output = '<div class="item-list">';

```

and

```
    $output = '</div>';

```

See details on http://api.drupal.org/api/drupal/includes!theme.inc/function/theme\_item\_list/7

# Answer
> 0 votes
You can just modify the settings in the view itself, so that the wrapper class is not included. Since you're using Drupal 7, just click on the '**Settings**' link next to the '**HTML list**' in the Format section (as in my screenshot) and then remove or modify the wrapper class it usually uses by default.

Hope that helps!

# Answer
> 0 votes
Since the views tree module doesn't provide a specific hook when it calls theme('item\_list') it means you cannot specifically target it's lists easily.

For more information on specific hooks see the $hook parameter docs for the theme() function.

(I created a feature request for this)

This means you have to override theme\_views\_tree\_inner() to override the call to theme('item\_list'\]) then override theme\_item\_list().

You could do it by adding these theme functions to your template.php of your theme (I'm assuming you are using views tree 7.x-2.0):

```
/**
 * Inner recursive theme function for views tree theming.
 *
 * @ingroup themeable
 * @param $view
 * @param $options
 * @param $row
 * @param $title
 * @param $result
 *   An array representing the raw data returned from the query.
 * @param $parent
 *   The id of the parent entry in the call stack.
 */
function THEMENAME_views_tree_inner($variables) {
  $view = $variables['view'];
  $options = $variables['options'];
  $rows = $variables['rows'];
  $title = $variables['title'];
  $result = $variables['result'];
  $parent = $variables['parent'];

  $items = array();
  foreach ($result as $i => $record) {
    if ($record->views_tree_parent == $parent) {
      $variables['parent'] = $record->views_tree_main;
      $items[] = $rows[$i] . call_user_func(__FUNCTION__, $variables);
    }
  }

  // Override call to theme('item_list']) with a call to
  // theme('item_list__views_tree') so we can easily theme views
  // tree lists specifically.
  return count($items) ? theme('item_list__views_tree', array('items' => $items, 'type' => $options['type'])) : '';
}

```

Then override theme\_item\_list but name the function like this to user your more specific hook:

```
/**
 * Returns HTML for a list or nested list of items for the views tree module.
 */
function THEMENAME_item_list__views_tree($variables) {

}

```

---
Tags: 7, theming
---


title: CSS not work after ajax replace

text:
# Question
Title: CSS not work after ajax replace
I have found that when I replace forms with AJAX, then the new forms loose their display styling. It seems like the css for the forms are not working any more.

How to solve this issue? Do i have to write js bind with .on() function to add css again? Any other suggesions?

# Answer
> 2 votes
In some cases it can depend on how and where you have added your CSS to the page.

The best way to do it is using #attached on your field via hook\_form\_alter() or similar.

If your CSS is already on the page though it should work on new elements added with ajax.

One possible cause is that your CSS selectors are too specific and the ID/class used isn't matching properly with the markup added by the ajax.

# Answer
> -1 votes
Yes, any event handlers that were attached will be disconnected when content is replaced by AJAX. You can use jQuery's .on() or .live() as alternative event hooks to prevent this.

---
Tags: ajax
---


# Question
Title: Prevent replacing <input type="submit"> with <button>
I am using Bootstrap 3 subtheme (7.x-3.1-beta2 ) on Drupal 7 for the administrative backend. It seems that the Bootstrap base theme replaces \<input type="submit"\> with a \<button\> element. That breaks the layout of the views backend.

I tried to change this by:

* copying button.func.php into the subtheme
* renaming the function according to the subtheme name
* modifying the output to return \<input\> instead of \<button\>

**Code in button.func.php**

```
<?php
function bootstrap_subtheme_adl_admin_button($variables) {
  $element = $variables['element'];
  $value = $element['#value'];
   if (!empty($element['#icon'])) {
     if ($element['#icon_position'] === 'before') {
       $value = $element['#icon'] . ' ' . $value;
     }
   elseif ($element['#icon_position'] === 'after') {
     $value .= ' ' . $element['#icon'];
    }
  }

return '<input' . drupal_attributes($element['#attributes']) . '>\n';
}

```

However, this does not have any visible effect. Any advise?

# Answer
If I'm reading the question directly, you've copied `button.func.php` into your sub-theme, modified the code inside it, and then tried to see if your changes work?

If that's what you did, the problem is that *Drupal never sees the code*. Fortunately (if that is the problem) the solution is simple: copy the code from that file into your sub-theme's `template.php` file and make whatever changes are required. Be sure the function is correctly named (i.e. to override `theme_button`, you'd need `themename` \+ `button` = `themename_button()`). In your example above, your sub-theme would have to be named 'bootstrap\_subtheme\_adl\_admin' in order for your function to be called even if the code is in the correct file.

---

Incidentally, the reason the `button.func.php` file works in the base Bootstrap theme appears to be the theme's registry.inc file.

---

## Basic sub-theme how-to with Bootstrap

1. Download Bootstrap sub theme into `/sites/all/themes`; don't bother to enable the theme
2. Copy `bootstrap_subtheme` from the `/sites/all/themes/bootstrap/bootstrap_subtheme` to `/sites/all/themes/bootstrap_subtheme`
3. Move `/sites/all/themes/bootstrap_subtheme/bootstrap_subtheme.info.starterkit` to `/sites/all/themes/bootstrap_subtheme/bootstrap_subtheme.info`
4. Enable `bootstrap_subtheme`

## Overriding a theme function implemented by a parent theme

1. Set up parent and subtheme as described above
2. **Never edit the parent theme in any way**
3. Copy the theme function you want to modify from e.g. `/sites/all/themes/bootstrap/theme/system/button.func.php` into the file at `/sites/all/themes/bootstrap_subtheme/template.php`
4. **Change the name of the function** in `/sites/all/themes/bootstrap_subtheme/template.php` from `bootstrap_button` to `bootstrap_subtheme_button`
> 0 votes

---
Tags: theming
---


# Question
Title: Organic groups: permissions groupadmin not respected
I am having troubles getting organic groups permissions working.

In my grouptype I want to give the groupadmin the permission to edit the group.

> **On an OG level:**
>
> *admin/config/group/permissions/node/mygrouptype*

I have set the permissions to 'Edit group' for administratormember

> **On a Global level:**
>
> *admin/people/permissions*

I have set the permission to Edit 'Mygrouptype'

However still my groupadmins are not able to edit their group. Setting this permission on a groupmember level does give the groupadmin the permission.

What am I missing?

# Answer
> 1 votes
Three steps solved my problem:

1.On admin/config/group/settings i selected a default administrator member

2.and disabled the : 'Strict node access permissions' setting.

3. On admin/config/group/permissions/node/mycontenttype i disabled the administer group permission.

---
Tags: organic-groups
---


title: Exclude a block from the views result

text:
# Question
Title: Exclude a block from the views result
I've created a views page named "Search" with a path of "product-page". Then I created a views block named "Sponsored Ads".

With the "Search" page, I exposed some fields for the filtering, then assigned the "Sponsored Ads" into the region and shows to only page listed "product-page".

I only want to display the "Sponsored Ads" into the "product-page" only, then exclude it from the results with "?" (Eg. /product-page?title=test&field\_category\_tid=All)

How can I achieve this? Please help...

# Answer
> 1 votes
There are actually quite a few methods on how to do this. The method here is quick and easy to do.

Install the devel module (you will uninstall it when your site goes live).

Make sure the block visibility settings is set up to only show on product-page.

Then add this code to your theme's template.php file.

```
function MYTHEME_block_view_alter(&$data, $block) {
  dpm($block);
  if ($block->module == 'views' && $block->delta == "BLOCK_DELTA") {
    //hide the block
    $params = drupal_get_query_parameters();
    if(count($params) > 0) {
      $data["content"] = FALSE;
    }
  }
}

```

Change MYTHEME to your theme's name, and clear your cache.

Now you need to change BLOCK\_DELTA with the delta of your block. To do that you will need to inspect the dpm output, and find your block, then find the delta of your block.

To further assist you in finding your block delta, you can inspect the block in question in your browser, and look at the id of the block. It will contain the delta as a substring with just the hyphens altered.

My delta is `block_content-block` so my line of code will be:

```
if ($block->module == 'views' && $block->delta == "block_content-block") {

```

When you are done remove the line `dpm($block);`. You may then uninstall devel module if you wish. This code is a primer and you can adjust it if you need, but as is it will work.

---
Tags: blocks, views
---


# Question
Title: How to list custom navigation menu with submenu?
I have created a custom menu in a drop-down manner. How can I show this custom menu with it's subitems programatically, so that I could customise it's styling?

# Answer
> 1 votes
You can use below function to render your custom menu your way

```
function _custom_menu_overview_tree_form($tree) {
  $output = '';
  foreach ($tree as $data) {
    $item = $data['link'];
    if ($item && $item['hidden'] == 0) {
      if(strtolower($item['title']) == 'about us page condition'){
            $output .= '<li class="right-nav">';
      }else{
            $output .= '<li>';
      }
      (0 == $item['plid']) ? ($class = 'parent') : ($class = 'child');

      if(isset($item['options']['attributes'])) {
        $attributes = array('attributes' => array_merge($item['options']['attributes'], array('class' => array($class))));
      } else {
        $attributes = array('attributes' => array('class' => array($class)));
      }

      $output .= l($item['title'], $item['href'], $attributes);

      if ($data['below']) {
        $output .= '<ul class="sub-menu">' . _custom_menu_overview_tree_form($data['below']) . '</ul>';
      }
      $output .= '</li>';
    }
  }
  return $output;
}

```

And use below code in your html.tpl.php or where you want to render your menu

```
$menu_items = menu_tree_all_data('your menu name');
echo '<ul class="foot-nav">' . _custom_menu_overview_tree_form($menu_items) . '</ul>';

```

Please try this and let me know if any issues.

# Answer
> 0 votes
I cracked through the following function

```
function load_menu_with_sub($menuname)
{
$links  = menu_tree_output(menu_tree_all_data($menuname));
$menu_array = array();
$link_count =  count($links);
$i = 0;
foreach($links as $menu_item)
{
if($i < $link_count-2){
$menu_array[$i] = array(
                      'menu_title' => $menu_item["#title"],
                      'menu_link' => $menu_item["#href"],
                     );
$count_sub = count($menu_item["#below"]);
$j = 0;

foreach($menu_item["#below"] as $sub_item)
{
if($j < $count_sub-2)
{
$menu_array[$i][$j] = array(
                      'menu_title' => $sub_item["#title"],
                      'menu_link' => $sub_item["#href"],
                     );
 $j = $j+1;
}
}
$i= $i+1;
}
}
}

```

---
Tags: routes
---


# Question
Title: Add "Post as anonymous" checkbox to forum topic creation
is it possible to add a post as anonymous checkbox to the topic creation in drupal forum?

I can also provide a user if not a string via which the content should be submitted. Basically I don't want users to need to logout but directly from their account create a disguise username or anything that would resemble this functionality.

Thanks! Jan

# Answer
https://www.drupal.org/project/forum\_cloakpost This module allows registered users to post to a forum as an anonymous user, via a checkbox on the add node/comment page.
> 0 votes

# Answer
You are looking for Anonymous Posting module, which will do your requirement exactly

> Anonymous Posting is a Drupal module that allow anonymous users to fill their contact informations (name, email and homepage) when posting any content type including Forum Topics. Then the submitted name will be shown instead of the usual generic defined anonymous string.
> 0 votes

---
Tags: nodes
---


# Question
Title: Display new tag to the newly added content
I am trying to show "NEW!" to the recently added. I know there is something to do with the Views module, but I couldn't find how to get it done.

How can I achieve this?

# Answer
> 3 votes
You can do it easily by adding new field **Node: Has new content** in views, it will show **NEW** status when a new node is added.

---
Tags: views
---


# Question
Title: Facet API, exclude option, and a field with multiple values
Im getting headaches concerning this one ...

Ive got a field, say a text field nammed "MyField", which can have multiple values.

Ive created a feed that imports the data for this filed.

After the import, my content looks like that :

Content A Myfield : \- Element 1 \- Element 2

Contnent B Myfield : \- Element 1

Content C Myfield : \- Element 2 \- Element 3

Now im trying to create a facet with an exclude option. What I would like is when I choose an element, all content, having at least the choosen element as a value of the Myfield field, should be hidden.

So if I check "Element 1", I want the content A and B to be hidden. And if I check "Element 3", only the content C would be hidden.

The fact is that this is not the way it works ...

If I check "Element 1", only the content B will be hidden, because Content A has another value "Element 2" for this field, so it is not retrieved during the query.

---

**I found something ...**

The file "sites/all/modules/contrib/search\_api/contrib/search\_api\_facetapi/plugins/facetapi/query\_type\_term.inc" contains the "addFacetFilter" function. This is where the exclude cases are processed.

If the Exclude settings is checked, this function changes the query condition to "\<\>" (instead of "=")

This is the query that is generated concerning an exclude facet :

SELECT COUNT(\*) AS expression FROM (SELECT DISTINCT t.item\_id AS item\_id, :score AS score, 1 AS expression FROM search\_api\_db\_default\_node\_index t LEFT OUTER JOIN search\_api\_db\_default\_node\_index\_field\_produit\_organisation\_pa t\_2 ON t.item\_id = t\_2.item\_id LEFT OUTER JOIN search\_api\_db\_default\_node\_index\_field\_derniere\_liste\_allergen t\_3 ON t.item\_id = t\_3.item\_id WHERE (( (t.created \>= :db\_condition\_placeholder\_0) )AND (t\_2.value = :db\_condition\_placeholder\_1) AND( (t\_3.value \<\> :db\_condition\_placeholder\_2) )))

Retrieved results are wrong.

**AND( (t\_3.value \<\> :db\_condition\_placeholder\_2)** is the default part added to handle the excluding setting.

Ive managed to modify the SQL Query so that the retrieved results are the good ones :

SELECT DISTINCT t.item\_id AS item\_id FROM search\_api\_db\_default\_node\_index t LEFT OUTER JOIN search\_api\_db\_default\_node\_index\_field\_produit\_organisation\_pa t\_2 ON t.item\_id=t\_2.item\_id LEFT OUTER JOIN search\_api\_db\_default\_node\_index\_field\_derniere\_liste\_allergen t\_3 ON t.item\_id = t\_3.item\_id WHERE (( (t.created \>= :db\_condition\_placeholder\_0) )AND t\_2.value = :db\_condition\_placeholder\_1) AND NOT EXISTS (select t\_4.item\_id FROM search\_api\_db\_default\_node\_index\_field\_derniere\_liste\_allergen t\_4 WHERE t\_4.value = :db\_condition\_placeholder\_3 AND t\_4.item\_id=t\_3.item\_id))

Ive replaced the excluding condition with :

**AND NOT EXISTS (select t\_4.item\_id FROM search\_api\_db\_default\_node\_index\_field\_derniere\_liste\_allergen t\_4 WHERE t\_4.value = 'moutarde' AND t\_4.item\_id=t\_3.item\_id)**

Now it returns only items that have no occurrence of the selected term in its values

Now I need to know how I can manage to get these correct results with views ... any idea ?

# Answer
> 1 votes
I did ask the same question in search\_api issue queue and this problem needed 2 patchs to be commited.

One for Search\_api\_database\_search : https://www.drupal.org/node/2361329

Another for Search\_api : https://www.drupal.org/node/2371099

Hope it can help !

---
Tags: search
---


# Question
Title: New Drush install instructions use Composer for install, even on Drupal 7?
The current Github install instructions for drush (http://docs.drush.org/en/master/install/#git-clone-ie-manual-install) say as the last step:

> From Drush root, run Composer to fetch dependencies.
>
> $ composer install

Since Drupal 7 does not usually have Composer installed, I assume these are Drupal 8 specific instructions.

Where can I find a link to instructions for installing Drush for a Drupal 7 install, where composer is not present?

# Answer
> 3 votes
Drush uses composer to install its dependencies, so please follow the composer instructions regardless of whether you plan to use drush with Drupal 7 or Drupal 8.

---
Tags: drush, installation, composer
---


# Question
Title: How to add another condition to a specific active facet?
I did try to add a condition using hook\_views\_pre\_execute or hook\_views\_query\_alter, but since Im usiong SearchAPI, theres is no point apparently in using these functions (no $query in views\_query\_alter, and no query too in views\_pre\_execute

Maybe using hook\__search\_api\_query\_alter could d othe trick but I dont know how to implement it.

My question is : How can I achieve this ?

Knowing that I need to add anoteh condition only when items of a specific facet are active (among a few other facets).

# Answer
> 0 votes
The solution is quite simple :

```
function mymodule_search_api_query_alter(SearchApiQueryInterface $query) {
    if(preg_match('/PRETTYPATHID/',url($_GET['q']))){
        $base_filter = $query->createFilter('AND');
        $base_filter->condition('MYFIELD', NULL, "<>");
        $query->filter($base_filter);
    }

}

```

---
Tags: search
---


# Question
Title: Is it possible to install new module without ftp in drupal 6?
I don't have the cpanel password of my hosting, I want to install new module through website. It's easy in D7, how can I do it in D6.

Note: if you suggest any module, I can't install that too through ftp and I don't know drush too.

# Answer
If all directories are writable, you should be able to enable PHP module, create a node with PHP filter, and in that node use:

```
file_put_contents ( 'path_to_modules/mymodule/mymodule.info', 'name = example
description = Demonstrates how to write info file.
core = 6.x');

```

The same for module file.

Preferably do that with rudimentary module that will allow you to upload and extract zip / tar.gz module files as provided by Drupal.org, and then remove PHP filtered node and disable PHP module.
> 1 votes

---
Tags: 6, installation
---


# Question
Title: Images in sites/default/files are not allowed to be seen anymore
Today I realized, that all images, that are located in sites/default/files/fields may not be accessed anymote, neither are they shown in my articles nor may I see them in the browser (e.g. http://daniel-stein.com/node/210#). All I get is a 403 - no permission - error. The folder and the files within are all set to 744 (and I also tested 777). I have not found any permissions I could adjust and I am not sure when this started or what I changed in that moment. Maybe it was around the time I changed from buedit to ckedit but the switch back was also useless.

# Answer
Ok, so I found a solution that worked for me.

In the process of investigating in this problem and the fact why it does not appear on other Drupal installations I have running on the same server I messed up the permission settings on my server. In order to reorder things, I installed the module https://www.drupal.org/project/security\_review \- it produces a list with potential security problems of your Drupal installation. I worked myself down the list solving the issues one by one. I am not sure if this was the point in the beginning but after I changed the permissions of the .htaccess-file in sites/default/files to 444 (readonly) suddenly my images were accessible again.

For your reference, here are a lot of other approaches you can try if the one I presented is not helping: https://www.drupal.org/node/1170440
> 0 votes

---
Tags: 7, media, wysiwyg
---


# Question
Title: Problem with custom scrollbar when it is called more than once on the same page
I making my custom module that works through Views and I have problem with one part of it. In one part, when I have longer text, custom scrollbar appears, and it works without any problems, but when I put more than one Views block on the same page scrollbar appears more then one (when I put two blocks it appears twice, on three blocks it appears three times, etc.).

There is my tpl.php file for View where scrollbar is called (this is the whole file with all other elements):

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<div id="<?php print $view_id; ?>" class="timeline<?php print ' ' . $gso_line_style; print ' ' . $gso_nav_style; print ' ' . $bso_button_type; ?>">
  <?php foreach ($rows as $id => $row): ?>
    <?php print $row; ?>
  <?php endforeach; ?>
</div>
<?php drupal_add_js('(function($){
    var test = false;
    $(window).load(function() {
      if(!test)
        timeline_init_'.$view_id.'($(document));
    });
    function timeline_init_'.$view_id.'($this) {
      $this.find(".scrollable-content").mCustomScrollbar();
      $this.find("a[rel^=\'prettyPhoto\']").prettyPhoto();

      $this.find("#'.$view_id.'").timeline({
        itemMargin : '.$gso_item_margin.',
        scrollSpeed : '.$go_scroll_speed.',
        easing : "'.$go_easing.'",
        openTriggerClass : \''.$gso_read_more.'\',
        swipeOn : true,
        startItem : "last",
        yearsOn : '.$go_hide_years.',
        hideTimeline : '.$gso_hide_timeline.',
        hideControles : '.$gso_hide_navigation.',
        closeText : "'.$bso_close_button_text.'",
        closeItemOnTransition: '.$go_close_item_on_transition.'
    });

    $this.find("#'.$view_id.'").on("ajaxLoaded.timeline", function(e){
      var scrCnt = e.element.find(".scrollable-content");
      scrCnt.height(scrCnt.parent().height() - scrCnt.parent().children("h2").height() - parseInt(scrCnt.parent().children("h2").css("margin-bottom")));
      scrCnt.mCustomScrollbar({theme:"light-thin"});
      e.element.find("a[rel^=\'prettyPhoto\']").prettyPhoto();
      e.element.find(".timeline_rollover_bottom").timelineRollover("bottom");
    });
  }
  })(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)); ?>

```

Can you help me with this or give me some idea how to solve the problem?

# Answer
> 1 votes
Try to use Drupal behaviors like

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

})(jQuery);

```

for more info go through Link

---
Tags: views, javascript
---


title: Loading a ctools modal on the home page

text:
# Question
Title: Loading a ctools modal on the home page
I have a front page that consists mostly of context rules to load various blocks, and for some users, a requirement to render a Ctools modal with a call to action. We aren't displaying much on the homepage besides a few views, and static blocks. I'm using this guide to build out the actual modal (which itself, will display a view with Contextual rules based on the user's settings) to show content tailored to them. Is there any in-code hooks I can use to activate this modal only on the home page, or should I look into the option of using a custom developed block (using `hook_block_info()` and `hook_block_view()`) to activate the modal on that page?

# Answer
Using ctools modal framework instead of those \[insert-fancy-word-here\]box JS library. Kudos.

Ctools module uses `js/modal.js` inside ctools module folder to attach Drupal Ajax events to links with `ctools-use-modal` class. That is all.

I can think about a few approaches.

## 1. Do not make them modal-enabled in first place.

If you are calling the `ctools_modal_text_button()` or the function that adds modal-compatible markup, you can wrap it with an `if` statement.

```
<?php
if (drupal_is_front_page()) {
  print ctools_modal_text_button(t('Open the modal'), 'my/path/nojs', '');
}
else {
  print l(t('Open the modal'), 'my/path/nojs');
}
?>

```

If you are using a block, cache modes `DRUPAL_CACHE_PER_ROLE` and `DRUPAL_CACHE_GLOBAL` won't be compatible with this. `DRUPAL_CACHE_PER_PAGE` would work, but I doubt caching this block would improve performance. It can rather have a negative effect. `DRUPAL_NO_CACHE` would be best.

If you are hardcoding block contents, you can create two blocks, with different visibility settings based on the path.

## 2. Change the JS or CSS.

If you can't change the PHP, you still can change the JS and/or CSS. A CSS solution would be the easiest. Print both modal and non-modal links, and if the `body` tag has `not-front` class, you can hide the modal links.

```
.not-front .ctools-use-modal {
  display: none;
}

```

You can un-ajax links as well. Here is a sample code:

```
(function($){

    Drupal.behaviors.zzzzzz = {
        attach: function (context) {
           $('.not-front area.ctools-use-modal, .not-front a.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          var base = $this.attr('href');
          Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
          delete Drupal.ajax[base]
        }
      });
    }}
})(jQuery);

```

There are other questions about Drupal behaviors and using jQuery with Drupal 7. Basically, above code finds modal links from non-front pages, and removes the Ajax properties defined in `Drupal.ajax`, so clicking the item does not trigger the modal.
> 0 votes

---
Tags: 7, chaos-tool-suite
---


title: Not able to change the settings.php

text:
# Question
Title: Not able to change the settings.php
I am working on drupal commons, and using pantheon servers for hosting. The major problem I am facing is the server database config issues. I am not able to change the settings.php file. Also Pantheon every now and then changes their db server password. How can I control this ? is there any server variable for the db instance, port, user id, password ?

# Answer
> 3 votes
Drupal removes "write" permission from settings.php, so to edit it, you need to give this permission back.

# SSH

```
chmod u+w sites/default/settings.php

```

# FTP, SFTP and alike

Use your cilent, and just tick appropriate checkbox. Like this:

# Answer
> 1 votes
Pantheon does not require any settings.php to operate a Pressflow-based Drupal distribution because all database credentials are injected into server side variables and read by Pantheon Pressflow core. In fact, Pantheon ignores file-based permissions while Drupal checks these and may sometimes complain. If you are unable to alter a file in your code base, you should ensure your Connection Mode is toggled to "SFTP" instead of "Git" because you will not have SFTP write access while the code is controlled by Git version control. The toggle is available on the Pantheon Dashboard of the development environment of your site.

You should also be aware that Pantheon does not support the Drupal Commons distribution as it is not Pantheon Pressflow based and cannot read the environment variables we inject on the fly, such as database credentials. To accomplish what you're trying to do, you will need to merge the Commons code base with Pantheon Pressflow Drupal and receive core updates from the Pantheon upstream. Simply downloading a distro tarball from Drupal.org and installing it on pantheon will not work, and is absolutely not supported on the platform.

Sources: Developing on Pantheon directly with SFTP mode

Adding a Custom Upstream

Running a Custom Upstream on Pantheon

Reading Pantheon Environment Configuration

# Answer
> -1 votes
1. Copy the file **setting.php** and paste them in same folder
2. Rename that folder like **setting1.php**.
3. Now you can change that file and user db name,apssword.
4. Rename that original settings.php as **originalsettings.php**.
5. Now you can rename that setting1.php file as **settings.php**.

now its working fine now.

---
Tags: 7, configuration
---


title: Override image-formatter.html.twig

text:
# Question
Title: Override image-formatter.html.twig
I'm looking for an option to override the `image-formatter.html.twig` template in my own theme. But in the HTML page output (twig debug is set to `true`) there's no option listed to override the formatter template. The only thing I see is:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- BEGIN OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

```

I need to place a `rel` attribute for the link which surrounds the image.

I found a solution which uses the option that you can write your own field formatter in your own module. But that seems to be too complex for this simple task.

# Answer
In your .theme file, add this suggestions alter hook (and flush caches so the new hook definition is picked up):

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_formatter_alter(array &$suggestions, array $variables) {
  $entity = $variables['item']->getEntity();
  $field_name = $variables['item']->getParent()->getName();
  $suggestions[] = 'image_formatter__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name;
}

```

Then if you look at the twig\_debug output, you should see something like:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- FILE NAME SUGGESTIONS:
   * image-formatter--node--article--field-image.html.twig
   x image-formatter.html.twig
-->

```

Once that is done, you can create your template file called `image-formatter--node--article--field-image.html.twig` in the templates directory of your theme, flush caches again so the template is picked up, and override the template with any changes you'd like.

This should include a caveat that the code hasn't been thoroughly tested :)
> 15 votes

---
Tags: 8, entities
---


title: How to create a quote request form?

text:
# Question
Title: How to create a quote request form?
I'm building a Drupal site that uses nodes to display a number of high value products. There are no e-commerce features due to the high value of the products being offered for sale, but the client wants a quote form on each product (node) page so that a potential buyer can enter some brief information and click to send a quote request for the item that they are viewing.

To make it clear, I have a content type called "Product", and I want this quote request form to be on each page and pre-loaded with the name of the product that that page is listing... it's not important whether the form is embedded in the node itself or displayed in a block, but it is important that the name of the product be preloaded in the form.

Following the form submission, ideally it would send an email to the website contact address.

I've considered using the entity form module and embedding the option to select a form in a node, but I don't want the client to have to manually create a form for each node.

Any ideas about how to create this functionality?

# Answer
> 1 votes
Entity Forms are, IMO, a long shot.

## 1. Webform module

You can use Webform module, and add an Option list (HTML select list) field to the webform, and autopopulate it with a URL parameter. Webform module supports populating the field value automatically from any `$_GET`, `$_COOKIE`, or `$_SERVER` value.

For the select list values, you can use a View to build the list of Product nodes.

## 2. Entity Forms

Since you already have an Entity Form, you can do it with the traditional field approach. Similar to the webform's select lists, you can create a View to list all Product nodes. Entity Reference module supports Option (radio, select, checkboxes) field type, with the options fetched from a View. You can use Entity Reference Prepopulate module to populate the Product node from a URL parameter.

## 3. Custom module

Either way above, you will have to use some modules. If you are OK to create a custom module, you can do it with a little coding as well. Be prepared to go through a little bit learning and conventions first. This is a nice guide to get you started.

You can do this easily with an EntityFieldQuery to fetch the eligible nodes list, and then setting the `#default_value` in `hook_form_alter` hook.

# Answer
> 0 votes
I've done something similar for a client using the Webform module. In my case it's sufficient to only know from which page (i.e., node) the form was submitted, therefore I've adjusted the e-mail template and added the token `[current-page:url]` to get the page's address.

However, if you need to store the data along with the submission result, you can add a hidden component and use the `[current-page:url]` token as its default value. I assume the Webform Rules module will be your best option, when you want to convert the submission result (i.e., the current page's url) into another value (e.g., the node's id).

---
Tags: 7, webforms, entities, ajax
---


# Question
Title: Image field - 'Number of values' is not showing up in admin form
Something's very wierd with my existing Drupal 7 setup (current Drupal version, set up in early 2013, custom Zen Subtheme). When I create a new Content Type with a new Field Type "Image" this 'Number of values' pulldown isn't showing up where it should. I've now spent the whole day researching how this could be, without any luck.

I've tried default themes, checked user permissions and also file permissions (while always rebuilding the theme registry). I googled around for hours but I couldn't find any clue how to fix this .

What could be the reason for this?

Any tips for further testing are welcome.

Edit:

* The field value is internally called `cardinality`.
* The problem seems to affect all field types of this installation.

# Answer
> 2 votes
Answering my own question:
I tracked down the bug by disabling module by module and finally found out that disabling the Gigya - Social Infrastructure module was bringing back the form fields.

Fortunately the issue was already listed and solved five days ago!

---
Tags: 7, entities
---


# Question
Title: How to embed a view in hook_page_build()
I'm trying to render a view into a region in **hook\_page\_build()**. I'm using views\_embed\_view(), but I'm getting the errors:

> Warning: Invalid argument supplied for foreach() in element\_children() (line 6428 of /var/www/.../includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 5893 of /var/www/.../includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 5903 of /var/www/.../includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 5941 of /var/www/.../includes/common.inc). Warning: Illegal string offset '#printed' in drupal\_render() (line 5948 of /var/www/.../includes/common.inc).

I have a view named 'blogs' and a view named 'block\_2'. In my hook:

```
function mymod_page_build(&$page) {
    $page['sidebar_second']['blogs'] = views_embed_view('blogs', 'block_2');
}

```

I'm trying to move away from blocks and context, and just render content I'd otherwise use in blocks directly into their regions in **hook\_page\_build()**.

# Answer
> 2 votes
The docs say hook\_page\_build()'s $page variable is for render arrays.

Less obvious from the docs without digging a little further but views\_embed\_view() returns a string of HTML markup.

So just assigning the result of views\_embed\_view() to the render array breaks it.

Instead you can use a #markup element.

Because it is the default element type you don't have to specify an element type or theme function or anything, so you can just do this:

```
/**
 * Implements hook_page_build().
 */
function MODULENAME_page_build(&$page) {
  $page['sidebar_second']['blogs']['#markup'] = views_embed_view('blogs', 'block_2');
}

```

If that is your entire code for this though (if you don't have some complex logic relating to when this view is being added) I would not recommend adding a block to a region in this manner.

There are lots of options already out there for adding blocs to regions without custom code. For example you could use one of these:

---
Tags: 7, views, hooks
---


# Question
Title: Creating an entity with an unlimited number of bundles
So I want to create an entity that can have as many user-created fieldable bundles as possible.

My first thought was to look at the Profile2 module, however I notice that there appear to be two separate entities as part of it - the profile2 entity, as well as a profile2\_type.

```
  // Add bundle info but bypass entity_load() as we cannot use it here.
  $types = db_select('profile_type', 'p')
    ->fields('p')
    ->execute()
    ->fetchAllAssoc('type');

  foreach ($types as $type => $info) {
    $return['profile2']['bundles'][$type] = array(
      'label' => $info->label,
      'admin' => array(
        'path' => 'admin/structure/profiles/manage/%profile2_type',
        'real path' => 'admin/structure/profiles/manage/' . $type,
        'bundle argument' => 4,
        'access arguments' => array('administer profiles'),
      ),
    );
  }

```

I want to have separate entities with only one instance, but unlimited bundles. Do I need to create two separate tables to accomplish this, or should it be possible with one table? I think it should be possible, but I'm not quite sure.

# Answer
> 1 votes
You have to register entities using hook\_entity\_info() so the system knows about them.

If you look at those docs it tells you about the different entity properties.

The one you are interested in at the moment is the bundle entity key and the bundles array.

You can see from the docs that you have to specify a list of bundles, otherwise it will be assumed you only have a single bundle with the same name as the entity type.

The example I would probably look at is node, because it is in Drupal core, so check out node\_entity\_info().

You can see it works similar to the profile2 one in that it gets its node bundle information from the database from where users have defined content types via the content type UI (and also from hook\_node\_info() for modules defining content types).

So you need a table for the bundle information, similar to the node\_type table.

You also need your table to store entity data, similar to the node table.

If you want to support revisions you also need a revision table, similar to the node\_revision table.

I can't see how it is possible with a single table unless you are storing 2 completely different types of data in a single database table, which would be bad.

Another thing to consider is that the system needs to know about bundles to provide UI screens for managing fields. You have to manage the fields before the user creates any content so at the time you need those UI pages there is nothing in the node table so it couldn't pull bundle data from there at that point. If you pulled bundle data from the main node table you wouldn't be able to administer the fields until a node was created of that bundle type.

I'm also not sure why you are apprehensive about having 2 tables.

---
Tags: entities
---


title: Opening a ctools modal on form submit

text:
# Question
Title: Opening a ctools modal on form submit
I have a custom profile form (part of a multi-step registration process) that requires a modal to be displayed once submitted. I am not clear on what the process is for this to happen, and the documentation i've seen isn't clear.

What I have tried (as seen below) is adding the submit action via a $form\['#action'\] which only returns the JS Object for the modal. Clearly, this isn't working. What should I do to render this modal when the form submits, while assuring the validation and submit calls fire?

The actual Ctools Modal logic is in its own modal, of which it generates on a hook\_menu() call to the correct route.

```
function example_profile_update_form($form, $form_state) {
  $form = array();

  $form['item'] = array(
    "#type" => 'textfield',
  );

  $form['#validate'][] = "example_profile_update_validate";
  $form['#action'] = url("modal/updated/nojs"); //Implemented as a hook_menu() call in its own module
  $form['#submit'][] = "example_profile_update_submit";

  return $form;
}

```

# Answer
Form API and Ajax frameworks work quite well together.

In your submit button, that you want to trigger the popup, it should work as an Ajax element first.

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit (and open popup)',
);

```

If you use submit and validate handlers as you have shown in your question, those submit and validate handlers will be executed at this point. If you want different submit/validate handlers, then you have to add them to the submit button itself.

Now, add `#ajax` property to the element.

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit (and open popup)',
  '#ajax' => array(
    'wrapper' => 'id_of_some_unique_element',
    'callback' => 'my_module_give_this_function_a_nice_name',
  ),
);
ctools_include('modal');
ctools_modal_add_js();

```

We play a trick here. Typically, `#ajax` property is used to replace some parts of the form. That's why we use the wrapper to indicate the **replacing** element. This will not be used at all if you trigger the modal, but make sure you refer to a unique DIV. Better leave it empty.

The `callback` is what we need. This callback should be a PHP function name, that returns some or full `$form` first parameter, **or**, it can print some Ajax commands. Do **not** set `$form_state['rebuild'] = TRUE` in your `#submit` handler.

`ctools_add_modal_js()` adds the modal.js file because it's necessary to trigger the popup.

```
function my_module_give_this_function_a_nice_name($form, &$form_state) {
  // this function gets the $form_state after submitting the form. All values, including the submitted values preserved.
}

```

Now, we need to print the modal contents.

```
function my_module_give_this_function_a_nice_name($form, &$form_state) {
  // this function gets the $form_state after submitting the form. All values, including the submitted values preserved.
  ctools_include('modal');
  ctools_modal_add_js();
  $commands = array();
  $commands[] = ctools_modal_command_display('title', 'modal content goes here');
  // You can add extra modal using drupal_add_js/css. You can also have them `#attached` to a rendarable array that you are going to print.
  print ajax_render($commands);
  exit;
}

```
> 4 votes

---
Tags: 7, chaos-tool-suite
---


# Question
Title: extend $.fn or Drupal.ajax.prototype.commands for calling javascript after ajax callbacks
*Use case*: You call ajax, and want to call some custom javascript (js) with some parameters as part of the response.

*Issue*: Two different solutions exist.

*Questions*:

* is there a preferred method or is this just a matter of style?
* are there differences in the benefits of each approach?

(there are a few questions eg  which supply different methods)

(Sorry these two examples may not be perfect - so feel free to edit)

**Extend JQuery: $.fn**

php:

```
$commands[] = ajax_command_invoke(
  NULL,
  'mymodule_command',
  array($data)
);

```

js:

```
$.fn.mymodule_command = function(data) {
  // dialog ajax id
  var dialogAjaxId = data.id;
  var blah = JSON.stringify(data.values);

```

};

**Extend Drupal: Drupal.ajax.prototype**

see this example

php:

```
$commands[] = array(
  'command' => 'mymodule_command',
  'arguments' => array(...),
);

```

js:

```
Drupal.ajax.prototype.commands.mymodule_command = function(ajax, response, status) {
  console.log('mymodule_command', ajax, response, status);
  console.log('arguments', response.arguments);
};

```

# Answer
> 2 votes
Extending `Drupal.ajax.prototype` is the way Drupal and almost every contrib handles this.

> is there a preferred method or is this just a matter of style?
>
> are there differences in the benefits of each approach?

The preferred method would be the latter. However, note that both methods are not the same. Ajax commands are passed through `ajax_render()` function, which allows modules to alter the ajax commands by implementing `hook_ajax_render_alter(&$commands)`. If you use the former method, you will see the `invoke` as the command, which makes it difficult to figure out the exact `invoke` command.

For Javascript eyes, it's just a matter of `$.fn` (shorthand for `jQuery.prototype`) vs `Drupal.ajax.prototype`.

---
Tags: forms, ajax
---


# Question
Title: Placeholder working, but giving Notice: Undefined variable: value and Notice: Undefined index: #type
This is what my code looks like:

```
foreach ($form["submitted"] as $key => $value) {
    if ("textarea" == $value["#type"]) {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
    if($value['#type'] == "webform_email") {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
    if($value['#type'] == "file") {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
}

```

Why are these errors there and what is the solution? A detailed explanation and working code wouldn't hurt, I am a beginner with Drupal! :-)

# Answer
> 0 votes
There can be some form elements, for examples, `markup`, without an explicitly set `#type`.

```
foreach ($form["submitted"] as $key => $value) {
    if (!isset($value["#type"])) { //If #type is not set, skip this iteration.
      continue;
    }
    if ("textarea" == $value["#type"]) {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
    if($value['#type'] == "webform_email") {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
    if($value['#type'] == "file") {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
}

```

---
Tags: forms
---


title: Manual setup of user's language

text:
# Question
Title: Manual setup of user's language
I need to switch user's language programmatically. The issue is I don't want it as an url part, and unable to switch it even with the regular language switcher block.

What I've try:

* admin/config/regional/language/detection: Disable **url**, Enable **Session**
* Now the **Language Switcher** core block adds ?language= to the current path. But this setting does not persist between pages, and does not appears in the session.
* manual setup of $\_SESSION\['language'\] does nothing
* `\Drupal::languageManager()->setConfigOverrideLanguage($language_manager->getLanguage($langcode))` does nothing

Drupal version is 8.beta2

# Answer
I don't really understand your use case correctly, but probably you need to implement a language negotiation manager. See an example at `/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationBrowser.php`.

If you also need to change the url for adding language, or changing how the links in language switcher work, you may need to override some more methods. See an example at `/core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php`.
> 0 votes

---
Tags: 8
---


# Question
Title: CSS not working after Commerce AJAX processed on field
I have got a problem with css after Drupal processes radio buttons on Drupal Commerce product page. Radio buttons are formatted (images instead of typical radio)

**Formatted radios**

After clicking any of radio buttons:

The HTML:

```
<div class="form-item form-type-radios form-item-attributes-field-pack-size">
    <label for="edit-attributes-field-pack-size">Pack size </label>
    <div id="edit-attributes-field-pack-size" class="form-radios">
        <div class="form-item form-type-radio form-item-attributes-field-pack-size">
            <input type="radio" id="edit-attributes-field-pack-size-50-grams" name="attributes[field_pack_size]" value="50 grams" checked="checked" class="form-radio ajax-processed">  <label class="option" for="edit-attributes-field-pack-size-50-grams">50 grams </label>

        </div>
        <div class="form-item form-type-radio form-item-attributes-field-pack-size">
            <input type="radio" id="edit-attributes-field-pack-size-100-grams" name="attributes[field_pack_size]" value="100 grams" class="form-radio ajax-processed">
            <label class="option" for="edit-attributes-field-pack-size-100-grams">100 grams </label>

        </div>
    </div>
</div>

```

The SCSS is:

```
    #edit-attributes-field-pack-size {
        overflow: hidden;
        input {
            opacity: 0;
        }

        label[for|="edit-attributes-field-pack-size"] {
            display: block;
            width: 102px;
            height: 102px;
            background: url('/sites/all/themes/blissout/img/radio.png') no-repeat;
            text-indent: -1000px;
            overflow: hidden;
        }
        label[for|="edit-attributes-field-pack-size-50-grams"] {

        }
        label[for|="edit-attributes-field-pack-size-100-grams"] {
            background-position: -102px 0;
        }
        label[for|="edit-attributes-field-pack-size-500-grams"] {
            background-position: -204px 0;
        }
    }

```

And it works perfectly until the ajax is "preprocessed" on radios. That Ajax calculates the price depending on the size of selection (it's drupal commerce code). It's different product variation but the classes doesn't change.

I have tried putting CSS into html.tpl.php. If the trigger('create') is solution could someone describe me step by step how to write js/jquery code for it?

# Answer
The problem is you're relying on an ID for your CSS selector, but when Drupal's Forms API refreshes a form via #ajax, it appends a numeric suffix to the ID to maintain a unique ID prior to replacement. Your CSS no longer applies because the selector no longer matches any element on the page. You should switch this to some class based selector instead.
> 1 votes

---
Tags: commerce, ajax, javascript, theming
---


# Question
Title: Make a relationship to last element of a Field Collection
I have a View with a relationship to Field Collection (with unlimited cardinality). I need this relationship to connect only to the last element (having the largest delta). How can I do this?

# Answer
> 0 votes
In order to show only the Field Collection item having the largest delta, you can use the Field Collection Views module as your formatter (i.e., Views field-collection items) in your View (i.e., parent View). With this formatter you can select another View (i.e., sibling View) to display your field collection items (so you will get a View within a View).

In the parent View you simply specify in the 'Multiple field settings' to display only the last result (i.e., Display 1 value(s), starting from 0, reversed checked), see screenshot below:

Note: in order to output the results in the order that is specified on your node, you have to set a relationship in the sibling View \<view\_name\_for\_field\_collection\> to 'Field collection item: Entity with the {Field Collection field}' and mark it as required. See this issue for the Field Collection Views for an extended explanation.

Let me know if you need any help with this.

---
Tags: views, entities
---


# Question
Title: Where should I be storing custom node-related data?
There are several types of data my website generates for every node. Node's popularity score, node's comment count obtained from a 3rd party API, etc... This data is set for every node.

In the past I've used to just add hidden fields to each node, i.e. `field_popularity_score`, `field_comment_count`, etc..., and had the fields updated on `hook_cron`; but I've ran into an issue. Each time those fields are updated, the node's revision date would change also.

Where should I be storing this data? I'd prefer to stay away from using the standard node fields, as it would break its purpose.

## Update

Apparently, per this post, Drupal 5 used to allow storage of serialized data into `$node->data`.

## Update

Interesting enough, Node object reference page lists `$node->data` as part of Drupal 7. I would love to hear if there is a way to use that field to store serialized data in Drupal 7.

# Answer
> 5 votes
I would suggest making your own table in the database, it's a perfectly acceptable practice if you name the table something unique that isn't likely to collide with other modules.

The database API is an extremely useful resource for this.

---

\[edit:\] Thanks to J. Reynolds - in this instance you will definitely need to tell Views about your table.

# Answer
> 2 votes
Set `$node->revision = FALSE` when saving your node and continue to use the field API. There are many advantages to using fields and they can be spooled up and destroyed programmatically (see `commerce_price` for an example) when your module is enabled an disabled.

Advantages are:

* Use existing table schema from defined field types.
* Integrates with display management tools (DS, Panels or "manage display"), with all the field formatters for that type.
* UI is there if you need it. You can set #access =\> false or use form displays in D8.
* More modules will be aware of your data and integrate with it (views was a good example).
* Way less custom code to maintain.
* Way less time consuming.

For a simple comment count or popularity score you should be staying well away from a custom table or the entity API.

Also, using `$entity->data` is also a recipe for a disaster. Not being able to filter or query on your data pretty much mitigates any advantage of using a relational database.

---
Tags: 7, database, entities
---


# Question
Title: How can I filter users within a user-configurable range in Views?
For example, consider a dating website. Each user has an **Age** stored in their profile. They also have a **Max age** and **Min age**, which are the maximum and minimum ages of people they hope to receive interest from (in other words, users with ages outside the range **Min age** \- **Max age** should not be allowed to contact that user).

How can I build a page in Views that filters the results for the current user to show other users that *both* meet the current user's age range and for which the current user meets their age ranges?

In other words, I need to somehow filter the results like this:

* Only show users that have ages within the range of the current user's **Max age** and **Min age** (example: current user is 20 and wants to see users from 18-25; filter to show users from 18-25)
* Only show users for which the current user has an age that falls within the range of their **Max age** and **Min age** (example: current user is 20 and wants to see users from 18-25; filter to show users who want to receive messages from someone age 20)

Is this something I can somehow do with contextual filters, or do I need to write my own custom filter?

# Answer
Install sandbox project Views arguments in filters

Add four contextual filters to your user view:

1. User:Uid, hide view when filter not available, Exclude (you will send in the user's own uid and exclude him from the result as you do not want him to be matched against himself)
2. Global:Null, hide view when filter not available, and give it an administrative title of 'current age'. (You will send it the current user's age as a param).
3. Global:Null, hide view when filter not available, and give it an administrative title of 'min age'. (You will send it the current user's min age preference as a param).
4. Global:Null, hide view when filter not available, and give it an administrative title of 'max age'. (You will send it the current user's max age preference as a param).

>

Then add normal filters as follows:

>

That should take care of the view, and you now just have to construct a link to add the parameters manually, or override a view hook to do so. Possible candidate would be hook\_views\_pre\_view where you have direct access to args param, but on other hooks it should be available on the $view object.

Something like this code will work, and you can just add your own defensive programming and substitute where appropriate.

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "compatible" &&  $display_id == "page" && user_is_logged_in() && count($args) != 4) {
    global $user;
    $account  = user_load($user->uid);
    $age = field_get_items("user", $account, "field_age");
    $min_age = field_get_items("user", $account, "field_min_age");
    $max_age = field_get_items("user", $account, "field_max_age");
    $args = array(
      $account->uid,
      $age[0]['value'],
      $min_age[0]['value'],
      $max_age[0]['value']
    );
  }
}

```
> 1 votes

---
Tags: views
---


# Question
Title: How to reduce the speed of rotation in view ticker module
I created a view with `views ticker` for the newsfeed items. The newsfeed items are configured to vertical scroll with `speed: very slow.` But the rotation speed of the items are a bit fast and I'm inclined to reduce the speed of the rotation.

So, I looked into module files and tried to change the vTicker\_speed values in the `views_ticker_style_plugin.inc` file located in the `../sites/all/modules/views_ticker/includes/`

I changed the values in the line 142. Previously, it was 1000 - one second to 40000 - forty seconds. But I couldn't get it reflected in the site. It scrolls with same speed as it was before.

Can any one suggest me how to reduce the speed. Or is there any other module to work with vertical scroll??

# Answer
> 0 votes
If you are using FADE effect, look in the folder xxxx of the module the views.ticker.fade.js file, and rise the value of the:

```
b = b || 4000;

```

to something like 10000 or 12000.

Good luck.

# Answer
> 0 votes
It is not enough if you edit only options under `$form['vTicker_Options']['vTicker_speed'] = array(` but you also need to edit it's options under `$form['vTicker_Options']['vTicker_pause'] = array(` on line # 121 and related options are on line # 126, to get changes eye catching. Also you can change it's scrolling speed in drupal's edit view page under `Format -> settings -> SHOWVERTICAL SCROLLER OPTIONS -> Scroller pause`

After you did clear drupal cache or click on some link in the view's edit page and don't do anything and click on apply button, so that save button will be available on the top of the view's edit page, then click on save button to take effect with your manual edits.

also you can give your own option to `$form['vTicker_Options']['vTicker_speed'] = array(` if you interest. :) Hope this will help.

---
Tags: views
---


# Question
Title: Associating comments with special pages/module output
I have what one could consider an "irregularity" in a Drupal module. I have this unique case (mostly due to vendor inconsistencies and ever-changing requirements) where when a user requests a certain item (in this case, something from an inventory database), a hook\_menu() call routes them to a callback that polls the inventory API (a REST service), and we pass that REST data to the user through a theme call in Drupal. Attempts to actually display the data directly to the browser are mostly unsuccessful due to CORS issues, and nobody is answering the phone at the vendor.

I've been informed there are some additional requirements that require our newly minted psuedo-content to host a "Comments" section, which if my knowledge of the CMS is clear, only associates with items the system is storing, e.g Entities and Nodes. Before I ask about a definitive solution, I should ask, if **there is any way to convince the CMS otherwise, and track a comments record for this faux-content**, or if my only option is to save this data as a node (even if its just a single field), and then 301 Redirect to it once saved. Any thoughts? I know this is a rather abstract question with an equally abstract solution, but time constraints make longer-term solutions unobtainable for now.

# Answer
> 0 votes
Well, I think you pretty much have the answer.

Handling comments without the help of the Node API would probably be a lot of work.

But if you don't need all the extra features the Node layer brings, you can try to apply the same method on an entity. The Reply module takes care of attaching comments to your entity type.

Again, it's more work than simply using a node to store each item comments section. Just use your callback function to load or create a node with a field storing the item ID (if it doesn't exist yet on the database).

You can then use `drupal_goto('node/' . $nid, array(), 301)` to redirect the user to the comments page.

---
Tags: 7, comments
---


# Question
Title: What is Best Way to Retrieve Status Messages in Multiple Locations?
We like to share the status messages in multiple location in single request, so we retrieve them:

```
function get_messages(){
    $status_messages = array();
    //loop through each message type
        foreach (drupal_get_messages(null, false) as $type => $messages) {
               foreach($messages as $key => $message){
                   $status_messages[$type]['enabled'] = true;
                   $status_messages[$type]['messages'] = array(
                       'message' => $message
                   );
               }
        }
return $status_messages;
}

```

Here, since we are passing "FALSE" to the drupal\_get\_messages function the messages are not reset which is what we like because multiple locations gets to call this function, however. At some point, the messages need to be reset.

1. One option is to clear messages at the last point of the request. Where and how to do that?
2. Another option, would implement a cache and run drupal\_get\_messages() with "TRUE" to call once and reset at the same time. I am not familiar with cache in Drupal or PHP. How to do that?

In short, we like to access status messages in multiple locations and $variable\['messages'\] is not available to serve the purpose. How to do that? Thank You for help

# Answer
The solution was using Drupal cache pattern by storing messages in static space as following:

```
function get_messages(){
    $status_messages = &drupal_static(__FUNCTION__);

    if(!isset($status_messages)){
        //loop through each message type
        foreach (drupal_get_messages(null, true) as $type => $messages) {
               foreach($messages as $key => $message){
                   $status_messages[$type]['enabled'] = true;
                   $status_messages[$type]['messages'] = array(
                       'message' => $message
                   );
               }
        }
     }
     return $status_messages;
}

```

Here, we get the static reference first and then check if its already set. if not, we retrieve the messages and reset at the same time by calling Drupal API function drupal\_get\_messages with "true" parameter. As result, we reset the messages that solves our problem and, in addition, our performance is improved due to caching

I have also summarize it all at my blog post "Caching In Drupal"
> 0 votes

---
Tags: status-messages
---


title: Child content types

text:
# Question
Title: Child content types
I need to create two content types (Call List and Call Announcements), in Call Announcements there are 5 fields, in Call List there are 12 fields but 5 of them are mutual with Call Announcements, I do not want to create 2 different content types (Call List, Call Announcements) because when the user create a node, he should be able to choose where the node is shown (in Call List, in Call Announcements, Both). (Call List and Call Announcements should be in the same database table)

>

How can I do these?

# Answer
Have a look at the Conditional Fields module and use a taxonomy vocabulary with Call List and Call Announcements as items that users can select on node creation. Of course, add a term reference field to that vocabulary under "manage fields" for the parent content type.

Conditional Fields can hide/disable/show fields upon user choice (Call List or Call Announcements).
> 3 votes

---
Tags: nodes
---


title: Alter menu item markup in Drupal 8

text:
# Question
Title: Alter menu item markup in Drupal 8
I am trying to play around with Drupal 8 menu. How I understand now menu is a service, so how to alter menu output in Drupal 8? Is there any documentation? Because *googling* show no useful results.

What I am trying to achieve is move **active** class from `<a>` element to parent `<li>` element, this should be possible to do in .twig template (I wouldn't like that) so how to get menu in Drupal 8 and alter it's attributes?

# Answer
I have a complete example for twitter bootstrap, I use:

Note: this code is incomplete, maybe broken with beta update, but it's an example/introduction.

```
function nature_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Prevent dropdown functions from being added to management menu so it
    // does not affect the navbar module.
    if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) {
      $sub_menu = \Drupal::service('renderer')->renderRoot($element['#below']);
    }
    elseif ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) {
      // Add our own wrapper.
      unset($element['#below']['#theme_wrappers']);
      $sub_menu = '<ul class="dropdown-menu">' . \Drupal::service('renderer')->renderRoot($element['#below']) . '</ul>';
      // Generate as standard dropdown.
      $element['#title'] .= ' <span class="caret"></span>';
      $element['#attributes']['class'][] = 'dropdown';
      $element['#localized_options']['html'] = TRUE;

      // Set dropdown trigger element to # to prevent inadvertant page loading
      // when a submenu link is clicked.
      $element['#localized_options']['attributes']['data-target'] = '#';
      $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
      $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
    }
  }
  // On primary navigation menu, class 'active' is not set on active menu item.
  // @see https://drupal.org/node/1896674
  if (($element['#href'] == '<front>' && drupal_is_front_page()) && (empty($element['#localized_options']['language']))) {
    $element['#attributes']['class'][] = 'active';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . new Attribute($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

After I have my view nammed "menu--main.html.twig" :

```
{#  https://api.drupal.org/api/drupal/core!modules!system!templates!menu.html.twig/8
    menu_name: The machine name of the menu.
    items: A nested list of menu items. Each menu item contains:
      attributes: HTML attributes for the menu item.
      below: The menu item child items.
      title: The menu link title.
      url: The menu link url, instance of \Drupal\Core\Url
      localized_options: Menu link localized options.
#}
<nav class="navbar navbar-default" role="navigation">
  <div class="container-fluid">
    <div class="navbar-header">
      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="{{ front_page }}">Site Name : {{ site_name }}</a>
    </div>

    <div class="collapse navbar-collapse">
      {# All menu and submenu items #}
      <ul class="nav navbar-nav">
        {% for item in items %}
          {# Menu with submenu #}
          {% if item.below %}
            <li class="dropdown">
              <a tabindex="0" data-toggle="dropdown">{{ item.title }} <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">
                {# Menu -> Submenu #}
                {% for item in item.below %}
                  {% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
                {% endfor %}
              </ul>
            </li>
          {# Menu without submenu #}
          {% else %}
            {# Menu - Link #}
            <li><a tabindex="0" href="" {{ item.attributes }}>{{ item.title }}</a></li>
            {# Menu - Separator #}
            {% if loop.last == false %}<li class="divider"></li>{% endif %}
          {% endif %}
        {% endfor %}
      </ul>

      <form class="navbar-form navbar-left" role="search">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>

      <ul class="nav navbar-nav navbar-right">
        <li class="dropdown">
          <a tabindex="0" data-toggle="dropdown">Dropdown 3<span class="caret"></span></a>
          <!-- role="menu": fix moved by arrows (Bootstrap dropdown) -->
          <ul class="dropdown-menu" role="menu">
            <li><a tabindex="0">Action</a></li>
            <li><a tabindex="0">Another action</a></li>
            <li><a tabindex="0">Something else here</a></li>
            <li class="divider"></li>
            <li><a tabindex="0">Separated link</a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav>

```

This view call "menu-infinite-child.html.twig" for unlimited infinite child (submenu) :

```
{# Submenu -> Submenu #}
{% if item.below %}
  <li class="dropdown-submenu">
    <a tabindex="0" data-toggle="dropdown">{{ item.title }}</a>
    <ul class="dropdown-menu">
      {% for item in item.below %}
          {% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
      {% endfor %}
    </ul>
  </li>
{# Submenu without Submenu #}
{% else %}
  <li><a tabindex="0">{{ item.title }}</a></li>
{% endif %}

```

Note: I use this configuration with bootstrap-submenu http://vsn4ik.github.io/bootstrap-submenu (MIT license).
> -2 votes

# Answer
There is one central problem: the active class is not always added in PHP, but for non-anonymous users its calculated using some javascript, see "active-link.js". For anonymous users, its calculated in `\Drupal\system\Controller\SystemController::setLinkActiveClass`
> 4 votes

---
Tags: theming, routes, 8
---


title: Label for Child in Hierarchical Select

text:
# Question
Title: Label for Child in Hierarchical Select
While using Simple Hierarchical Select Module, I have 2 levels of Hierarchy for my Phone.

However I want to add the label for Child list like:

Is this possible? then how?

# Answer
You Can do with custom jquary with set Intervel function.

Eg: i have attached screenshot at bottom

//Add label to state //on change first level(here country)

```
$('select.shs-select-level-1').change(function(){

    var $aSelected = $('.shs-wrapper-processed').find('label');

    if( $aSelected.hasClass('Extra-Label1') ){
        $('.Extra-Label1').text("State");
    }
    else{
        $('select.shs-select-level-2').before('<label class="Extra-Label1">State</label>');
    }

});

```

//Add label to city

```
$('select.shs-select-level-2').change(function(){

    var $aSelected = $('.shs-wrapper-processed').find('label');

    if( $aSelected.hasClass('Extra-Label2') ){
        $('.Extra-Label2').text("City");
    }

    else{
        $('select.shs-select-level-3').before('<label class="Extra-Label2">City</label>');
    }
});

```

//The above code is ok, but last label will loss after change any select levels so needs add in set intervel function

```
setInterval(function(){
    var $aSelected = $('.shs-wrapper-processed').find('label');
    var $bSelected = $('.shs-wrapper-processed').find('select');
    if( $aSelected.hasClass('Extra-Label2')&& $bSelected.hasClass('shs-select-level-3') ){
        $('.Extra-Label2').text("City");
    }
    else{
        $('select.shs-select-level-3').before('<label class="Extra-Label2">City</label>');
    }

},1000);

```
> 1 votes

# Answer
I know I'm late, because this answer has been answered long time ago, but I don't think this is the right way to do it, especially with the java script interval function – it might work but in many cases may cause a problem.

For those who need the same result I suggest to use this java script code which is based on action when the ajaxStop event is triggered.

First you nedd to create a java script file in your module directory, for exapmle: `YOUR_MODULE_NAME/js/custom_shs_behaviors.js` with the following code:

```
/**
 * @file
 * Custom behaviors for Simple hierarchical select:
 *   Change the first option text from "- None -" to whatever you want (default: "- Any -").
 *   Create labels for each level.
 */
 (function($) {
  Drupal.behaviors.customShsBehaviors = {
    attach: function (context, settings) {

      // Helper function for an option text replacement.
      // use: optionObj.replaceOptionText(); for default replacement from '- None -' to '- Any -'.
      // or optionObj.replaceOptionText('Foo'); to replace the '- None -' with 'Foo'.
      $.fn.replaceOptionText = function(replacement) {
        var replacement = replacement ? replacement : '- Any -';
        if ($(this).text() == Drupal.t('- None -')) {
          $(this).text(Drupal.t(replacement));
        }
      };

      // Function that helps to get the select element width including its padding and margin.
      $.fn.getSelectWidth = function() {
        var width = Math.round($(this).wrap('<span></span>').outerWidth(true));
        $(this).unwrap();
        return width;
      }

      // Define labels.
      var labels = ['Label-1', 'Label-2', 'Label-3'];

      // act when the ajaxStop event is triggered (there are no more Ajax requests being processed.)
      // see: @link http://api.jquery.com/Ajax_Events/ @endlink
      $('.shs-wrapper-processed').ajaxStop(function(event, xhr, settings) {

        $("select.shs-select").each(function(level) {

          // fix the SHS bug - new level that is being created has the same ID as the previous one.
          // make sure that each select has an ID and the class corresponding to the level.
          // YOU CAN USE THESE TWO LINES ONLY IF YOU ARE USING SHS WITH THE ABILITY TO ADD NEW LEVELS.
          $(this).attr('id', $(this).attr('id').replace(/(.*)select-(\d+)/, "$1select-" + (level+1)));
          $(this).attr('class', $(this).attr('class').replace(/(.*)level-(\d+)/, "$1level-" + (level+1)));

          // Replace the first option text using the helper function for an option text replacement.
          $("option", this).first().replaceOptionText();

          // Get label width.
          var labelWidth = $(this).getSelectWidth();

          // Create label.
          if ($("label[for='" + $(this).attr('id') + "']").length == 0) {
            $(this).parent().before(
              "<label for='" + $(this).attr('id') + "' style='display: inline-block; width: " + labelWidth + "px'>" + labels[level] + "</label>"
            );
          }

          // Remove the label if the select element has just been removed by clicking any option on lower level.
          // There might be several Ajax requests bound with this action,
          // so we have to make sure that our "removing process" will be executed at most once.
          // See: @link http://api.jquery.com/one/ @endlink
          $("option:not(:selected)", this).one("click", function() {
            $(".shs-wrapper-processed").parent().find("label").each(function() {
              if ($(this).attr('for').slice(-1) > level+1) {
                $(this).remove();
              }
            });
          });
        });
      });
    }
  };
})(jQuery);

```

And attach the java script file to your form. You can do it by using the hook\_form\_alter() in your theme or module file:

```
/**
 * Implements hook_form_alter.
 */
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {

  switch($form['#id']) {
    case 'YOUR-FORM-ID' :
      $form['#attached']['js'][] = drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/custom_shs_behaviors.js';
    break;
  }
}

```

You're done! With this code you can set the label for each level of your shs and even change the default option text, for example: from `- none -` to `- any -`.
> 3 votes

# Answer
Some developers may wish to use the pre-existing label over the top category to represent a title for the hierarchial select (rather than a header for the top category).

Here's another (jQuery) way you could achieve a similar effect, using a locational hierarchy for the demo:

In your custom js you can add a top level label when the document is "ready" - custom way or the preferred Drupal.behaviors way (neither demonstrated).

```
$('select.shs-select-level-1').before('<label class="shs-label">' + Drupal.t('Region') + '</label>');

```

Then monitor for any changes to the entire container. If one is detected, you can clear all the labels of a custom class and then re-attach all the classes where jQuery can ignore exceptions

```
$('#field-select-a-city-add-more-wrapper').change(function () {
    $('#field-select-a-city-add-more-wrapper').find('label.shs-label').remove();
    $('select.shs-select-level-1').before('<label class="shs-label">' + Drupal.t('Region') + '</label>');
    $('select.shs-select-level-2').before('<label class="shs-label">' + Drupal.t('Country') + '</label>');
    $('select.shs-select-level-3').before('<label class="shs-label">' + Drupal.t('State') + '</label>');
    $('select.shs-select-level-4').before('<label class="shs-label">' + Drupal.t('City') + '</label>');
});

```
> 0 votes

---
Tags: 7, taxonomy-terms
---


title: Firing a Ctools Modal on a link click

text:
# Question
Title: Firing a Ctools Modal on a link click
Once again, I am stuck asking questions on CTools that people have asked a million times before. I have a view that displays a list of custom-developed entities (built with ECK) and each one has a link that should show a Ctools-driven modal.

I looked at a few approaches (namely this) to explore any method to get Drupal to display said modal. I figured that I didn't need all this extra views hook logic to fire the modal -- ideally, if a `hook_menu()` click is fired, it should open the modal and any contents I send to it (which will be done through additional methods). Right now, it treats the logic as a static route, and returns the results as a page. I also explored using the Ctools Auto Modal module (seen in the example, which reflects current code), which also returns the same results when used as documented.

I'm completely lost here, mostly because of the reach of Ctools and the various conflicting forms of documentation on its use for something simple as a tie in for `hook_menu()`. The long hours i've been pouring into this project are clearly having a toll on my ability to implement this, does anyone have any insight?

The actual logic is below:

```
/**
 * Implements hook_menu()
 *
 * The sole item call in hook_menu is driven from a URL that is built
 * Within a view, from rewrite rules. When activated, it should render
 * the new modal window.
 */
function example_menu() {
  $items['selectbook/%'] = array(
    'title' => "Perk Modal",
    'page arguments' => array(1),
    'page callback' => 'example_modal_page',
    'access arguments' => array('view content'),
    'access callback' => TRUE,
    'modal' => TRUE,
  );

  return $items;
}

/**
 * Returns a test modal
 */
function example_modal_page($js = null, $attribute = null) {
  return "Test Modal"; //Right now returns as new page call not as a modal
}

```

# Answer
You mentioned you tried ctools\_automodal which is a quick way to accomplish creating a link in a view to open in a modal. With the module, you can use hook\_menu\_alter to add 'modal' =\> TRUE to the link menu router item. Nothing else is involved. Ctools\_automodal handles all the rest. That means you don't need your own example\_modal\_page page callback, and you don't need to call ctools\_modal\_render. Let the Ctool\_automodal module do that for you.

If your path has a wildcard, then ctools\_automodal will need an actual wildcard variable defined and a "\_load" function. In your example above, your path is selectbook/%. If you change it to "selectbook/%selectbook" and defined a selectbook\_load function then ctools\_automodal should recognize it as a modal path. Here's an example:

```
/**
 * Implements hook_menu().
 *
 * The sole item call in hook_menu is driven from a URL that is built
 * from rewrite rules within a view. When activated, it should render
 * the new modal window.
 */
function example_menu() {
  $items['selectbook/%selectbook'] = array(
    'title' => "Perk Modal",
    'page arguments' => array(1),
    'page callback' => 'example_modal_page',
    'access arguments' => array('view content'),
    'modal' => TRUE,
  );

  return $items;
}

function selectbook_load($selectbook) {
  // Todo: Do something with selectbook, like load an entity.
  // For this proof of concept, just return it.
  return $selectbook;
}

function example_modal_page($selectbook) {
  // If you loaded an entity in selectbook_load, then you have that
  // fully loaded entity in $selectbook.
  return "Test Modal";
}

```
> 0 votes

---
Tags: 7, chaos-tool-suite
---


# Question
Title: is there a way to use preprocess_page only for certain page templates?
I have a preprocess\_page function in template.php that I need to use to pass a variable into a page (not node) template. The code works where I need it to, but it's also trying to run on EVERY page, which I don't want.

Is there a way to make a `hook_preprocess_page()` function run only on certain page templates, or a different function name (e.g. `mytheme_preprocess_page_speaker()`)?

The preprocess function I am using is the following one.

```
function bluemasters_preprocess_page(&$vars) {

  if ($vars['node']->type == 'session') {
      $sess_type = field_get_items('node', $vars['node'], 'field_session_type');
      $sess_type_name = $sess_type[0]['taxonomy_term']->name;
      $vars['session_type_name'] = $sess_type_name;
  }

}

```

This works on nodes that are of the content type "session", but when I view other pages that use other content types, I get an error message telling me there's an undefined index of 0 on the line that's defining `$sess_type_name`. I need to make it so that the function ONLY runs on nodes of type session.

**updated** it appears the error is only occurring on a view with a page display that displays content type=session. So how can I avoid that?

# Answer
> 1 votes
I made a test using the following code, in my test site.

```
function code_testing_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    watchdog('code_testing', var_export($variables['node'], TRUE), array(), WATCHDOG_DEBUG);
  }
}

```

I then created a view showing the nodes of a specific content type (in my case, it was snippet). When I visited the view page, and checked the output from `watchdog()`, I have not found any information about `$variables['node']`.
Effectively, that is what I would expect, as `$variables['node']` is set in template\_preprocess\_page() using the following code.

```
  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }

```

Probably, if the view uses a URL like http://example.com/node/1, and there is a node with that node ID, `$variables['node']` could be initialized. Differently, if the view is using a different URL, I would not expect `$variables['node']` to be set.

To notice that views\_preprocess\_node() uses the following code.

```
  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
    $vars['view'] = $vars['node']->view;
    $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name;
    if (!empty($vars['node']->view->current_display)) {
      $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;

      // If a node is being rendered in a view, and the view does not have a path,
      // prevent drupal from accidentally setting the $page variable:
      if ($vars['page'] && $vars['view_mode'] == 'full' && !$vars['view']->display_handler->has_path()) {
        $vars['page'] = FALSE;
      }
    }
  }

```

Probably the first control statement can be used in `hook_preprocess_node()` to check if a view is being served.

# Answer
> 0 votes
I was looking for a way to disable the page title display for a certain menu callback via hook\_preprocess\_page() and came across your thread. The best solution I could find was looking in `$variables['theme_hook_suggestions']`, as follows:

```
// Loads for menu callback 'app'
function mymodule_preprocess_page(&$variables) {
  if ('page__app' == $variables['theme_hook_suggestions'][0])
    $variables['title'] = false;
}

```

---
Tags: 7, theming
---


# Question
Title: Views block link defaults to target="_blank" using rewrite output
My client is using d6 and views 3. They want to be able to display a box containing a random static image with an internal link to display in the same browser tab or an external link that would display in a new tab. I created a content type with a field to upload an image, a text field to include a url, and (for simplicity's sake) a text field to include the target (either \_self or \_blank). Then I built a views block to display each image using the 'rewrite the output of this field' option on the image field. The text for the rewrite looks something like this:

```
<a href="[field_link_value]" [field_target_value]>[field_image]</a>.

```

The problem I'm having is even when field\_target\_value has target="\_self" in it, views or something is ignoring it and the a tag is always showing up in firebug with target="\_blank". Another weird thing is that when I display the page source, the target doesn't appear at all. When you click on the image, it does in fact bring the page up in a different tab as expected.

I've looked in the views code and did not see anything in there that seems to be the cause. There is some custom code and theming on the site but I have not been able to find anything in there either.

Anyone have any clues why or thoughts on the strategy I am trying to use ??

# Answer
> 0 votes
Print the results from the views template.you can rewrite the views template for that specific field and check the link that whether its external or internal using the drupal function url\_is\_external and you can add the attribute target="\_blank" to those views fields that are external urls.

Off topic suggestion : if you want all external links on your website should open in new tab then you can use the extlink module to open all external links in new tabs.

> External Links is a small module used to differentiate between internal and external links. Using jQuery, it will find all external links on a page and add an external icon indicating it will take you offsite or a mail icon for mailto: links.

# Answer
> 0 votes
Thank you for the suggestions. I ended up using the linkimagefield module and removing the rewrite from the view but it still showed the same behavior. I finally tracked it down as some javascript code originally added to check if the URL started with the letters http. If so, the link was treated as external and target='\_blank' was added, overriding any other target attribute included. So this was ultimately not a drupal thing.

---
Tags: views
---


# Question
Title: What will happen to my existing panels if I reinstall the panels module?
The need is to reinstall panels because of some issues with it. However what will happen to the already existing panels if you reinstall or even remove panels entirely?

# Answer
You will lost your custom panel configuration. To prevent that you can export all your panels to code with features.

This is because modules should remove its own data on hook\_uninstall.

```
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

```

This way you will have a features module with all your panels configuration.

This are the steps:

1. Install features module.
2. Go to admin/structure/features/create
3. Give a name to the feature module.
4. Select panels configuration
5. Download the feature.
6. Move this module to the features folder (site/all/modules/features).
7. Uninstall panels
8. Enable panels
9. Active the feature on admin/structure/features

There are also 'export' and 'import' tabs/links on the Panels UI and Pages UI but this is a manual process and can be slower than using features.
> 6 votes

# Answer
**If** all you are doing is replacing the code and not disabling and uninstalling the module, this won't affect your existing panels, however it is always a good idea to back them up using either the method mentioned by jorgetutor or a full database backup (always useful)
> 1 votes

---
Tags: nodes, panels
---


title: Views#3 custom handler error

text:
# Question
Title: Views#3 custom handler error
I'm learning how to implement a custome Views 3 field handler.

Using the following handler code:

```
class views_handler_filter_sub_nodes extends views_handler_field_custom{

    function options_form(&$form, &$form_state){

        drupal_set_message('My customer handler is responding', 'warning');

        parent::options_form(&$form, &$form_state);
    }
}

```

I get the following error, repeated twice:

```
Deprecated function: Call-time pass-by-reference has been deprecated in _registry_check_code() (line 3119 of /var/www/My-Site/includes/bootstrap.inc)

```

I have removed the **&** symbols from the arguments. The errors go away but so do all the configuration fields in my View component, as illustrated below:

Can anyone help, please?

# Answer
> 0 votes
Huh? It's been a year and no one has found the error referred to by the message ("Call-time pass-by-reference").

Leave

```
function options_form(&$form, &$form_state) {

```

unchanged.

And change this:

```
parent::options_form(&$form, &$form_state);

```

to:

```
parent::options_form($form, $form_state);

```

and your error should go away.

---

Briefly (for those who are new to user defined functions, as it relates to this issue)...

**Function declaration**

A function's arguments are defined in the function's declaration (the line that begins with the `function` keyword). They are a list of PHP variables the function expects to receive from the caller (see Function arguments in the PHP manual for more information). The function declaration determines how many arguments are expected, their datatypes, whether they are required or optional, and whether they are passed by reference or not, among other things.

You have surely noticed the `$form` and `$form_state` variables used in lots of function declarations, sometimes with and sometimes without a preceding **&**. Each **&** tells the function that that argument will be passed to it *by reference*. This means the function does not receive a copy of the variable from the caller (as usual), but a pointer to it.

A function may change the contents of references directly from within the function, while a copy is private to the function and must be `return`ed, if the function want its changes to be available to the function that called it (of course, the caller must know what to do with the returned data). Any changes made to reference variables remain after the function ends.

**Function execution**

When a function is called/executed, the **&** MUST be omitted, otherwise you get the aforementioned "Call-time pass-by-reference" error. The function declaration determines if it's a reference, not the caller.

---
Tags: 7, views
---