title: How to get last list item in Rules?

text:
# Question
Title: How to get last list item in Rules?
I have a multi-value field. How can I get the value with highest delta value in Rules? The only idea I have is to create a custom component a loop through all list values in it. Then I could use a auxiliary variable and compare each item with it (so that variable will correspond to highest value). This seems to be rather slow. Is there any better solution?

# Answer
> 1 votes
Or add a `php script` step to your form and simply use the Field API to extract the highest value of the `delta` as a `variable` to be used later in Rules execution.

---
Tags: 7, rules
---


# Question
Title: How can I return literal JSON from a node as a JSON object in views json?
I have a content type with a field called output. This field will contain JSON. I want to output this field as JSON using Views JSON (in Views Datasource). The problem I'm encountering is views datasource is a. wrapping my field in quotes, and b. escaping my double quotes...

```
    [
    {
    "content": "{\"account-confirmation\":{\"body\":\"\",...

```

I need it to return something like:

```
    [
    {
    "content": {"account-confirmation":{"body":"",...

```

I've tried everything I could possibly think of. Is there any way I can output the literal value of the field without wrapping the value in quotes and escaping quotes?

# Answer
> 0 votes
Views Datasource will escape the contents of any string field. If the field were an object, it would be formatted as JSON. (See: `views_datasource/views/plugins/views_plugin_style_json.inc`.) There doesn't seem to be any way to override this behaviour other than patching the module or using some field type that would produce this result.

I faced a somewhat related problem and had to write my own API endpoint to get the JSON as I wanted it. I used `views_get_view_result()` to get the raw data and rework it so that I had the correct array structure. Then I run drupal\_json\_encode().

---
Tags: views, services
---


# Question
Title: How can I redirect users upon login sometimes but not break the "Forgot password?" function?
I'm using Rules to redirect users with certain roles upon login using the *Page Redirect* action. The "Force redirect" option is set to true (changing this to false does not fix the problem, and if it is false then users who log in from a block on the front page are taken back to the front page, which is not what I want).

My problem occurs when a user forgets their password and requests a one-time login link via e-mail. When the user clicks the link, he/she is taken to the login page. From this page, pressing "Login" will redirect the user according to my custom rule instead of taking the user to the page where the password can be changed.

How can I redirect my users using Rules without breaking the forgot password function?

# Answer
You can do that with a rule like that:

```
{ "rules_after_login_redirect_to_news" : {
    "LABEL" : "After login redirect to news.",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "0",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_login" ],
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "^user\/reset\/",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "news" } } ]
  }
}

```
> 8 votes

# Answer
OK...after doing some looking around and a bit of playing around, this solution seems to work:

Add a condition to your re-direct rule with the following php-evaluation (make sure you have PHP filter module turned on...It's part of the core):

```
if (arg(0) == 'user' && arg(1) == 'reset') {
  return false;
} else {
  return true;
}

```

This should check to see if the user is using a one-time password and if so skip the re-direct Rule.

Hope that helps! Found some different situations on Rules forum, and that seems to be a good compromise.
> 6 votes

# Answer
I tried the answer but it was not working for me, not sure what the `^` means but i ended up having my rule with the following:

```
{ "rules_after_login_redirect_to_news" : {
    "LABEL" : "After login redirect to news.",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "user\/reset\/*",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "news" } } ]
  }
}

```

The `*` means that anything after user/reset will be brought into the rule.

Also it should be noted that if you are using this with anything else, you should add an 'AND' set with it so it will make sure it relates both sets properly.
> 2 votes

# Answer
I am sure there is 100 ways to do this. The Login Destination module looks like it may accomplish what you are looking for.

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.

I looked through the issues, and it seems they have fixed the "broken forgot password" problem in their implementation. Might be worth a shot, although it looks like it isn't under "active" development. Last update was 2010.
> 1 votes

# Answer
The Password Reset Landing Page (PRLP) modules works well without requiring Rules (...in my experience).

There's also Password Hustle, which almost got me there as well.
> 1 votes

---
Tags: rules, redirection
---


title: Customise Mollom status messages

text:
# Question
Title: Customise Mollom status messages
I had a look around and couldn't see if this had been asked before so decided to create a new question. Please delete this if this is a duplicate.

I'd like to customise the status messages that appear to users when they trigger the captcha and profanity filter, as the default messages are quite long winded. My experience with Drupal is VERY limited and am not sure if there is a module specific hook for overriding such settings, or if this is relating to core/a core hook.

I've had a look at the mollom.module code and notice that the message is being set at line 2220

```
form_set_error('mollom', t('Your submission has triggered the profanity filter and will not be accepted until the inappropriate language is removed.'));

```

My question being - is there a simple hook I can use to access this? Perhaps in my preprocessor functions? What is the 'Drupal way' of modifying this message?

If it is of any relevance I am using the Entityform module for my form. Please let me know if you need me to provide additional information.

Thanks for your help in advance.

# Answer
If you look in the settings.php for your site, there should be a template for overriding strings in the interface (anything in the `t()` function).

You would add something like this to the settings.php file:

```
$conf['locale_custom_strings_en'][''] = array(
  'Old string'      => 'New string',
);

```

I haven't used it, but there's a module that makes this easier: String overrides.
> 1 votes

---
Tags: status-messages
---


# Question
Title: Feeds import creating more nodes instead of replacing or updating - Drupal 7
I have Feeds module, but even if I use the correct "guid" and it appears in feeds\_item database table, and I configured it to "Update" (also tried "Replace") existing nodes, and "Delete" non-existing nodes, it will create more nodes, so my database is getting higher and higher Nid numbers. I am using Feeds Tamper submodule. What can be wrong?

# Answer
I figured out the problem: I had not set "Guid" as unique identifier, that is the reason it was duplicating the rows in the database and why it was not replacing or updating the content. The problem now is how to reset the node-\>nid number to a reasonable number after all these deleted entries.
> 0 votes

---
Tags: 7, nodes
---


title: User profile tabs only for current user

text:
# Question
Title: User profile tabs only for current user
On my user profile I have various tabs (view, my bookmarks, translate, ...). the problem ist, those tabs should only be visible for profile owner and not if I visit another profile.

Some of those tabs (bookmarks, submissions) are set via view: user/%/submissions with a menu tab - the permissions here are set. But how do I set permission for those tabs only to the current user?

# Answer
Alter menu and set `'access callback' => 'user_access'` Or if you have custom profile tpl then render tabs like this:

```
global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
  //*******render tabs here*********/
}

```
> 0 votes

---
Tags: users, routes
---


# Question
Title: How to know which name will have my view tpl file?
Currently i have a view with the name:

name (String, 21 characters ) home\_slideshow\_mobile

At the same time this view content is displayed inside a block, which filename (tpl.php) should it have my template file to rewrite the content of this view?

Thanks a lot :)

# Answer
You can have multiple templates for views like :

```
views-view--home-slideshow-mobile.tpl.php

```

if your display is a block, you can write it like this :

```
views-view--home-slideshow-mobile--block.tpl.php

```

then you have templates for views fields :

```
views-view-fields--home-slideshow-mobile.tpl.php

```

Templates for views format (like unformatted for example) :

```
views-view-unformatted--home-slideshow-mobile.tpl.php

```

If you want to alter the template of your block, you can declare a `block.tpl.php` like :

```
block--my-block-module--my-block-machinename.tpl.php

```

You can check all views template in the module views (in like `sites/all/contrib/views/theme/...`). You can copy the template and paste them in your theme and rename it to target your specific view.
> 1 votes

# Answer
https://api.drupal.org/api/views/theme!theme.inc/group/views\_templates/7

See the suggestion for views templates.

If You calling a view block in your custom tpl.php use echo views\_embed\_view('view\_machine\_name', 'block\_1'); You can find out the display name by clicking the tab and check its name in the address bar of your browser: "#views-tab-block\_1" gives you "block\_1'.
> 3 votes

# Answer
In your views, you can get a theme suggestions by clicking **Theme: information** under **Advanced** settings of your view. It gives you suggestion for every field, view style etc.
> 1 votes

---
Tags: views, entities, theming
---


# Question
Title: Migrating a Content Types and its Nodes into another site
I have 2 Drupal 7 sites and I want to migrate data from one into the other. One of the D7 sites has a bunch of content types that the other doesn't have, along with a bunch of nodes associated with it (about 1000+ nodes). It's something I can't migrate manually or else it would take forever.

I know everyone points to the Migrate module to do something like this, but are there other similar methods that are just a streamlined. FYI, I never used the migrate module, as it seems like its more for migrating foreign data from other DB sources into drupal.

I remember there was another module that lets you copy data from another Drupal site, but it has to be the same version. Which one was this called?

Now the question is, what is the fastest approach in migrating data + content types between same version Drupal 7 sites? And what are some other caveats I might need to know?

# Answer
> 1 votes
migrate\_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed

https://www.drupal.org/project/migrate\_d2d

Using this module you can easly migrate your content types to other d7 instance. Here You Just need to give database link form which you want to migrating content types.

# Answer
> 1 votes
Use features module to capture your content types and use node export module to export and import your nodes to your drupal site.

---
Tags: 7, nodes, migrations
---


title: Ctools: stay always within modal window

text:
# Question
Title: Ctools: stay always within modal window
When I load some pages using Ctools modal window, those pages have many another links, submit buttons etc, so when I follow those links, I loose the window. Drupal Overlay has no problems with it.

Is it possible to emulate Drupal Overlay using Ctools?

# Answer
You may can use this module Overlay Paths

This is a simple module that enables administrators to use the built-in Overlay for non-admin pages.

This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.

This module is designed to be used by module developers comfortable with writing code to define which pages should appear in the overlay.
> 1 votes

# Answer
I had a similar issue, and I discovered that the problem was that the other links did not have the **ctools-use-modal** class assigned to them. I got around this by writing a custom jQuery behavior that assigned that class to the appropriate links, in my case to the links in a pager:

```
(function ($) {
  Drupal.behaviors.addCtoolsModalClass = {
    attach: function (context) {
      if (context = '#modalContent') {
        $('#modalContent .pagination li a').addClass('ctools-use-modal');
      }
    }
  }
})(jQuery);

```

This will cause your clicked links to stay within your modal.
> 0 votes

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


# Question
Title: Is there a way to have a customized content add page form depending on who has logged in?
I have a website that operates through administrators. Obviously I have the ability to create content pages through drupal's dashboard, but is there a drupal included way (or module perhaps) that will allow me to limit what another logged in person could see? I know I can change permissions to what is accessible by different groups (i.e. users, partial admins, administrators, etc.). I want to be able to actually change what someone who isn't an admin will see. They shouldn't be able to see the drupal dashboard, for example, or certain sections of the "add/blocks" forms/create new content form.

If there is no option that comes defaul with drupal, firstly that is a huge undersight on drupals part, but is there another way to create this effect? One way I thought was to find drupal's core files that add the page (i.e. "node/add") and hardcode php permissions that check who the logged in user is. If they are admins, allow full priveleges, but if they are another group, then disable certain features of the page.

If this is the case, where can I find the files I'll need to edit? I'm having trouble doing so. It would be the actual form creation page that I'm looking for.

Thank you for any ideas and your time.

# Answer
see this path on your drupal installation :

admin/people/permissions where admin had power to set accessbility of menus,content etc
> 1 votes

---
Tags: users, nodes, blocks
---


title: Migrate module showing error messages

text:
# Question
Title: Migrate module showing error messages
I am importing database from Drupal 6 to Drupal 7 with migrate module.

The progress bar is 5%. The importing data taking a long time.

How could I make it faster? Using Drush? And the error messages below are having problem?

> Processed 263 (0 created, 0 updated, 263 failed, 0 ignored) in 27.8 sec (568/min) - continuing with '1cf4f3dbbFile'
>
> Processed 260 (0 created, 0 updated, 260 failed, 0 ignored) in 27.3 sec (571/min) - continuing with '1cf4f3dbbFile'
>
> Processed 258 (0 created, 0 updated, 258 failed, 0 ignored) in 27.5 sec (564/min) - continuing with '1cf4f3dbbFile'
>
> Processed 253 (0 created, 0 updated, 253 failed, 0 ignored) in 27.5 sec (552/min) - continuing with '1cf4f3dbbFile'

# Answer
I have gone thorugh drupal migration many times and it takes much time if DB is heavy.So Take a breath and keep it going.....once 100% migration is done then you proceed. And also D2D module provides option to select which content types you want to migrate first.In this way you can divide your migration into parts and process will be fast then previous. Good Luck :)
> 1 votes

---
Tags: migrations
---


# Question
Title: How to make the File Attach option available?
When attaching a file to an instance of a content type, there is an option to use ‘file attach’. This is an alternative to uploading a file to the server from one’s local computer. Instead, when creating the content, you click on File attach option and it shows the contents of the folder sites/default/files/file\_attach.

but i don’t remember how to get this option to be available! does anyone know?

this is much more efficient than uploading files from my laptop to the server

thank you,

# Answer
On the edit page of the content type that contains the file field, there is a closed pane labelled 'File Attach Setting'. Inside of that is a checkbox that reads 'File attach from server directory'. It needs to be checked.

Also note, regardless of where you've specified that the file be stored, the module will create a dir named file\_attach. This confused me earlier. I thought it was looking only for files in the default directory ie sites/default/files/file\_attach
> 0 votes

---
Tags: files
---


# Question
Title: give value to form element after select event - value should be catched with JQuery
I'm pretty new with Drupal & JQuery. I post this question because I was not able to find a solution in the net.

I have a select form element to choose a country. This select displays de country names but keeps the country\_code because this is the value to be stored in the DDBB once the form submitted. This select element is linked to ajax because there is a second select field which should show values depending on the selected country.

As soon as the complete address is introduced, JQuery should show a map with the location of the entered address. For that reason I need JQuery to access the country name before the form is submitted.

There is a function that returns the country name for a given country\_code but I do not know how to run that function so that the result can be catched by JQuery. One solution would be keep the country\_name instead of the country\_code (in the select element) but then , into the submit function of the form, I would need a function to get the country code and I would like to avoid this.

```
$country_list=get_country_list();

$form['c_pais'] = array(
'#title' => t('Address - Country'),
'#type' => 'select',
'#options' => $country_list,
'#required' => TRUE,
'#default_value' => $value_country,
'#ajax' => array(
    'event' => 'change',
    'callback' => 'call_region1_select',
    'wrapper' => 'dropdown_region1',
),
);

function get_country_list()
{
    db_set_active('mydb');
    $result=db_select('country_list')
    ->fields('country_list',array('country_id','country_name'))
    ->orderBy('country_name','ASC')
    ->execute();
    $llista_paisos['0']='--- chosse a country ----';
    while($node = $result->fetchAssoc())
    {
        $llista_paisos[$node['country_id']]=$node['country_name'];
    }
    db_set_active();
    //print_r($llista_paisos);
    return $llista_paisos;
}

```

# Answer
Use like this to get form select list element in jQuery.

```
$("#elementId :selected").text() //the text content of the selected option(country name)
$("#elementId").val() //the value of the selected option(country code)

```
> 1 votes

---
Tags: forms, javascript, google-maps
---


# Question
Title: When using drupal_add_js with the 'setting' option, do the set variables apply for all users?
I am trying to find out if the following function will just set the JavaScript variable for that specific user, or if it will switch back and forth between usernames.

```
function my_module_form_submit($form, &$form_state) {
  $username = custom_get_username_function();
  drupal_add_js(array('user' => $username), 'setting');
}

```

# Answer
> 0 votes
Assuming that `custom_get_username_function()` returns a different username for each of the logged-in users, then that code will pass to JavaScript a different and a single username for each user. There could be 4 different logged-in user, but each user gets one username, assuming `custom_get_username_function()` is using the currently logged-in user ID to retrieve the username.

I would rather not add JavaScript code from a form submission handler; if I need to add it, I would add it to the form, or to the page where the users are redirected after they submit the form.

---
Tags: 7, javascript
---


# Question
Title: How to create a view of nodes that are referenced by a node that references the current node?
I have three content types: patient, patient medication, and physician.

Using the Node Reference module, patient medication references the patient content type and the physician content type. How can I create a view with a contextual filter that does the following: When I view a physician node, I want to view all patients that the physician has interacted with. Using the two Node Reference fields in the patient medication content type, how can I display a block of unique patients that the physician has prescribed a medication to?

I basically have it set up like a relational table: Patient \<-- Patient Medication --\> Physician (The arrows represent the node reference)

# Answer
Create a view of content type Physician and set relationship between Patient --- Patient Medication & Patient Medication --- Physician keep both relationship required. Now add all field related with Patient nodes. Here only a block display with patient and Patient Medication.
> 1 votes

# Answer
Let's suppose that that's your Patient Medication structure:

* Title
* Patient (*field\_ref\_patient*) (node reference to Patient content type)
* Physician (*field\_ref\_physician*) (node reference to Physician content type)

So, let's make a view with these settings:

**Fields**

* Patient (*field\_ref\_patient*) (Relation: Patient)

**Relations**

* Physician (*field\_ref\_physician*) (The **reverse** version)

**Contextual Filters**

* Content NID (Default value: Content ID from URL)

This might give you the patients of Patient Medication where Physician is the node that you are viewing

I created an example here: http://dfjfp.ply.st/ (you have 24 hours to check it until it die), go to Structure \> Views \> Physician and give it a node ID, in my example the ID is 3, that id belongs to the Patient Medication that i created.
> 1 votes

---
Tags: views, nodes
---


title: White Screen of Death on Chrome

text:
# Question
Title: White Screen of Death on Chrome
So I'm getting a white screen of death on my newly created Drupal 7 site that was working fine until a minute ago. This is only happening on Chrome, the site works fine on IE and FF.

**On chrome, the console gives the following error message:**

> net::ERR\_INCOMPLETE\_CHUNKED\_ENCODING

**What I've done recently that might be causing this error:**

* I enabled the xmlsitemap module
* I enabled clean url's on my site - maybe this is being caused by something wrong in my .htaccess file?

**My cPanel Error log reports the following, though I'm not sure these are related issues:**

```
[Thu Sep 24 20:10:33 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/sites/default/files/milla.jpg, referer: http://mydomain.fi/?q=node/7/edit&destination=admin/content

[Thu Sep 24 20:09:04 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin, referer: http://mydomain.fi/?q=admin/structure/types/manage/blog-post&destination=admin/config/search/xmlsitemap/settings

[Thu Sep 24 20:00:07 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin

[Thu Sep 24 19:59:59 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin

[Thu Sep 24 19:59:48 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin

```

First real Drupal project that I'm actually hosting somewhere, and now that I just got it up and running it's all coming crashing down :(

# Answer
> 1 votes
Well, I found a solution from here: http://www.zyxware.com/articles/3424/solved-drupal-boost-drupal-site-not-working-in-chrome-and-getting-a-blank-white-screen-when-boost-is-enabled

I added the following line to my .htaccess file:

```
Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"

```

Still occasionally getting the same error message in the console, but at least now the site is loading :)

# Answer
> 0 votes
Try to copy .htaccess file from Drupal's distributive to /home/myuser/public\_html/ (may be .htaccess is absent now)

Try "/home/myuser/public\_html/?q=admin" (may be clean url isn't supported) and then switch off "clean-url" setting

---
Tags: 7, wsod
---


# Question
Title: Am I able to populate an entity form text field with a value from a URL link on an external site
I am trying to pass a url variable from an external 3rd party site and have that variable populate an entity form text field that I have on an entity form on my company's website.

Basically we have a "Request for Information" form on our drupal site that people can come to and fill out. We have some 3rd party companies that have links to our form on their websites. We are trying to be able to track which website the person filling out the form came from so we want to add a url variable to the links on their websites so that when a user clicks on the link on their site that it takes the url variable from that link and places it in a hidden field on our drupal entity form.

Is this at all possible?

# Answer
Yes. Checkout the Field default token module. It lets you substitute tokens in place of a field's default value. In your case you want to use `[current-page:query:var]` for your field's default value. This will let you send someone to the URL http://example.com/my\_entity\_form?var=DEFAULT which will pre populate the field with *DEFAULT*.
> 0 votes

---
Tags: entities, uri
---


# Question
Title: Why aren't the main menu and the secondary menu simply regions?
I noticed that you can put content pretty much anywhere ( where a theme provides regions) using blocks.

This becomes pretty straight forward and makes sense. But then I was trying to find where the "**My account**" and "**Logout**" links came from. And after some searching I found out they are configured in the **Menus -\> Settings** admin page.

Now I read the controversy about the misleading help text for the **Source for the Secondary links**, so this "special" behavior to display secondary links doesn't seem to work anymore in Drupal 7.

**So my question is:** Why are these "regions", treated separately at all ?

Why not have normal main menu and secondary menu regions ?

# Answer
So after much research I found that the main menu and secondary menu settings are there for historical reasons. They had proper functionality in Drupal 5 but its usefulness has declined over the release of newer version ( 6 and 7 ) to the point where modern themes ignore them completely in favor of the powerful regions concept.

The included themes ( as others have mentioned ) have these special "regions" still just because no one cares to remove them.

The original idea was to have an easy way to present sub menu links ( secondary menu ) dependent on the what you select in the main menu.

The modern approach is to have a pop-out sub menu ( like Superfish ) this has made the secondary menu feature obsolete.

So much so in fact, that the functionality is broken and no one fixes it.

In summary, the feature is broken and obsolete. I hope someone removes it from Drupal 8.
> 3 votes

# Answer
I am afraid I can't answer your question. But the Menu Block module might be a solution to your problem.

The module can render menus in a block. It can also render a submenu for the main menu and put it in a separate block.

(If you have child menu items and the parent is the front page, you might need to patch the menu block module. Drupal does not seem to like child menu items of the front page.)
> 1 votes

# Answer
If you make your secondary links "source" the primary links, then secondary links will automatically show the child menu items of the current active menu item / page.

Regarding menus as regions, you may be mistaking theme regions for page content.

Main menu and secondary menus are page content often placed directly within a theme region.

There's nothing to stop you putting the menus in a block wrapper for Admin \> Structure \> Blocks administration, then add to a theme region that way.

It just matters what best suits your site design and layouts.

e.g: put menus in blocks

```
/**
 * Implements hook_block
 * Provide core menus as regular blocks
 */
function example_menus_block_info(){
  $blocks['example_main_menu'] = array(
    'info' => t('example Main menu'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  $blocks['primary_tabs'] = array(
    'info' => 'Local tasks: primary',
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  $blocks['secondary_tabs'] = array(
    'info' => 'Local tasks: secondary',
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  $blocks['primary_secondary_tabs'] = array(
    'info' => 'Local tasks: primary and secondary',
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  return $blocks;
}

/**
 * hook_block_view
 */
function example_menus_block_view($delta = ''){
  $block = array();
  $block['subject'] = ''; // default no title
  switch ($delta) {
    // Our own properly wrapped main menu for panels.
    case 'example_main_menu':
      $main_menu = menu_main_menu();
      $options = array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        );
      $block['content'] = theme('links__system_main_menu', $options);
    break;
  case 'primary_tabs':
    $block['content'] = array(
      '#primary' => menu_primary_local_tasks(),
      '#theme' => 'menu_local_tasks',
    );
    break;
  case 'secondary_tabs':
    $block['content'] = array(
      '#secondary' => menu_secondary_local_tasks(),
      '#theme' => 'menu_local_tasks',
    );
    break;
  case 'primary_secondary_tabs':
    // default, same as core
    $block['content'] = menu_local_tabs();
    break;
  }
  return $block;
}

```

Clear cache and can then add the menus as regular Drupal blocks.
> 1 votes

# Answer
Regions are provided by the Drupal theme.

They are declared in the .info file of theme.

I can suggest you are working with the `bartik` theme.

Secondary menu (like any other menu) can be printed like block or programmatically. You can find `$secondary_menu` variable in the `/themes/bartik/templates/page.tpl.php` file at line 143.

If you want to switch off secondary or main menu visit `/admin/appearance/settings/` page at your Drupal site and uncheck `Main menu` or `Secondary menu`

> Why not have normal main menu and secondary menu regions ?

Some themes (for example Fusion) provide special regions for menu from box. But there is no need in that because you can create you own region wherever you want with few steps:

1. Declare region in theme .info file
2. Print your region in page.tpl.php file of you theme
3. Flush caches

For more details read Theming Guide and Assigning content to regions
> 0 votes

# Answer
If you want your menus in specific regions you can disable the main menu and secondary menu on your theme settings page.

Every menu in Drupal has a block at the block configuration page.

You can then place the menu blocks in any region you desire. I'm not sure why Drupal by default is not setup like this.

You should also be able to disable the menus when creating a new theme by not specifying it as a feature in the themes info file.

See http://drupal.org/node/171205#features
> 0 votes

# Answer
Ray, I suspect the answer to your question is the same as to "Why isn't the logo a region?". Postings such as Display a block next to the Logo show that this causes confusion too.

I suspect that in the original Drupal, themes were much simpler. Drupal's authors could have just provided a content area, plus special-purpose spaces such as those for the logo and the two menus, which were enough to implement their original idea of a Web page. Maybe there were no regions yet, but someone then realised that these special-purpose spaces could be generalised thereto.

Most readers will be familiar with the way that programmers implement something and then realise that various special-purpose features can be generalised. Since StackExchange asks for facts rather than opinions, I searched for stuff about how Drupal developed, but found nothing relevant (though I suppose I could look at the code archives). I see from Evolution of Drupal and the Drupal community - SlideShare that Drupal 4.7.0 already had blocks. And that the first Drupal had only a couple of dozen themes, "all ugly".

By the way, I've been experimenting with Devsaran's Venture theme, and that appears to depend on these abnormal non-regions. So they're still used in at least one modern theme. I described my experiences with it at Why can themes (Venture, but perhaps others too) display a main menu even when the main-menu block is disabled?, where I also referred to your answer to your question.
> 0 votes

---
Tags: 7, blocks, theming
---


# Question
Title: Setting default image style to 'original image' in formatter
In a custom formatter that I'm writing, I have a problem with default\_value for an image style.

```
function MYMODULE_field_formatter_info() {
  return array(
    'MYMODULE_formatter' => array(
      'label' => t('My Custom Formatter'),
      'field types' => array('image'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'settings' => array(
        'trigger_image_style' => '',
      )
    ),
  );
}

function MYMODULE_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array();

  $image_styles = image_style_options(FALSE);
  $element['trigger_image_style'] =  array(
    '#type' => 'select',
    '#title' => t('Trigger image style:'),
    '#description' => t('Image style to be used for trigger'),
    '#default_value' => $settings['trigger_image_style'],
    '#options' => $image_styles,
  );

  return $element;
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  $html = "";
  $settings = $display['settings'];

  // ensure deaults?
  if (!isset($settings['trigger_image_style'])) $settings['trigger_image_style'] = '';
  //.....
}

```

Seems that Drupal will return incorrect path:

```
image_style_url($settings['trigger_image_style'], $item['uri']);

```

until I explicitly set a style of my choice. The incorrect path will have double slash, as in:

```
http://example.com/sites/default/files/styles//public/trigger-images/test1.jpg

```

I thought that empty string simply means 'use original image'... How should I tell Drupal to use original image if the style is not set or is an empty string?

# Answer
It is have simple solution when you want specified `image_style` use something like

```
  image_style_url('850x450',$file->uri);

```

and when you don't want use any image style and want use origin image use

```
 file_create_url($file->uri);

```
> 1 votes

---
Tags: 7, entities, media
---


# Question
Title: How to put a token in field Simplenews -> Subscribtion block -> block message
I want to add a token in a field which is used when the simplenews module is installed and configured. There is then a block available for each newsletter. In this block the user can fill in his email and push the subsribe button.

I want to display a token in this field:

* Block \> Simplenews subscribption block \> block message.

(the block title is supporting tokens, but the block message not)

How to do this?

# Answer
It's likely there's no off-the-shelf solution here. The block message field is a variable in the Simplenews module. It's not possible to make variables dynamic; there's no hook to override variable values.

In order to make something like this happen, you'd have to use a combination `hook_form_alter()` to change the block setting form & `hook_block_view_alter()` to alter the output of the Simplenews block.
> 0 votes

---
Tags: tokens
---


# Question
Title: How to use Display Suite to trim whitespace from a field
I have created a new content type, Plants, for my web site. One of the fields, scientific name, requires special formatting. Usually it is all italics, but sometimes a mixture of italics and non-italics such as *Abelia x grandiflora* 'Kaleidoscope'.

To make this work I defined the field as long text. I have tried several combinations of formats and field templates using Display Suite. The only one that seems to preserve the proper italics is Format Default and Field Template Drupal default. This preservers the proper italics, but results in an empty blank line that looks pretty crummy. See image.

Generated HTML according to Firebug:

```
<section class="field field-name-field-scientific-name field-type-text-long field-label-inline clearfix view-mode-full"><h2 class="field-label">Scientific name: </h2><div class="field-items"><div class="field-item even"><p><em>Abelia x grandiflora</em> 'Kaleidoscope'</p>

```

How can I eliminate the blank line or trim the white space at the end?

# Answer
Sorry for the digression — but semantic markup does matter. This articles speaks well to what it is: https://boagworld.com/dev/semantic-code-what-why-how/

Your input filter (or, less possibly, your rich text editor) is adding the paragraph tag. Check out the input filter you're using for this field. If this filter has "`Convert line breaks into HTML (i.e. <br> and <p>)`" enabled, found here: `admin/config/content/formats/<inputfiltername>` — this could be adding paragraph tags. Keep in mind changing this will impact how all your fields that use this input filter are rendered. You can always create an additional input filter to suite your needs.
> 1 votes

---
Tags: display-suite
---


# Question
Title: add text before block is being displayed in region content
I have a block that I want to display in my *Content* region which works fine but the block is always fix aligned in the top left corner (`float: left` property). How can I set it so, that my content displays above the block in my region?

# Answer
Assign this css code to one class of your block ( or the #id )

```
.your-block-class-name:before {
  content: "";
  display: table;
}

```
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: facets not showing all the options drupal commerce
Go to this page if you take a look to the facets at the sidebar you will notice that they are not displaying all the available options.

When I search 1 word at the search bar for example "tract" then the facets work as expected, but when I use 1 or more words the facets does not display all the options... Does any body have had this issue before with Facets of Drupal commerce?

Any suggestions?

# Answer
you should probably set the filter in the view like this
> 1 votes

---
Tags: 7, commerce, search
---


# Question
Title: I'm getting a 404 on a user/reset/%/%/% path
I'm getting a 404 on a user/reset/%/%/% path. The cached router item looks good but the page is still not found.

```
Array
(
[title] => Reset password
[page callback] => drupal_get_form
[page arguments] => Array
    (
        [0] => user_pass_reset
        [1] => 2
        [2] => 3
        [3] => 4
    )

[access callback] => 1
[type] => 0
[file] => user.pages.inc
[module] => user
[_load_functions] => Array
    (
        [2] =>
        [3] =>
        [4] =>
    )

[to_arg_functions] =>
[weight] => 0
[_number_parts] => 5
[_parts] => Array
    (
        [0] => user
        [1] => reset
        [2] => %
        [3] => %
        [4] => %
    )

[_fit] => 24
[_visible] =>
[_tab] =>
[tab_parent] =>
[tab_root] => user/reset/%/%/%
[menu_name] => user-menu
[delivery callback] =>
[theme callback] =>
[theme arguments] => Array
    (
    )

[load_functions] => a:3:{i:2;N;i:3;N;i:4;N;}
[access arguments] => Array
    (
    )

[title arguments] => Array
    (
    )

[title callback] => t
[description] =>
[position] =>
[context] => 0
[path] => user/reset/%/%/%
[file path] =>
[include file] => modules/user/user.pages.inc
)

```

I've used drush fn-hook menu\_alter to see if anything is changing this path but I would figure that end up in the cached router entry above. Any help with this would be much appreciated.

# Answer
This was being caused by a third party custom module, funny enough *not* in hook\_menu\_alter.
> 0 votes

---
Tags: users
---


# Question
Title: Override a node page of specific content with views page
I want to create a views for overriding the node page for specific content. For example, when I click the link of a node in a list page, by default , it will go to the node page (e.g node/1), but I want to display a views page, so I can customize the views by views rather than customize the display in content type.

How can I do that?

# Answer
Create a views of content, set path of it to something like **mynode/%**(or what you want(yourpath/%)), add contextual filter **Nid**, set default value **Get Content ID from Url**,and then customize views fields with what you want.
This link can help you about how to pass Nid to views
> 0 votes

---
Tags: 7, views, nodes
---


title: Load only the submenus under given menu

text:
# Question
Title: Load only the submenus under given menu
How to get ONLY the list of Submenus under given menu programmatically. Say, the `given menu` means a `main-menu` item. I tried with `menu_tree_page_data`. But not sure if I can use it to select only the required menus.

The scenario is, I have active menu loaded using `menu_get_active_trail()`. So I have all the details of the main menu. Now with those details I need to get the submenus under that.

# Answer
> 1 votes
```
$main_menu_tree = menu_tree('main-menu');
foreach ($main_menu_tree as $key => &$main_menu_item) {
    if (is_numeric($key)) {
        $main_menu_item['#below']['#theme_wrappers'][0] = 'some_other_theme_wrapper';
    }
}
print drupal_render($main_menu_tree);

```

If you have array of main menu active trails you can use foreach to loop through the array print menus and their sub menus.

# Answer
> 0 votes
Try this code and it should work. I tested it now and it works by fetching sub menus.

```
$menuItems = menu_tree_page_data('main-menu');
foreach($menuItems as $key => $value) {
    foreach($value as $menuKey => $submenus) {
        if(isset($submenus['link_title'])) {
            print $submenus['link_title'];
        }
    }
}

```

# Answer
> 0 votes
if you just a specified Menuitem subItems just put a if between 2 foreach

```
$menuItems = menu_tree_page_data('main-menu');
$sub=array();
foreach($menuItems as $key => $value) {
if($menuKey=='yourmenuitemkey'){
    foreach($value as $menuKey => $submenus) {
        if(isset($submenus['link_title'])) {
            $sub[]=$submenus['link_title'];
        }
      }
    }
  }

```

---
Tags: 7
---


# Question
Title: Redirect user page to user/edit and user/login
I want to do page redirect when user access **/user** page. When user anonymous user access the /user it should redirect to user/login page and when logged in user access the /user page it should redirect to user/%/edit page.

I have tried the following the code

```
function my_user_menu_alter(&$items){
   $items['user']['page callback'] = 'my_user_page_redirect';
}
function my_user_page_redirect() {
  global $user;
  if (user_is_logged_in()) {
  drupal_goto('user/'.$user->uid.'/edit');
}
 else {
   drupal_goto('user/login');
 }

}

```

For logged in user it redirects to user/%/edit page. For anonymous user it displays webpage redirect error

How can I do this. Thank You

# Answer
> 1 votes
You can do it without `hook_menu_alter`, achieve it in `hook_init`, try something like (don't forget changes in hook\_init need clear the cache to getting applied)

```
function yourmodule_init(){
   if(current_path()=="user"){
   global $user;
     if (user_is_logged_in()) {
      drupal_goto('user/'.$user->uid.'/edit');
    }
   else {
      drupal_goto('user/login');
   }
}
}

```

---
Tags: routes, users, redirection
---


# Question
Title: Display images filed in views slideshow in node content page
Are there any ways to format/replace the images display in a node(e./g node/1)? I add a image field for my content type which allow multiple images, i want to display it in gallery/thumbnail/jcarousel/slideshow....

I know how to make a viewslideshow in a view, but it seems no way to do the same thing in node display (e./g node/1)

# Answer
1. Create slideshow view block.
2. In view configuration, provide contextual filter of field "Content: Nid" and then provide default value "Content ID from URL".
3. Now place this block into Content region.
> 0 votes

# Answer
if your using a module which has a field formatter, like owlcarousel, you can set the field to be rendered as slide show in the field UI
> 0 votes

---
Tags: nodes, media, javascript
---


# Question
Title: Adding Taxonomy terms programmatically with specific tid?
I would like to add a term to a vocabulary specifing the **tid**, already tried with Taxonomy CSV import/export and Taxonomy import/export via XML modules but both create terms with a new tid.

I even tried programmatically with *taxonomy\_term\_save()* but if i set the **tid** it just looks for a term with that ID.

I need to do this because then i'll import a lot of nodes, and all of them already have a relation with a term.

Any other way to do this?

# Answer
> 0 votes
**tid** will be assigned to the terms automatically by drupal. My suggestion is first create the terms then you can use **taxonomy\_get\_term\_by\_name** function to find the term and then map it to the respective node while importing.

# Answer
> 0 votes
you can add a custom number field to you taxonomy vocabulary, and save this reference id there for later use.

---
Tags: taxonomy-terms
---


title: Alter menu link for taxonomy link

text:
# Question
Title: Alter menu link for taxonomy link
I've path alias and taxonomy menu. Now menu displays taxonomy link as **vocabulary\_name/term\_name.**

For example, my vocabulary name is 'category'. I want to change into 'article'. I've to only for this situation. I've used path alias. Unfortunately my view link looks like same.

I've tired hook\_menu\_alter() and hook\_menu\_link\_alter(). But there is no luck. I need your suggestions.

# Answer
> 0 votes
Go to the path alias, set your path to what you want, then from `admin/config/search/path/delete_bulk` delete all taxonomy path , then from `admin/config/search/path/udate_bulk` rebuild them.(this is is pathauto mdoule)if your menu link not worked rebuild them ( with taxonomy menu module)

---
Tags: routes
---


title: Restrict concurrent content edit

text:
# Question
Title: Restrict concurrent content edit
I want to **restrict concurrent edit** by the users.

If **user A** is editing a content then **user B** should not be able to edit the content at the same time. That content should be visible, just not editable.

I am unable to find any module that provides this feature for Drupal 7.

Is there any module, or how can I achieve this programmatically?

# Answer
> 2 votes
This is old question but there is a module for restrict concurrent editing: Content lock

> Block concurrent editing: When a user is editing a node, any other user that attempts to edit the same node will be blocked from doing so, and notified that the content is already being edited.

# Answer
> 1 votes
There is a module for that. Try the Conflict module

> This module allows parallel editing of nodes with field-level conflict detection and a trick to prevent accidental overwriting of fields when they are changed by another session while a node is being edited.
>
> This behavior is useful for things like issue queues where multiple people might be following up to an issue simultaneously.
>
> It works by hashing the field data and comparing these hashes. This is done so we can generically do a 3 way comparison between the original node, the node as edited by us, and the node as edited by others.

---
Tags: 7, nodes
---


# Question
Title: Displaying the parent term first in Views
I have managed to create to organize my content using the Taxonomy module, it is 2 levels deep.

```
Level 1
    > Level 1-a
        > Level 1-a-i
    > Level 1-b
        > Level 1-b-ii
Level 2
    > Level 2-a
        > Level 2-a-i
Level 3
    > Level 3-a
        > Level 3-a-i

```

I display this using the Views module. But the problem I am facing is that the view displays all terms,

```
Level 1
Level 1-a
Level 1-a-i
Level 1-b
Level 1-b-ii

```

What I am trying to achieve on this view is something like this

```
Level 1
Level 2
Level 3

```

And then when the user clicks a level it will display child, until they reach the deepest level of the taxonomy

```
Level 1-a
Level 1-b

```

and then for example selecting **Level 1-a**

```
Level 1-a-i
Level 1-a-ii
Level 1-a-iii

```

# Answer
The Views Tree module might be what you're after.
> 0 votes

---
Tags: views, taxonomy-terms
---


# Question
Title: How do you disable strict errors for PHP 5.4 & 5.5 in Drupal 7 via the settings.php file?
Currently I disabled the error messages via UI under Administration \> Developement \> Logging & Errors:

But I want to be able to do this via the settings.php file. How can that be done?

# Answer
> 3 votes
And the Drupal way:

Add this line in settings.php

```
$conf['error_level'] = 0; // 0: None, 1: Errors and warnings, 2: All messages

```

You can set any persistent variable this way. You can get the variable names simply using Firebug or any browser's developer tool and check the `name` attribute of the input field in the administration form. Which in you case the Logging & Errors page. If you look at the source code, the radio buttons have the `name` attribute `error_level` and each radio button has a `value` attribute. Simply set this value to the variable in you settings.php using `$conf` array.

You can also set any variable using `variable_set()` function in any custom module, in an update script for example.

Or using Drush:

```
drush vset error_level 0

```

# Answer
> 2 votes
You can use this code on your settings.php file.

```
error_reporting(E_ALL ^ E_STRICT);

```

or

```
error_reporting(E_ALL & ~E_STRICT);

```

Note: E\_STRICT has only been part of E\_ALL since php 5.4

http://php.net/manual/function.error-reporting.php

# Answer
> 1 votes
Check if adding the following at the begging of the settings.php works:

```
ini_set('error_reporting', 30711);

```

that will affect the PHP settings for your site.

# Answer
> 0 votes
Drupal seems to override the setting.php

The best answers I found so far are the ones in that thread: Remove the strict warnings from being shown

Either you go hide the warnings in drupal interface:
*This will hide everything, but occuring problems will still be logged, and hiding might be a good solution for a production environment anyway*.

Or you directly modify the Drupal error handler:
*This is the solution I chose, which is more focused on the need. The only drawback I see is that the operation might have to be done again when updating drupal version.*

btw, avoid using lines like `ini_set('error_reporting', 30711);`
error and warning values use mask for readibility, so, you'd better use something like `(E_ALL & ~E_STRICT & ~E_WARNING)` than any crude number value

---
Tags: 7
---


# Question
Title: How do I create content links to a group node without using panels?
I am new to Organic Groups and I am following the videos at https://modulesunraveled.com/organic-groups-7x-2x . Video 4 demonstrates how to insert a create content link on a group page using Panels and I am able to replicate this, when following the video.

However, I would prefer not to use Panels and can not display a create content link in a basic layout (without Panels or Display Suite).

Various posts say that having entityreference\_prepopulate module is key, but as far as I can tell, I have this configured properly (otherwise my panel wouldn't work).

I am expecting to see a display formatter on the content type or perhaps a module generated block, but nothing seems apparent.

What am I missing?

# Answer
> 0 votes
Answering my own question.

Seems I needs to use install OG Extras - https://www.drupal.org/project/og\_extras

---
Tags: organic-groups
---


# Question
Title: Display root terms based on child in a view
I've a city vocabulary (see example below) which I import from 3-th party service. Each city may be spelled differently (either with wrong spelling or with special characters). In my example let's assume that TEST is a different variation of Oslo city.

These cities are already used in Content Type 'Person'. I built a view that display Persons with a category City. Everything works well and my view looks like this:

Now I need to substitute/replace TEST with Oslo (as it is different spelling of Oslo city). On a view I expect to not see TEST and Oslo must get +1 as a counter.

> Oslo (34)

**UPDATE** Here are my settings for the view.

What should I do in order to achieve that? Thanks.

# Answer
Try this:

You can use relationship, and add "Taxonomy term: Parent term" field relation in it. Now make relationship with city field. It will give root term name based on child term name.

I have recently done this, it works.

Hope it will works for you.
> 2 votes

---
Tags: views, taxonomy-terms
---


title: install modules with custom module

text:
# Question
Title: install modules with custom module
Is there any way to install all modules a in specific folder with a custom module? I need to install my custom module and have all modules in a specific folder installed automatically.

# Answer
If you define the modules in the subdirectory as dependencies of your main module, then they'll be enabled once your "controller" module is.

i.e.

```
name = Really Neat Widget
description = Provides a really neat widget for your site's sidebar.
core = 7.x
package = Views
dependencies[] = MODULE_ONE
dependencies[] = MODULE_TWO

```

Source

Alternatively, you could take a look at the Master module.
> 2 votes

# Answer
If the modules you need to install are in a well know list, you can just add them as dependencies of your module. They will not get automatically installed, if Drush is not used to enable your custom module, but your custom module could be installed only if the administrator user installs and enables the dependencies.

If you need to programmatically install modules found in a folder, and you don't want to make assumptions about which modules are (maybe you don't control which modules are in that folder), you need to use `file_scan_directory()` and `module_enable()`. With the latter function:

* You don't need to check the modules are already enabled, since the function does it

```
foreach ($module_list as $module) {
  // Only process modules that are not already enabled.
  $existing = db_query("SELECT status FROM {system} WHERE type = :type AND name = :name", array(
    ':type' => 'module',
    ':name' => $module,
  ))->fetchObject();
  if ($existing->status == 0) {
    // Load the module's code.
    drupal_load('module', $module);
    module_load_install($module);

    // ...
  }

  // ...
}

```
* You don't need to invoke `hook_install()`

```
// Now install the module if necessary.
if (drupal_get_installed_schema_version($module, TRUE) == SCHEMA_UNINSTALLED) {
  drupal_install_schema($module);

  // Set the schema version to the number of the last update provided
  // by the module.
  $versions = drupal_get_schema_versions($module);
  $version = $versions ? max($versions) : SCHEMA_INSTALLED;

  // If the module has no current updates, but has some that were
  // previously removed, set the version to the value of
  // hook_update_last_removed().
  if ($last_removed = module_invoke($module, 'update_last_removed')) {
    $version = max($version, $last_removed);
  }
  drupal_set_installed_schema_version($module, $version);
  // Allow the module to perform install tasks.
  module_invoke($module, 'install');
  // Record the fact that it was installed.
  $modules_installed[] = $module;
  watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO);
}

```

Keep in mind Drupal will install/enable the first module it finds matching the name; it doesn't mean it will be the module in that folder.

If then you need to be sure the modules in that folder are already downloaded, and you are creating a new site, I would rather create an installation profile, which allows you to declare its dependencies with a Drush Make file, and use it to create the new site.
> 2 votes

# Answer
You can use `modulename_install()` and then module\_enable()

It may be usefull to check enabled modules with module\_list()
> 0 votes

# Answer
You are most likely looking for installation profiles and distributions. From the info page:

> Installation profiles combine core Drupal, contributed modules, themes, and pre-defined configuration into one download. Installation profiles provide specific site features and functions for a specific purpose or type of site. They make it possible to quickly set up a complex, use-specific site in fewer steps than if installing and configuring elements individually.
> 0 votes

---
Tags: 7
---


title: Views charts pager doesn't match parent

text:
# Question
Title: Views charts pager doesn't match parent
I have a view with a table that has a pager to show 5 items at a time:

```
Items to display:Display a specified number of items | 5 items

```

In another display I have a chart that is attached to the table. How can I set the view so that the chart display the same content that is in the table? There is the `Inherit pager` option that I set to `Yes` but the chart always show the firts 5 items and not the 5 items showed in the table.

You can see in the image below that the chart is in fact limited to 5 (as the table) but the dates (x-axis) don't match.

Am I missing something here? Or is this a limitation?

# Answer
Maybe there is another solution for this problem but after trying many things I noticed that one solution is to disable the sorting of the "Run Date and Time" field. This way, the table is always sorted in the same way for that field but the pager is respected.
> 0 votes

---
Tags: views, paging, charts
---


# Question
Title: Search API view - Displaying items that doesn't meet Facets criteria
I have a search api view where I display houses with number of bedrooms in each of the house, and I'm using facet api to create filter so that for example if I would click on "2" it would only display houses that have only 2 bedrooms in it.

But I would also like to below this view (or as part of this view) display other results that doesn't meet the criteria (and that are filtered out by facets) and I'm really stuck with how this can be done.

In addition I only want it to happen with "Bedrooms" but not with "Bathrooms".

I hope someone can help I'm really stuck with this issue!

\** small update 26.09.2015 \**

I'm trying to achieve that now by combining two views together using views attachment and having "views negate" filter to work on values provided by exposed filter.. so far no luck.

And views attachments are being displayed UNDER pagination, instead of after the normal results which is not what I ideally would want to have.

After that I'm planning to change the normal exposed filter into BEF with links and style them as facets...

# Answer
> -1 votes
Might be wrong place, but my query is related to retrieving improper data. I am using facet to filter the result its working fine. But if I use solr slop to retrive data all the record are proper and then try to filter the record using another facet Sector then the result displayed in location facet is improper. e.g

Initially search for England, it retrieves all data of England record include location, Sector Cont type data.Location details are displayed in location facet block. But when I do deep filter using Sector facet(sector records are within location searched I.e. England) I get records from Scotland location too.. Scotland location is listed in the location facet along with England. Not knowing what is going wrong afteer using Solr slop as without it all the data retrieved is proper.

---
Tags: views, search
---


title: ctools with panels colon issue IIS

text:
# Question
Title: ctools with panels colon issue IIS
When using **Panels** module I have noticed that one of the ajax calls is creating an url with colon inside :

For Example :

```
dev-www.redbusbingo.com/panels/ajax/editor/select-content/panel_c

%3A = :

```

The problem is that iis Dont know how to Handle ":/" , or to say this colon in the end of string

This case break the site with error 500 .

```
500 Error Case : "dev-www.redbusbingo.com/panels/ajax/editor/select-content/panel_c" ( Colon at the end Before "/")

```

Good Case :

```
 "dev-www.redbusbingo.com/panels/ajax/editor/select-content/panel_c" ( NO colon at the end Before the "/")

```

Is there any way to replace this colons ?

Just to say i have reported this bug to Microsoft and they said that this a security issue and because of that they will not allow colons in the url .

Currently i can't work on my site because of this error and my iis , Please assist me with this .

Thanks Haniel

# Answer
I've finally succeded in correcting this bug, by modifying directly the Panels module. I'll publish a patch on panel's forum on drupal's site. Here's the solution :

In the file /sites/all/modules/panels/plugins/display\_renderers/panels\_renderer\_editor.class.php, you have to change get\_url() function (line 505), replace this:

```
 $url = 'panels/ajax/' . $this->plugin['name'] . '/' . $command . '/' . $this->display->cache_key;

```

by this

```
 if (variable_get('clean_url', FALSE))
  $url = '?q=';

$url .= 'panels/ajax/' . $this->plugin['name'] . '/' . $command . '/' . $this->display->cache_key;

```

As you maybe know the problem is caused by cleans Url, so it works without the fix if u disable it. But if you want to keep cleans url, apply the fix, it forces all ajax requests to be without cleans urls

PS: Thank you to MPD♦ who deleted my previous answer where i put a link to azure forum which was a possible way to solve the problem.
> 1 votes

---
Tags: ajax, panels, chaos-tool-suite
---


title: Disable cache for specific blocks

text:
# Question
Title: Disable cache for specific blocks
I would like to let pages continue to benefit from Drupal 8 caching mechanism for anonymous users, except for a specific blocks which should update on every page refresh knowing that they are generated from Views.

Is it technically possible? How?

# Answer
What does that views block show?

D8 has cache tags and contexts that will automatically invalidate the block if something changes.

So if you have a list of nodes, every time a node is added or updated, that block will be updated, but until then, the cached version is used. Which is much better than rebuilding on every page.

It also works with the page cache, those pages will be updated automatically as well.

Many, many things *just work* with caching out of the box, without the need for any manual configurations.

Edit (responding to comment):

Random with the random sort plugin? That should automatically mark that block as non-cacheable. That however does not affect the page cache module. There is now a new smartcache/dynamic page cache module but it will only be in the next beta (or RC!). That will eventually allow to cache the rest of the page and just build that part.

But a case like this is probably best implemented by using some javascript. If there only a few nodes you could display them all, hidden by default and just randomly make one of them visible. Or request a URL with javascript that returns a random Ad or even better visit a random of N URL's that each returns an ad (e.g. by returning a list of URL's and then picking one of them. You could even do that directly for the image URL.
> 1 votes

# Answer
If this is a custom block, then you can use the Cache API, and set the cache max age to 0, eg

```
$build = [
 // ...
 '#cache' => [
   'max-age' => 0,
 ],
];

```

If it is an existing block, then you can alter it to add this into the render array.
> 11 votes

---
Tags: views, blocks, 8, caching, users
---


# Question
Title: Show block on specific views search result
My view exposed search results path looks like this:

www.xyz.com/?field\_port\_tid=5971&field\_length\_value=&field\_length\_value\_1=&field\_cabins\_value=&field\_cabins\_value\_1=&field\_price\_week\_range\_value=&field\_price\_week\_range\_to\_value=

I would like a block to show only if the path has specific taxonomy term in it (in this case tid=5971).

# Answer
If you have the **PHP filter** (not advised but still popular) module enabled you can use the *Pages on which this PHP code returns TRUE (experts only)* option for block visibility with the following code.

```
<?php return (isset($_GET['tid']) && $_GET['tid'] == 5971); ?>

```
> 1 votes

---
Tags: blocks
---


# Question
Title: Disable email to admin on new user registration
When a new user registers, an email is sent to the admins. I can't work out how to turn this off. There doesn't seem anywhere where I can alter it. In Home » Administration » Configuration » People » Account settings

Who can register accounts? "Visitors" is checked (not "Visitors, but administrator approval is required")

# Answer
> 0 votes
There are a module for control this emails sendings: MailControl

---
Tags: users, emails
---


# Question
Title: How to grant permission directly to a user other than a role?
Our client frequently need to grant arbitrary permissions to arbitrary users. It's very boring and fault-prone for our client to create new roles, assign users to roles and then set role permissions.
The module *user permissions* can grant permissions directly to a user, but the grantee must have the powerful permission "administer permissions", which is not what I want.

# Answer
> 1 votes
Use the user permissions module. Contrary to your objections to using this module, it is **not** the **grantee** who needs the "administer permissions", but the **grantor**

# Answer
> -1 votes
Create role:

```
if (!user_role_load_by_name('new_role')) {
  $role = new stdClass();
  $role->name = 'new_role';
  user_role_save($role);
}

```

Add Permissions:

```
$new_role = user_role_load_by_name('new_role');
$values[] = array(
  'rid' => $new_role->rid,
  'permission' => 'create article content',
  'module' => 'modulename'
);
$query = db_insert('role_permission')->fields(
  array(
    'rid',
    'permission',
    'module'
  ));
foreach ($values as $record) {
  $query->values($record);
}
$query->execute();

```

---
Tags: users
---


# Question
Title: Adding an external image to a views output
I am trying to alter the output of a view with a tpl.php file. My goal is to insert an image immediately after another image in the view. This should only happen for 1 result. That is to say, if the value of my array image is apple, I want to also display another image of apples. So if I have a view that returns images of fruits:

* Grapes
* pears
* apple
* peaches
* bananas

I want to display these images:

* Grapes
* pears
* apple apple1
* peaches
* bananas

I'm open to ideas, so far I've been trying to solve the issue programatically by creating a custom .tpl file for the view, but if a cleaner solution exists I'd be willing to give it a try.

# Answer
I've come to the conclusion that I believe the best/easiest way to do this is by adding another field to my content type, and inserting the associated image in that field. Even though I've created a field in that content type that is only required for one piece of content.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Core updates and module updates: Does order matter?
I inherited a badly out-of-date Drupal 6 multi-site instance. There is only the production instance. (yeah, that gives me a warm-fuzzy!)

Many modules are several versions behind and the core is several versions behind.

Does the order in which I perform the updates matter? I'm thinking update core first, then update the modules, but I'm just not sure.

Anyone care to advise?

# Answer
> 1 votes
Order does matter.

Sadly, it's hard to tell exactly *how* it will matter in your situation. **If you can, make a dev copy of this site** and experiment on it. I would either go with core-first or with all at once. But that's my intuition, and actual tests on a copy of actual site matters much more.

Usually it's OK to jump all versions in-between the one you have and most recent one. For modules, sometimes, rarely, it's good to use most-recent minor version and don't install next major version at all (if both are maintained), or install most-recent minor and then update major. Sadly, it's different for each module, so fastest thing would be to update everything straight to the recent version, and see if / what broke. Of course, this is only feasible on a dev copy, not production.

---
Tags: 6, updating
---


# Question
Title: How often is settings.php called? And is $user available to it?
I'm thinking about adding some handling to the `settings.php` code, to set the `ini_set('session.gc_maxlifetime', 2880);` value based on the role of the logged it (or not logged in) user.

i.e. for admin role, moderator role, I'd set a real long value so as to basically not ever get logged out due to idling too long, while writing a long article, or whatever, while for "lesser" roles, like a regular member, they'll get a regular, shorter `maxlifetime`.

**My 2 questions:**

**1)** Is the `Global $user` var available within `settings.php`, so I can check it for the user's roles?

**2)** How often does it get called? Only once during initial site load? Or every time a user loads a page? I don't want to be (re)setting the value every time a page loads.

# Answer
> 2 votes
The settings.php file is included on the first bootstrap phase (`DRUPAL_BOOTSTRAP_CONFIGURATION`), while the global `$user` is initialized on `DRUPAL_BOOTSTRAP_PAGE_CACHE` or `DRUPAL_BOOTSTRAP_SESSION`, which are both later bootstrap phases.

The settings.php file is included each times Drupal bootstraps, which means every time Drupal serves a page, including the ones served from its cache. As such, the settings.php file can use plain PHP functions or a restrict set of Drupal functions; in both the cases, the code cannot access the user variable. It is not even possible to initialize it using the database, since the database connection is initialized after the file has been included. (The obvious reason is that the database settings are contained in the settings.php file.)

### Reference

---
Tags: configuration
---


# Question
Title: Drupal 7 db_query how to return regular array from varchar field
I am attempting to combine two arrays - one is stored in the database in a varchar field. Something like this.

```
["0","1","2","68","69","95","96","97","98","99","100"]

```

I am bringing in a similar array that comes from the front end.

```
["0","1","2","45","66","95","97","98","99","100"]

```

I need merging the two and remove duplicates.

```
   //merge post data and stored data
      $merge = array_merge($arr1, $arr2);
      //remove duplicates
      $merge = array_unique($merge);

```

My problem is that when retrieving the `varchar` field, I am not getting a normal array but an associative. Here is my code.

```
$arr2 = db_query('SELECT stats FROM {my_db} WHERE uid = :uid AND nid = :nid', array(':uid' => $usid, ':nid' => $noid))->fetchAll(PDO::FETCH_ASSOC);

```

I need this to return a regular array, not an associative to combine the two and remove duplicates. Does anyone know how?

When I do a `print_r()` on `$arr2` it returns the following.

```
Array
(
    [0] => Array
        (
            [stats] => ["0","1","2","68","69","95","96","97","98","99","100"]
        )

)

```

I can't seem to be able to merge it and pass it to `array_unique()` on.

# Answer
https://www.drupal.org/node/1251174

```
$arr2 = db_query('SELECT stats FROM {my_db} WHERE uid = :uid AND nid = :nid', array(':uid' => $usid, ':nid' => $noid))->fetchCol();

print_r($arr2[0]);

```
> 0 votes

---
Tags: database
---


title: What is content pane and embed?

text:
# Question
Title: What is content pane and embed?
When you click the *Add* tab in a view, you have many choices including *Content pane and embed*. What are those?

# Answer
Many modules provide add-on functionality for Views. Chaos tools suite (ctools) provides the Content Pane display, which is a way to embed views in other areas of your site using advanced context passing. The views are not treated as pages and you can therefore embed them multiple times, just as you can with blocks, but with blocks your context handling is very limited.

For one good example of where and how to use it you may look at Panels module.

Some tutorial here:

Drupal Tutorial - Panels #6 : Related Content With Views Content Panes | WDTutorials.com
> 1 votes

---
Tags: views
---


# Question
Title: How to hide "Counter" and "Date" on certain page/node?
How do I hide the "Count content views" of a certain page/node?

I want to hide the numbers of reads along with the date the page was updated without effecting other pages on the site.

# Answer
You need to interact with the theming layer (template.php in theme)

As you want to alter an element within a node, you may use function template\_preprocess\_node(&$variables) to alter, remove or disable that element. You will need to do a conditional test first ($variables\['node'\]-\>nid) and check $node-\>nid against the nid of your specific node page. You can then look for the element within $node.

You may also just use Drupal 7 Template (Theme Hook) Suggestions, if the element you wish to hide is a standalone element (ie not embedded in a larger render array), in which case you will copy over the base theme's node template and just comment out/alter the bit in question - for node it is node--\[type|nodeid\].tpl.php.

When working in the theme layer remember that your theme always has the last say so you can safely make alterations knowing that you cannot cause problems for any other modules or base themes in the process.
> 0 votes

---
Tags: nodes
---


title: Categorize without taxonomy

text:
# Question
Title: Categorize without taxonomy
How can we categorize things on our site without using taxonomy. I have learned Taxonomy but want to know how to categorize things without Taxonomy. Can anyone help me Please.

# Answer
> 0 votes
You could always add "List" field type to your custom content type. By default you could choose between lists of Text, Integer and Float. While configuring you could choose whether or not it will be checkboxes, radio buttons or select lists. Later in Views you could filter content with use of these fields.

It's in Drupal core, no additional modules (except of Views of course)

---
Tags: taxonomy-terms
---


# Question
Title: Redirecting Pages from Standard Node page to views page
How can I redirect all of my nodes created by a content type to a views page with a different url? For example, I created content types for publications and then have pathalias creating a url for a created node:

**publications/form-one**

I am then using views to reformat that look and feel of the node fields and also add in some other data from other content types via Relationships and Context. In the end my new url is:

**publications/001**

Now, my search results will find the **/form-one** url and bring the user to that page, but I'd like to only return the user to the **/001** page that I have compiled in views with the additional data.

Some thoughts I have had, but not sure how to implement:

* If I take all the url alias away from publications and reset it back to node/nid and then .... not sure here? Some Context Redirect?
* Redirects? I have a TON of pages.
* hook\_node\_view()?

Thanks for any thoughts and please ask for clarification if needed.

# Answer
Chaos tool suite (ctools) has a sub-module called Page Manager.

> Page manager is a critical tool for Drupal development. It's a sub-module of Chaos Tools that enables you to change the paths of pages, even some of those defined by Drupal core. While it won't change the appearance of a node, it can change the context of it. With Page Manager you can control who has access to pages, and how they get to the pages, including nodes that are part of other pages. Working hand-in-hand with other modules like Panels, Page Manager can help give you great control over the user experience.

Using it you can do redirects on a specific content type to your view and pass along the context such as the nid. No need to worry about aliases.

You do it as follows:

1. Activate Page Manager
2. Go to admin/structure/pages
3. Enable /node/%node to override it.
4. Create a variant with a 301 redirect
5. Create a selection rule on Node Type = Your node type
6. Set the redirect destination to your-view-path/%node:nid
> 0 votes

---
Tags: 7, views, nodes
---


# Question
Title: How to set the node ID to start with 100,000?
I am running a new site with Drupal 7.

I want the **node ID to start with 100,000.**

How do I set it? I don't want the node start with node 1.

# Answer
To make node IDs start from 100000, in a **new site** (which I assume doesn't have any nodes created yet), all that's needed is to run this SQL statement (assuming you're using MySQL, PostgreSQL or SQLite):

* For MySQL or SQLite:

**ALTER TABLE node AUTO\_INCREMENT = 100000;**
* For PostgreSQL, and inspired by the accepted answer to "Reset auto increment counter in Postgres", it should be something like so:

**ALTER SEQUENCE node\_nid\_seq RESTART WITH 100000;**

Change the `100000` value in this SQL to any other value (like `123`), to make node IDs start from that other value (like `123`).

Caution when applying such change in an **existing site**, whereas the new node ID (like `123`) is less then the highest node ID used already in your site. Because in that case you may get all sorts of effects you may not want/like ... Though in a **new site** (as in this question here) those effects don't apply.
> 4 votes

---
Tags: 7, nodes
---


title: Alter field items before render

text:
# Question
Title: Alter field items before render
I'd like to add an item to a multivalued image field rendered by the Field Slideshow module. I need to display an image coming from field image B of entity B in the slideshow of field image A of entity A. The Field Slideshow module implements hook\_field\_formatter\_view. I'd like to be able to add an item at the end of the $items variable of this function. How can I do that ?

# Answer
If someone comes here, use template\_preprocess\_field

In template.php :

```
function MYTHEME_preprocess_field(&$variables) {
  $element = $variables['element'];

  if ($element['#field_name'] == 'field_myfield') {
    //Load the related node, I let you do this step ...
    //$nid = ...

    $nodeB = node_load($nid);
    $variables['items'][0]['#items'][] = $nodeB->field_another_image_field[LANGUAGE_NONE][0];
    //If you have a pager
    $variables['items'][0]['#pager']['#items'][] = $nodeB->field_another_image_field[LANGUAGE_NONE][0];
  }
}

```
> 1 votes

# Answer
The hook you're looking for is hook\_field\_prepare\_view https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook\_field\_prepare\_view/7

It runs before hook\_field\_formatter\_view().
> 0 votes

---
Tags: entities, javascript
---


title: Feeds duplicate all my images

text:
# Question
Title: Feeds duplicate all my images
I'm using feeds with Commerce. For each of my product variation, I have 4 images.

Each time I execute the feed import, the images are all copied by the number of variation. For example, if a product has 10 variations that are supposed to use image **testpicture.jpg**, the result is 10 copies named **testpicture.jpg**, **testpicture0.jpg**, **testpicture1.jpg**, etc.

How can All my product variations point to the same image and not make copies of the image with an incremental number?

# Answer
> 1 votes
I suppose there are a few ways, but this is how I do it:

You need to have your images managed by Drupal. I use Media module (7.x-2.0) and its sub-modules to first upload my images to the Media library. I make sure that my images have unique file names and I do not change it during the upload (Media allows you to rename after upload, just leave at default).

I then map my images via:

* Image -\> Images: Ref in the feed settings and use Feeds Tamper to Explode in case I need multiple images
* Images: Alt and Images: Title, again using Feeds Tamper.

In my uploader file I then use the exact same image names as the file names for Image. Feeds will then map to the Drupal Managed File entity ids which it looks up by name via the URI stream wrapper (I think). I also include fields for Image Alt and Title.

If you don't want to use Media then you may use FileField Sources, but getting the images in the very first time is then a hassle.

---
Tags: commerce, feeds
---


# Question
Title: Ajax form submission error when using use-ajax-submit
I receive the following message when I attempt to submit a form with `use-ajax-submit` class attached to the submit button:

> An error occurred while attempting to process /my\_form?\_wrapper\_format=drupal\_ajax: ajax.$form.ajaxSubmit is not a function

Similar to this question, but for Drupal 8.

# Answer
The following dependencies need to be added to the library attached to the form in order to use `use-ajax-submit`.

*my\_module.libraries.yml*

```
my_module.my_library:
  dependencies:
    - core/drupal.ajax
    - core/jquery.form

```

The library needs to be attached to the form:

```
$form['#attached']['library'][] = 'my_module/my_module.my_library';

```
> 2 votes

---
Tags: forms, ajax, 8
---


# Question
Title: How do i set limit query into url from views output
In drupal i need to output json fields. So i used views\_datasource. In my situation, i need to call same api source to multiple section, but i don't want to create multiple view only for 5 items or 10 items or all items for same content types data. So in **views\_datasource** i need to use limit filter from all of views results like "http://example.com/serve/all-articles?limit=10".

Can anybody help me to do it?

# Answer
Ccreate a custom module and implement hook\_views\_pre\_build.

To create the module follow these steps:

In `sites/all/modules` create a new folder with the name of your module. As you are not contributing this module back to Drupal and it is specific to your project just give it the name of your project and other code tweaks can also live in there.

Let's assume you called your project `custom_project` and it is at `sites/all/modules/custom_project`.

Add a file called `custom_project.info` to it with this content:

```
name = Custom Project Module
description = This module is for project related tweaks
core = 7.x

```

Add a file called `custom_project.module` with this content:

```
<?php
function custom_project_views_pre_build(&$view){
  if ($view->name == "NAMEOFVIEW") {
    if (isset($view->args[0]) && is_numeric($view->args[0])) {
      $view->set_items_per_page($view->args[0]);
    }
  }
}

```

Now install this module (and in future if you add any hooks then clear the cache)

You call this on a friendly url ("http://example.com/serve/all-articles/10").

If you wish to add a query parameter to the url as in "http://example.com/serve/all-articles?limit=10" then your function will need to inspect drupal\_get\_query\_parameters for that parameter instead of pulling it out of `$view->args[0]`.

ie.:

```
<?php
function custom_project_views_pre_build(&$view){
  if ($view->name == "NAMEOFVIEW") {
    $query_params = drupal_get_query_parameters();
    if (isset($query_params['limit']) && is_numeric($query_params['limit'])) {
      $view->set_items_per_page($query_params['limit']);
    }
  }
}

```

You need to replace `NAMEOFVIEW` with your views name. You get it like this:

Note that a view has a name, but also a display id. The display id in this case is page. If you add a block it will get a block display id. So the above code will work for all displays that you add to this view, even for blocks etc. To limit it to just the page you will change the one line to this:

```
if ($view->name == "all_content_of_article" && $view->current_display == "page") {

```
> 0 votes

# Answer
Is using another display in the same view out of the question? It would be a lot easier than a programmatic approach in my opinion?

You could then have all your base configurations on the view main display and create another display with the single override?

If you did go the custom route, you may have to deal with the more complex view caching or disable the views cache on this view.
> 0 votes

---
Tags: views
---


# Question
Title: How can I dynamically add drupal behaviors to a form from php using ajax?
I am creating a form which dynamically changes based on the value of a select element. What happens is this:

1. The user selects a value from the select element
2. The select element uses Drupal's ajax methods to reload the form, now with some new elements for further configuration
3. Some of the new elements need to be turned into jQuery widgets.

Now, the obvious solution here is to use behaviors to run the widget initialization code. The issue is that I don't know ahead of time which elements need to have what code run on them. I will only know that at the time the ajax portion of the form loads.

Currently, my solution is to have a very short JavaScript file which is solely responsible for adding new behaviors which in turn run the jQuery UI code that I need.

An alternate solution is to pre-load all of the possible configuration elements and inject all of the behaviors ahead of time. For various reasons this isn't a good idea, not least because I rather like lazy loading.

My question is: is there some way to attach behaviors **in php** through Drupal's ajax mechanism, like there is a way to modify the settings?

# Answer
Yes you can attach Drupal Behaviors to newly added elements (DOM nodes):

You can check ahah.js (in Drupal.ahah.prototype.success):

```
// Attach all javascript behaviors to the new content, if it was successfully
// added to the page, this if statement allows #ahah[wrapper] to be optional.
if (new_content.parents('html').length > 0) {
  Drupal.attachBehaviors(new_content);
}

```

Or if your script creates the elements (answer on stackoverflow about drupal-behaviours):

```
var newNodes = $('<a href="#">Hello</a> <a href="#">World</a>').appendTo('#someDiv');
Drupal.attachBehaviors(newNodes);

```
> 2 votes

# Answer
Just to know. Are you using #states from Form API?

I think you should use drupal\_add\_js through a hook\_form\_alter in order to make sure that the widget plugin will be already loaded in the page and then use the behavior just to call the method responsible to property convert the element into a JQuery UI element. Using this approach I think you shouldn't worry about adding a behavior on the ajax response.
> 0 votes

# Answer
This item answers your question if you was dealing with a custom callback: drupal\_add\_js within AJAX callback

*djayp34's* answer should help you in your scenario though:

`drupal_add_js` doesn't work properly in an *AJAX callback*. If you need to execute a JavaScript function within an AJAX callback, here's a way :

First in your form, you have to create (you can just import it) the JavaScript function :

```
function my_module_form($form, &$form_state) {
// [...]
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
     // Whatever you want to do.
        }',
        'inline'
     );
 // [...]
 return $form;
}

```

Then in your *AJAX callback*, you need to call the function you have created :

```
function my_module_my_ajax_callback($form, &$form_state) {
  // [...]
  $commands[] = array("command" => 'myFunction',);
  // [...]
  return array('#type' => 'ajax', '#commands' => $commands);
}

```
> 0 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: How to group drush command sets together in sequence?
For example, when installing a drupal site, there are 3 sets of commands:

```
drush dl drupal-7.x

drush site-install standard --account-name=admin --account-pass=admin --db- url=mysql://YourMySQLUser:RandomPassword@localhost/YourMySQLDatabase

drush make example.make

```

Is there a way to group these 3 tasks and have drush do them one by one without having the user do it 3 times?

# Answer
> 0 votes
There are quite a few, I tend to use a shell script, but you can create your own drush command: http://www.sitepoint.com/drupal-create-drush-command/

Here is an example of how I would do this with a shell script (mac / linux).

```
#!/bin/sh

# Default parameters to use.
version="7"
profile="standard"
user="admin"
pass="admin"
mysql_user="YourMySQLUser"
mysql_pass="RandomPassword"
mysql_host="localhost"
mysql_db="YourMySQLDatabase"
makefile="example.make"

# Collect parameters from the command line to override defaults.
for args in "$@"
do
  # Get the drupal install version.
  if [[ ${args:0:10} == '--version=' ]]
  then
    version=${args:10}
  fi

  # Get the installation profile
  if [[ ${args:0:10} == '--profile=' ]]
  then
    profile=${args:10}
  fi

  # User name to give the drupal admin user account.
  if [[ ${args:0:7} == '--user=' ]]
  then
    user=${args:7}
  fi

  # Password to give the drupal admin user account.
  if [[ ${args:0:7} == '--pass=' ]]
  then
    pass=${args:7}
  fi

  # Mysql username
  if [[ ${args:0:13} == '--mysql-user=' ]]
  then
    mysql_user=${args:13}
  fi

  # Mysql password
  if [[ ${args:0:13} == '--mysql-pass=' ]]
  then
    mysql_pass=${args:13}
  fi

  # Mysql host
  if [[ ${args:0:13} == '--mysql-host=' ]]
  then
    mysql_host=${args:13}
  fi

  # Mysql db
  if [[ ${args:0:11} == '--mysql-db=' ]]
  then
    mysql_db=${args:11}
  fi

  # Drush make file to use.§
  if [[ ${args:0:11} == '--makefile=' ]]
  then
    makefile=${args:11}
  fi

done

`drush dl drupal-$version.x`
`drush site-install $profile --account-name=$user --account-pass=$pass --db-url=mysql://$mysql_user:$mysql_pass@$mysql_host/$mysql_db`
`drush make $makefile`

```

Example usage:

```
~/path/to/script --profile=minimal --user=adminuser --makefile=meh.make

```

---
Tags: drush
---


title: LDAP Configuration with Synology DSM

text:
# Question
Title: LDAP Configuration with Synology DSM
We have Synology DSM (Disk Station Manager) Installed in our office, and my Drupal 7 site is hosted on it. I want to use Directory Users to use Drupal with same credentials using LDAP.

I installed the LDAP required modules, but I am still having trouble configuring and connecting.

Did anyone work with LDAP with Drupal?

# Answer
We have successfully integrated Drupal with DSM using LDAP project: https://www.drupal.org/project/ldap

Basicall DSM is running OpenLDAP which is supported by the project. Be sure to enable php-ldap extension.

The ldap module distribution comes with a set of submodules that you enable to configure LDAP authentication and authorisation:

* ldap\_servers - define LDAP server
* ldap\_user - Sync users (User entity fields to LDAP attributes) with LDAP
* ldap\_authentication - Allows user to authenticate with their LDAP username/password
* ldap\_authorization - Give Drupal users roles based on LDAP group.

It also provides a comprehensive GUI to visually configure everything. Also integrates with 'devel' to debug.

HTH
> 0 votes

---
Tags: authentication-authorization
---


title: How to clear cache externally?

text:
# Question
Title: How to clear cache externally?
I'd like some help how to clear the cache using an external script. I have a script that adds nodes each night, and I'd also like it to clear the views cache so - without having to make out by myself the MySQL query.

# Answer
> 7 votes
If you just want to clear one or two particular cache bins you can use `cache_clear_all()` (assuming your script has Drupal bootstrapped):

```
cache_clear_all(NULL, 'cache_views');
cache_clear_all(NULL, 'cache_views_data');

```

# Answer
> 11 votes
If you are running a script, you'll likely benefit from using Drush. With the Drush php-eval and php-script commands, you can easily call a snippet of php code (such as the examples shown in other answers to this question) after bootstrapping Drupal. Without Drush, you would have to set up a web service and use wget or curl to run your code, or try to call the Drupal bootstrap code yourself. Better yet, Drush even comes with a built-in command to clear the cache, so you don't need to worry about writing any php code at all, if that's all you want to do from your script. Just use:

```
cd /path/to/drupal/sites/default && drush cache-clear all

```

You may also wish to learn about site aliases; if you define an alias called @site, then you can instead use:

```
drush @site cache-clear all

```

# Answer
> 6 votes
I suggest register menu and externally call it ,in call back of it put your code(clear cache )

```
function yourmodule_menu() {
    $items = array();
    $items['customclearcache'] = array(
        'title' => 'clear cache',
        'description' => 'clear cache',
        'page callback' => 'yourmodule_clear_cache',
        'access callback' => TRUE , // or any access you need
    );
    return $items;
}

 function yourmodule_clear_cache(){
   cache_clear_all(NULL, 'cache_views');
   cache_clear_all(NULL, 'cache_views_data');
   drupal_set_message(t('cache clearing completed'));
   drupal_goto("node"); // or any page you want
}

```

and you can clear cache with calling this url : `yoursite.com/customclearcache`.

Also if you installed `drush` clear cache with it `drush cc all`

```
   //first go to your installed site path
  $cd /path/to/drupal
   $drush cc all

```

# Answer
> 0 votes
Best way to clear the cache externally is by using Drush commands.

You could use `drush cc` in the terminal and it will ask you what exactly you want to clear. In example it will ask for:

Enter a number to choose which cache to clear.

```
 [0]   :  Cancel
 [1]   :  all
 [2]   :  drush
 [3]   :  theme-registry
 [4]   :  menu
 [5]   :  css-js
 [6]   :  block
 [7]   :  module-list
 [8]   :  theme-list
 [9]   :  registry
 [10]  :  views

```

Select you option and you could clear the cache externally.

For more details about the drush and commands of it you could visit drush GitHub page.

# Answer
> 0 votes
If you want to clear the cache externally, the easiest way is to use `drush`, for example:

```
drush -y cc all

```

which would clear all Drupal caches (but not all caches). In Drupal 8: `drush cr`.

Other way is to write a simple script which would truncate/delete all tables which starts with `cache_`, for example using the following one-liner:

```
echo "SHOW TABLES LIKE 'cache%'" | drush sqlc --extra=--skip-column-names | xargs -L1 -I% echo "DELETE FROM %;" | drush sqlc --extra=-v

```

# Answer
> -2 votes
`TRUNCATE` the `cache_views` table in the database.

---
Tags: 7, views, caching
---


title: check current path in using comtext php

text:
# Question
Title: check current path in using comtext php
I use Context PHP module to write a simple condition:

```
$curr_uri = check_plain(request_uri());

if($curr_uri == '/mypath?123'){
   return TRUE;
}
else{
   return FALSE;
}

```

While this works perfectly for logged in users, it doe's not work for anonymous users. How this might be possible? Permissions are set ok.

# Answer
First off, there could be manly causes to this, most likely permissions but if you're saying these are correct I'd look at the caching.

From how you wrote the question it suggested you're using the php filter (I'd advise against the use of this really and opt for module development). If you are doing this within a module I would check that the hook you are using is the correct one and is being fired.

As for your code, check\_plain isn't needed here because you're not outputting the uri to the browser only checking against it.

I would use the inbuilt drupal functions to do this though either way.

Take note, the current\_path() function returns the internal path for the url, not the friendly one, 'node/1' instead of 'this-url'.

```
$query = drupal_get_query_parameters();
return current_path() === 'mypath' && $query['key_of_query'] === '123';

```
> 1 votes

---
Tags: 6
---


# Question
Title: Moving / Migrating image files from another site into an existing Drupal 7 site
I'm currently doing a data migration from one Drupal 7 site to another Drupal 7 site. So far I exported the data from the old site into a CSV file and then have it get imported into the new site by looping through each row of each result and doing a $node object and then node\_save.

The problem now is how do import/copy the images over? I have the url path from the old site.Do I use file\_unmanaged\_copy() function to get them into the system? But from the docs, it says I can only use public:// and I'm not sure if http urls to the images would work. Or is there another function I need to use for this purpose?

# Answer
Why not use Feed Import I am using it to import content from Joomla and WP sites into new Drupal sites with Drupal to Drupal export import should be a lot easy. My process is as follows:

1. Create desired content types with all matching fields on the new site.
2. Create Import profile for this content type go to mystie/import to download csv template
3. Export content from the old site with path to images so to have matching content with image
4. Upload images to new web site and change paths in csv file
5. Import and create or update content.
> 2 votes

---
Tags: 7, media, migrations, files
---