# Question
Title: Import xml with Feeds module. Only one value is imported
I have a xml (http://pastebin.com/q64L3ECX) that I need to import with Feeds module into my site. Basically, with this xml example, I need to import 3 nodes where my GUID (set as unique) is "test\_case". Each test\_case is inside a test\_set.

The problem is that I can only get the first test\_case of each of the two test\_set of that file. Can someone help me understand what is wrong?

Debug output:

```
xpathparser:0 :
<test_set_name tl_label="Name" tl_name="name" tl_physicalname="CY_CYCLE">GUI.00 Launch Applications</test_set_name>
<test_set_name tl_label="Name" tl_name="name" tl_physicalname="CY_CYCLE">GUI.02 EM NE.000 EM NE Generic.Generic EM NE tests</test_set_name>
xpathparser:1 :
<test_case_name tp_label="Test Name" tp_name="name" tp_physicalname="TS_NAME">Launch TNMS</test_case_name>
<test_case_name tp_label="Test Name" tp_name="name" tp_physicalname="TS_NAME">Open</test_case_name>
<test_case_name tp_label="Test Name" tp_name="name" tp_physicalname="TS_NAME">ManualNetworkScan</test_case_name>

Created 1 node.

```

# Answer
For example, our *relation's key* will be test case's GUID (Test cases (Entity reference by Feeds GUID) (field\_test\_cases)):

* Content type `test_set`:
    + `field_test_cases`: Type - Entity Reference, Target type - Test case (type test\_case), Number of values - unlimited.
* Content type `test_case`: standard Title and Body fields.

Test case's importer's config:

```
$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'test_cases';
$feeds_importer->config = array(
  'name' => 'Test cases',
  'description' => '',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml html htm',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'text()',
        'xpathparser:1' => 'text()',
      ),
      'rawXML' => array(
        'xpathparser:0' => 0,
        'xpathparser:1' => 0,
      ),
      'context' => '/report/test_sets/test_set/test_cases/test_case/test_case_name',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          'xpathparser:1' => 0,
        ),
      ),
      'allow_override' => 1,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'guid',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'xpathparser:1',
          'target' => 'title',
          'unique' => 1,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 1,
      'bundle' => 'test_case',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

```

Test set's importer's config:

```
$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'test_set';
$feeds_importer->config = array(
  'name' => 'Test set',
  'description' => '',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml html htm',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'test_set_name/text()',
        'xpathparser:1' => 'test_set_name/text()',
        'xpathparser:2' => 'test_cases/test_case/test_case_name/text()',
      ),
      'rawXML' => array(
        'xpathparser:0' => 0,
        'xpathparser:1' => 0,
        'xpathparser:2' => 0,
      ),
      'context' => '/report/test_sets/test_set',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          'xpathparser:1' => 0,
          'xpathparser:2' => 0,
        ),
      ),
      'allow_override' => 1,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'guid',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'xpathparser:1',
          'target' => 'title',
          'unique' => 1,
        ),
        2 => array(
          'source' => 'xpathparser:2',
          'target' => 'field_test_cases',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 1,
      'bundle' => 'test_set',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

```
> 1 votes

---
Tags: importing-exporting, feeds
---


# Question
Title: is there any general or universal way to change Drupal's objects CSS?
In some cases, when I install new themes, some regions\ blocks\buttons are too near to each other, and I need to start adding margins between them individually with css. This takes much time...

Is there a way to automate this process? Is there some kind of a general\universal ID or class for all regions\blocks\buttons that I might be able to use to space all of regions\blocks\buttons "In one piece" and with much comfortability? It could also help me save time that could go on other things.

# Answer
> 3 votes
No. Of course there are default Drupal styles but there are no guarantees that whichever base theme you are working from hasn't overridden them.

The good news is that most popular base themes will implement classes that are universal to a particular type of output, like a row or a block. For instance, Foundation uses its own 'row' and 'column' but retains the core 'block' class.

Since you asked :), here is something you might do to add padding to columns in a Bootstrap subtheme:

```
.main-container > .row > section {padding: 1em;}

```

Note the '\>' combinator. This refers to *immediate descendents*.

```
<div class="main-container">
  <div class="row">
    <section>
      <!-- this element will be our target since it's an immediate descendent of .row -->
      <section>
        <!-- this element is not -->
      </section>
    </section>
  </div>
</div>

```

Note: If a selector is prefixed with '#' it is an *id*, and will only apply to one element. A *class* is prefixed with '.' and can apply to multiple elements. So all rows in bootstrap can be accessed with:

```
.row {padding: 1em;}

```

---
Tags: theming
---


# Question
Title: How to unzip or uncompress a file .epub on Drupal?
I've created a content type that upload files .epub on database. Now for some reason (to use epub on a mobile app) I need to get the file .epub uncompressed.

It's like in my content type I upload a .zip file but when drupal store it it's stored unzipped.

Did someone knows a Drupal API function or a method that uncompress or unzip a .epub files?

Note that when I upload an .epub file or .jpg image or any other type of extensions, in the table file\_managed I always get filemime : "application/octet-stream"? is it normal ?

# Answer
> 1 votes
PHP already has a built in class to process zip files. You can combine that with a `hook_node_presave` invocation in a custom module to process the field containing your ePub file and extract it to a directory in your file system.

```
/**
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node) {
  if(isset($node->field_MYFIELD[LANGUAGE_NONE][0]['fid'])) {
    $file = file_load($node->field_sss[LANGUAGE_NONE][0]['fid']);
    $file_path = drupal_realpath($file->uri);
    $file_name = pathinfo($file_path, PATHINFO_FILENAME);
    $zip = new ZipArchive;
    if ($zip->open($file_path)) {
      $zip->extractTo(drupal_realpath("public://MYMODULE_customdir/$file_name"));
      $zip->close();
    }
  }
}

```

---
Tags: nodes, files
---


# Question
Title: How do I conditionally style an image field based on terms
I have a Drupal website with a content type (*Article*) which has a taxonomy term reference field (*Topic*) for the *Topics* vocabulary.

The *Article* path aliases, based on the taxonomy term are, for example, the following one.

* /books/100-days-around-the-world
* /culture/chinese-and-medicine

The content type has also an image field (*Image*). I want to style the main image for the articles classified under *books* differently; I want the image to have greater height than width.

The only way I could think to achieve that is creating a new view for it. I tried to create it, but it only rendered the first article of books. The following screenshot shows the view settings.

>

The real problem is that I don't know a view that renders the article content page. When I contacted the theme author\], for previous modification requests, I was told to use the node--article.tpl.php template file. So I have only two ways:

1. Create a view that renders articles as I described earlier
2. Write code in the node--article.tpl.php template file that conditionally set a style for the image field when the article topic term is *books*

I don't know how to get what I need using the two approaches.

# Answer
### Method 1. Use a node preprocessor

Add this to your theme's template.php, then clear the cache:

```
function THEMENAME_preprocess_node(&$variables) {

  // This only applies to content type 'article' in teaser view.
  if ($variables['node']->type == 'article' && $variables['view_mode'] == 'teaser') {

     // Find out if node has at least one tag and an image.
     if (isset($variables['content']['field_tags']) && isset($variables['content']['field_image'])) {

      // Map tags to style names.
      $settings = array(
        'apple' => 'medium',
        'banana' => 'large',
      );

      // Build an array of tag names.
      $tags = array();
      foreach ($variables['content']['field_tags'] as $k => $v) {
        if (is_int($k)) {
          $tags[] = $v['#title'];
        }
      }

      // For each mapping, check if the tag exists in the $tags array;
      // if yes, apply the style.
      foreach ($settings as $tag => $style_name) {
        if (in_array($tag, $tags)) {
          $variables['content']['field_image'][0]['#image_style'] = $style_name;
        }
      }
    }
  }
}

```

Note that we could also do something similar in node--article.tpl.php, but generally you want to keep code logic out of the template files.

---

### Method 2. Use Rules and Field formatter conditions modules (no coding required!)

The example below will set the image style of `field_image` to 'thumbnail' in the node's teaser view if `field_tags` contains a term with an ID of 18.

The *Field formatter conditions* module an image style to be conditionally set based on the outcome of a rule. It involves creating a rule, then going to *Structure \> Content types \> \[content type\] \> Manage display* and adding the condition in the configuration options of your display (in this case the "Teaser" display).

*Note: This example only checks for a single term. To compare against more terms, add more "List contains item" conditions, one for each term.*

Here is the rule:

Here are the formatter settings:
> 2 votes

# Answer
Simplest way is to add/edit the `node--article.tpl.php` (don't forget to flush caches after you have). Once you have done this you can vary the output based on the values in the `$node` object.

Node template API reference
> 0 votes

---
Tags: 7, views, media
---


# Question
Title: How to use the Rules module to implement a custom redirect for an outdated URL?
I used to show content from a catalog via the Views module, accessing an external database, so that all of the URLs would be something like /content?name=\[name\].

For various reasons, I've opted to import the content directly into Drupal as a unique content type. So now my URLs are /content/\[name\].

I need to implement a 301 redirect so that people going to the first URL (due to old bookmarks, links, etc.) are taken to the new URL.

Is it possible to set up a rule for the content type to accomplish this? The \[name\] field is the same so I feel like it should be a fairly straightforward thing to set up.

I did some searching around, and came up with `RewriteRule ^/?content/([^/d]+)/?$ content?name=$1 [L,QSA]`. I tried putting that in the .htaccess file after `RewriteEngine on`, and that didn't work. Am I following the proper .htaccess convention? I tried `RewriteRule ^(.*)/content?name=(.*)$ $1/content/$2 [R,L]` too, but it didn't work.

# Answer
# Why using .htaccess might not be an option

There are situations where setting up a redirect in your `.htaccess` file may not be an option, such as:

* you are not allowed (= do not "have") edit access to your .htaccess file.
* your provider does not allow specific directives in .htaccess files (which you'd want to use).
* your Drupal site is running on IIS.
* you don't have the required knowledge to correctly code the redirect in your .htaccess.
* ... (what else?).

These are all reasons for using an approach based on the Rules module, as further detailed below.

# Use Rules with 'Drupal is initializing'

Using the Rules module to get this to work, you should be able to use the "**Drupal is initializing**" event. That will ensure that the rule gets triggered BEFORE the actual content is shown.

# Use a Regular Expression

The link that you want to "intercept", should be formatted in some type of regular expression, which you then use as your rules "Condition". so that you have a rule that corresponds to "before showing the actual content of something that matches a specific path ...". After you get that part to work, your Rules "action" should specify the actual redirect to be performed.

**Remark**: in this case you can also use "`contains /content?name=`" (instead of the regular expression) to get the text match working.

# Sample rule

Refer to the "option 1" part of my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains this rule in export format:

```
{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

Here are some suggested tunings of the above sample, to make it work for your case also:

* machine name and label.
* replace the `node/*` by your path (in the "label", and the regular expression).
* replace the path in the action part of the rule by your target path (more details below), and check if you do want some type of error message to be shown (if not remove that part of the action).

# Use the value of the \[name\] variable in the redirect

To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

**PS**: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.
> 11 votes

# Answer
For 301 redirects, you might want to look at the Global Redirect module. Some more details about it (from its project page):

> GlobalRedirect is a simple module which…
>
> * Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> * Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> * Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> * Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
> * Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
> * Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
> * Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin module. In Drupal 6, the settings page is bundled into the module.
> 2 votes

---
Tags: 7, nodes, rules, redirection
---


# Question
Title: How to change Drupal's default language programmatically?
I am trying to change the Drupal's default language programmatically but haven't found the codes/function. Any suggestions?

# Answer
Here is a corrected and tested version of the code posted by @Clive in a comment to the OP:

```
$langs = language_list(); // Note: No argument
// debug($langs, '$langs');
$langcode = 'en';
variable_set('language_default', $langs[$langcode]);

```

The code snippet above assumes that the two-character code that you assign to `$langcode` is enabled. Uncomment the call to `debug` to see the languages that are enabled on your site and what array indices they use.

Note that the setting will not take effect until the next page load.
> 9 votes

# Answer
I have found the code and its pretty simple .

```
//Set Default language
    $default_language = array('language' => 'en-US',
                            'name' => 'English',
                            'native' => 'English',
                            'direction' => LANGUAGE_LTR,
                            'enabled' => (int) TRUE,
                            'plurals' => 0,
                            'formula' =>'',
                            'domain' => '',
                            'weight' => 0,
                            'javascript' => '');
variable_set('language_default', (object) $default_language) ;

```
> 1 votes

# Answer
By implementing the following hook: hook\_language\_negotiation\_info() and here is a full example

http://tassaf.moriamedia.com/drupal-7-default-language-after-translation/
> 0 votes

# Answer
Just setting the variable is not always enough. By the time you've done so, the Drupal language negotiation function may have already run, and it will not react to this variable change. The proper way to do this is as follows:

```
// Get the list of languages
$languages = language_list();

// Set up the new language code
$new_lang_code = 'fr';

// Make sure the required language object is actually set
if (isset($languages[$new_lang_code])) {
  // Overwrite the global language object
  global $language;
  $language = $languages[$new_lang_code];
}

```

This has been documented in other questions such as: function to change language object

An additional option is to write your own custom language negotiation hook: https://api.drupal.org/api/drupal/modules!system!language.api.php/function/hook\_language\_negotiation\_info/7
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How to implement a follow author (or user) function?
Is it possible to implement a **Follow** button for authors of posts in Drupal 7, so that users can:

* Follow any one they wish, and
* Be notified about the new posts of those authors.

This sounds like '*Mashable Follow button*' for authors.

Do you have any suggestions about how to implement this?

# Answer
# Minimal solution

The Notifications module currently only has an Alfa version for D7 (which is this question is about), which dates from Dec 2011.

Therefor, use the Flag module as an alternative. So that users can "flag" authors they want to "follow". You'd want to use a flag related to entity "users", which is a non-global flag. Probably defined with a label like "Follow Author" (to 'flag' an author) and "Unfollow Author" (to undo a previously flagged Author).

Combine this with using the Rules module to send eMails whenever content gets updated by some author. Whereas the eMails are sent to all users who "flagged" that author (= the users who indicated they wanted to "follow" that author). If you'd only want to send such eMails for a subset of content that's being updated (eg only for selected content types), then it's just a matter of adding an appropriate extra "condition" to your rule.

# Improved solution

Optionally you may also want to consider the Message module for more options in the area of sending some type of notifications. For this, you need a flag like described above (say with machine name `follow`).

On top of that you need a ***Message type*** and a custom ***Rule***, both are detailed below. And you probably also want to add a custom ***View*** of those messages.

### Message type

Below is an export of "a" Message type that you could use to get started (by simply importing it in your own site). It defines the message to be created when a user is flagged and it actually works together with the custom rule below. This message type has machine name `user_following`, and uses a replacement token like `@following_user` (adapt both to fit your needs, eg change `@following_user` to `@user_who_flagged` if you prefer):

```
{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [ "@following_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@following_user started following [message:user:name]",
        "format" : "plain_text",
        "safe_value" : "\u003Cp\u003E@following_user started following [message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

```

This Message type (compare to a *Content type* ...) will be used to create Messages (compare to *Nodes*) that will look as in this example:

> Hillary.Trump started following Donald.Clinton

To avoid confusion, note that `[message:user:name]` in the message type sample above is the user **to** which the Message is targeted, not the flagging user!

### Custom Rule

Here is a rule (in Rules Export format) which creates a message when a user is flagged:

```
{ "rules_somebody_started_following_you" : {
    "LABEL" : "Somebody started following you",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_follow" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "user_following",
            "param_user" : [ "flagged-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:following-user" ],
          "value" : "[site:current-user]"
        }
      }
    ]
  }
}

```

Some more details about this rule:

* Its purpose is to deliver a message (using the Message module) to a user being flagged (using the Flag module).
* It is triggered after a user is flagged with the flag with machine name `follow`.
* It creates a Message with machine name `user_following`.
* It makes a variable with machine name `following_user` available as a replacement token for the message to be created ... so that the "flagging user" (= `[site:current-user]` when the flagging happens) can also be included in the message to be created.

### Custom view

With the above rule and message type, you'll have "messages" that get created ... "*So what?*" you may think. Well, since all this is entity API based, you can create a custom view (using Views) to visualize these messages, e.g. shown via a path like `/user/nid/messages`. Whereas the only limitation for such Views is your own imagination (you could even create the Charts about those Messages (eg by originating user, by date, etc).

# Additional info

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module.

For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation. And/or checkout the video introduction "Your Drupal site can talk" (if you want you can fast forward to about 03:30 where it really starts).

**Note**: this approach can be used also for any type of users (not just for "authors").
> 5 votes

# Answer
The Notifications module provides this functionality. Enable the **User Subscriptions** and **Notifications UI** sub-modules of it.

> This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.
> 3 votes

---
Tags: 7, emails, notifications
---


# Question
Title: How to exclude the user table using the drush sql-sync command
How do I exclude Drupal's user table from drush's `sql-sync` command?

# Answer
> 1 votes
The command is executed like this, if you're going to ignore the users table might as well ignore roles and permissions too, but that's up to you:

```
drush sql-sync -v --skip-tables-list=users,users_roles,role_permission @prod @dev

```

`-v` is optional and will display what the command is doing & confirm the tables are being skipped like so:

```
The following tables will be skipped: role_permission,users,users_roles

```

# Answer
> 4 votes
You can use `--skip-tables-list` flag on your `drush sql-sync` command

```
drush sql-sync @prod @dev --skip-tables-list=user

```

the table lists should be comma seperated.

For more options on `sql-sync` check this documentation.

---
Tags: drush, database
---


# Question
Title: Path Redirect Import module getting "Line 1 contains invalid status code"
I created a CSV file without the headers:

```
From URL    To URL  Redirect Status Redirect Language

```

But the file doesn't import and I get error messages:

> "Line 1 contains invalid status code"

My CSV file:

```
“file/sitemap.xml”, “sitemap.xml”,  “301”,  “en”

```

# Answer
Looking at the csv row you provided, it looks like that the syntax is not correct:

1. Try to separate fields only with ',' and not with ', ' (comma + whitespace)
2. Use regular double `"` quotes or single quotes `'`, not these opening  and closing  double quotes you get when using word processors. I guess for the last two columns (status code and language) you won't need quotes at all.
3. You may also remove the headers line from the csv and check the "no headers" option if it contains non-ascii bytes.

See also this tutorial: Module of the Day: Path Redirect Import.
> 0 votes

---
Tags: 7, redirection, importing-exporting, path-aliases
---


# Question
Title: How to get field value from referenced entity inside a field collection
My structure is as follows:

I've got a custom contenttype with a multivalue field containing a field\_collection. In this field\_collection there are an amount field, a entity\_reference\_field and a computed\_field. The referenced entity also contains several fields.

What I need to do:

* Step 1: In the computed field (inside the collection) I need to get the value of a certain field of the entity, referenced by the entity\_reference field (also inside the field collection) and multiply this value with the value of the amount field.
* Step 2: In another computed field (on the node itself) I need to sum up all the values of all the computed fields inside these collections.

My Problem is primarily Step 1

# Answer
Based on what I read in the computed\_field documentation, you have two options when creating the necessary code to compute the field. You could create the PHP into the text area of the field (I really dislike PHP in the database...but that's just me) or you can create a custom module with a specific function in it. Per the documentation:

```
Drupal 7

To use a function in a custom module instead of writing the code in text area create a function that looks like:

<?php
function computed_field_YOUR_FIELD_MACHINE_NAME_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $entity_field[0]['value'] = 'value';
}
?>
Parameters:

&$entity_field - The computed field. Used to store the computed value.
$entity_type - The entity type: node, user, comment, etc.
$entity - The actual entity (a node, user, comment, etc.)
$field - General field settings.
$instance - Field instance settings.
$items - The list of items.
Note:
Make sure $entity_field is passed by reference.

```

What is awesome about this method is we have the entity available to us via $entity (in your case, it would be an entity of type field\_collection). From this approach, I would:

1. Create a custom module with this function
2. I would then create logic around calling the $entity variable, loading the entity (if required) and then getting it's entity reference, which will probably require another entity load.
3. Do compute field logic that you'd like.

Once this is done, you can use the same custom module to write another `computer_field_YOURFIELD_compute()` function for your initial field (on the node) that computes the combination for all field\_collection computed field values.
> 1 votes

---
Tags: entities
---


# Question
Title: How do I perform a 301 redirect for all old .asp pages?
I am trying to figure out a way to redirect all the old .asp pages to a specific page in my Drupal site.

Is there a way I can accomplish this with a web.config file? I cannot use a .htaccess file because the site will still be running on IIS.

# Answer
> 2 votes
Why not use Drupal 7's core URL redirect interface? It has an option for 301 redirects: Configuration \> Search and metadata \> URL redirects.

I like it because it captures stats on how many redirects are happening.

# Answer
> 1 votes
I think you should be able to get this to work by using the Rules module.

Depending on how the format of the old .ASP pages look like, you may want to also use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For more details, refer to my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?".

---
Tags: 7, redirection
---


# Question
Title: How to close the overlay after form submission
In order to be able to quickly edit Fullcalendar items, I altered the node edit form of the specific content type so the events are saved with AJAX and the page doesn't have to reload.

However, I don't know how to close the overlay afterwards. I found overlay\_close\_dialog(), but how do I implement this in my functions (I'm very new to Drupal coding)?

Until now I have:

```
<?php
/**
* Implements hook_form().
*/
function fullcalendar_ajax_node_save_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'agenda_item_node_form') {
     $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add to Apple Form'),
    '#weight' => 50,
      '#ajax' => array(
        'wrapper' => 'agenda-item-node-form',
        'callback' => 'fullcalendar_ajax_node_save_callback',
        'effect' => 'fade'
        ),
    '#submit' =>
      array (
        0 => 'node_form_submit',
      ),
    );
  }
  return $form;
}

function fullcalendar_ajax_node_save_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  return $form;
}
?>

```

# Answer
The callback should be:

```
function fullcalendar_ajax_node_save_callback(&$form, &$form_state) {
  // Could check that the overlay is open? Part of core, so overkill
  if (module_exists('overlay') && overlay_get_mode() == 'child') {
     $current_path = current_path();
     overlay_close_dialog($current_path,
        array('query' => drupal_get_query_parameters(NULL, array('q', 'render'))));
    $form_state['redirect'] = FALSE;
  }
}

```

See overlay.module, about line 148 function overlay\_init() for an example in core that uses as much drupal API as possible.
> 0 votes

# Answer
https://api.drupal.org/api/drupal/modules!overlay!overlay.module/function/overlay\_close\_dialog/7

```
function fullcalendar_ajax_node_save_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'agenda_item_node_form') {
     $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add to Apple Form'),
    '#weight' => 50,
      '#ajax' => array(
        'wrapper' => 'agenda-item-node-form',
        'callback' => 'fullcalendar_ajax_node_save_callback',
        'effect' => 'fade'
        ),
    '#submit' =>
      array (
        0 => 'node_form_submit',
        1 => 'your_custom_callback'
      ),
    );
  }
  return $form;
}

function your_custom_callback($form, &$form_state) {

  $url = "<front>";
  if (module_exists('overlay') && overlay_get_mode() == 'child') {
    unset($_GET['destination']);
    overlay_close_dialog($url, array('external' => TRUE));
    $form_state['redirect'] = FALSE;
  } else {
    $form_state['redirect'] = $url;
  }
}

```
> 0 votes

---
Tags: ajax, forms, modal-dialogs
---


title: Use symlinks in the files directory

text:
# Question
Title: Use symlinks in the files directory
I use symlinks `sites/default/cdn` ( symlinks for /u01/cdn) instead of `sites/default/files/`. I've `chmod` two folders cdn is 777. But when I access the link `admin/config/media/file-system` and paste `sites/default/cdn` then displays following error;

My permissions are:

Can you help me for my problem? please. Thank you.

**Solution**

I have found problem. Only disable SELinux. use command: `setenforce 0` to disable SELinux.

# Answer
> 0 votes
I have found problem. Only disable SELinux. Use command: `setenforce 0` to disable SELinux.

---
Tags: files
---


# Question
Title: How to list nodes that share only the first selected value in an entity reference field?
I have entity reference field to a taxonomy vocabulary on a node, which is a multi value field.

In Views, how do I list related nodes that share only the first selected category?

Example: Suppose I have selected "category3" and "category4" for a node. I want to show other nodes which have selected "category3".

# Answer
> 0 votes
You should be able to set up something like what you are after with the following steps:

* Create a view of content (nodes)
* Add a contextual filter for NID with a that gets it's default value from "Content ID from url" (presuming the related products are to appear on the original products own page).
* Add a relationship on field\_category, call it something like "category", require this relationship
* Add a filter of field\_category:delta, value = 0
* Add a relationship of "Content using field\_category", require this relationship, use relationship: category, call this relationship something like "related"
* Add another contextual filter that's also for NID with a that gets it's default value from "Content ID from url", use relationship: related, tick "Exclude" in the "More" fieldset at the bottom.
* Now when you add your fields use relationship: related.

---
Tags: 7, views
---


# Question
Title: Disable editing of a node after it has been published
**Scenario:**

A user can create a node (content type "story"). All story nodes that are created are unpublished by default.

I have a boolean field called "publish my story". Once this has been checked and saved the node is published using rules.

**Question:**

Is it possible to *revoke* a users ability to edit published nodes by using rules as I do not want them to change the story afterwards.

# Answer
Yes, you can define dynamic rules in a custom module. See `hook_node_access`

Here's a sample implementation:

```
/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access($node, $op, $account) {
  if (
    // The $node argument can be either a $node object or a machine name of
    // node's content type. It is called multiple times during a page load
    // so it is enough if you perform the check once you get the object.
    is_object($node) && $node->type == 'story' &&
    // Operation on which you want to act: "create", "delete", "update", "view".
    $op == 'update'
  ) {
    // Check if the node is published.
    if ($node->field_published[LANGUAGE_NONE][0]['value'] == 1) {
      return NODE_ACCESS_DENY;
    }
  }
}

```
> 8 votes

# Answer
Here are a complete module to perform the task, plus assigning a role to do that behavior with it:

`saidbakr_tools.info`:

```
name = SaidBakr Tools
description = Tools offered by Said Bakr said.fox@gmail.com
core = 7.x

configure = admin/config/administration/saidbakr_tools

```

`saidbakr_tools.module`:

```
<?php
/**
 * Implements hook_node_access().
 */
function saidbakr_tools_node_access($node, $op, $account) {
   global $user;
  if (
    // The $node argument can be either a $node object or a machine name of
    // node's content type. It is called multiple times during a page load
    // so it is enough if you perform the check once you get the object.
    is_object($node) && $node->type == 'article' &&
    // Operation on which you want to act: "create", "delete", "update", "view".
    $op == 'update'
  ) {
    // Check if the node is published.
  //  var_dump($node);
    if ($node->status == 1 && in_array(variable_get('saidbakr_tools_role','author'), $user->roles)) {
      return NODE_ACCESS_DENY;
    }
  }
}

/**
 * Implements hook_menu().
 */
function saidbakr_tools_menu() {
  $items = array();

  $items['admin/config/administration/saidbakr_tools'] = array(
    'title' => 'SaidBakr Tools',
    'description' => 'Settings for SaidBakr Tools!',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('saidbakr_tools_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: Current posts settings
 *
 * @see saidbakr_tools_menu()
 */
function saidbakr_tools_form($form, &$form_state) {
  $form['saidbakr_tools_role'] = array(
    '#type' => 'textfield',
    '#title' => t('The role name'),
    '#default_value' => variable_get('saidbakr_tools_role', 'author'),
    '#size' => 20,
    '#maxlength' => 24,
    '#description' => t('Enter the role name that its users should not be able to edit published contents.'),
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

```

Create the above two files in a folder, name it `saidbakr_tools` and then upload it to your Drupal installation at `sites/all/modules`.

In this solution to test node publish status, I used `$node->status`
> 1 votes

---
Tags: 7, nodes, users, rules
---


# Question
Title: Getting a list of altered fields when saving a node
I need to trigger some logic to recalculate certain computed fields based on what fields may have been altered when a user updates a node. So I'm looking to create a function that returns a list of of fields the user has updated.

I've come pretty far by using hook\_node\_update().

Currently the process is like this.

My hook\_node\_update looks roughly like this:

```
function hook_node_update($node) {
  $old_node = node_load($node->nid);

  // Figure out what fields have been altered.
  $altered = _get_altered_fields($node, $old_node);

  // Recalculate the fields *after* node save.
  drupal_register_shutdown_function('_process_fields', $node, $altered);
}

```

And the \_get\_altered\_fields function:

```
function _get_altered_fields($node, $old_node) {

  $changed = array();

  if ($old_node-> field_somefield != $node-> field_somefield) {
    $changed[] = 'somefield';
  } elseif ($old_node-> field_someotherfield != $node-> field_someotherfield) {
    $changed[] = 'someotherfield';
  }

  return $changed;
}

```

The problem with the above is that I get 'false positives' (i.e. 'someotherfield' gets registered as changed even though it is not) because the $node object does not have the exact same data structure as $old\_node, which was fetched from the database. In general $node has more attributes - especially if it is a taxonomy field - such as 'vid', 'weight' and 'rdf\_mapping'.

I tried creating a normalize function where I unset those attributes, but it gets very messy. I figure someone must have done this before me. Any suggestions how to do this in a clean way?

# Answer
> 0 votes
The simple way of recalculating and update field without any effect of other field is hook\_entity\_update or code like display here.

```
<?php
$entity_instance = entity_load('entity_name', array($id));
$entity_instance->field_myfield[LANGUAGE_NONE][0]['value']= 5;
$entity_instance->save();
?>

```

---
Tags: nodes, hooks
---


# Question
Title: Show title of referenced node in node template
I'm working on a node template for my content types and use Entity reference to reference my content with each other. THe machine name of my entity reference field is *og\_group\_ref*. In my node template I used `print_r(get_defined_vars())` to show all existing varialbes to select variables I need. When I look for *og\_group\_ref* I only get the *target\_id* of that reference:

```
[og_group_ref] => Array
            (
                [0] => Array
                    (
                        [target_id] => 65
                    )
            )

```

So, my question is how do I get the title of that referenced node?

# Answer
For example, if I remember node structure right:

* Load node by id into $node
* Put title to $node\_title

$node = node\_load(og\_group\_ref\[0\]\[target\_id\]);

$node\_title = $node-\>title;

All you need is to get og\_group\_ref object/element
> 1 votes

---
Tags: theming, nodes, entities
---


# Question
Title: How to rewrite Views filter URLs when based on an aliased node URL?
I realize this seems confusing, but let me give some background first ...

I have a node (say `node/123`) with a path alias (call it: `/books`). So if I go to http://example.com/books I'm viewing a page that's already been aliased by Drupal from `/node/123`.

However, now I put a Views block on that page and that block has an exposed filter. So, when I filter results I end up with an URL that looks something like so: http://example.com/books?type=fiction

---

Now here's the problem: I want to rewrite the above URL into something like http://example.com/fiction-books

This isn't as easy as it seems:

* You can't use the pathauto module to set a new alias.
* You can't use a function like `hook_url_inbound_alter` or even `custom_url_rewrite_outbound` because the querystring doesn't exist in any of those.

I attempted a rewrite in htaccess, which seems like the best solution, but I can't get anything there to work (I suspect this is because of Drupal rewriting the alias already so the pattern to use there is confusing).

For the record I know almost nothing about rewrites, but I've got this in htaccess which doesn't work:

```
RewriteCond %{REQUEST_URI}^/books$
RewriteCond %{QUERY_STRING}^type=fiction$
RewriteRule %{REQUEST_URI}^/fiction-books$ [L,R=301]

```

So, how do I do it? Advice on an internal Drupal-way would be ideal. But if not, then help via an htaccess RewriteRule would be really appreciated.

# Answer
Have a look to Query Parameters To URL, I believe it fits your need :

> This module provides the ability to rewrite URL query parameters into Clean URL components on specified paths.
>
> An example of a dirty URL like that could be: *example.com/events?field\_category\_id\[0\]=100&field\_category\_id=101&field\_author\_name\[0\]=John*
>
> Using this module you can transform the URL into: *example.com/events/p/field\_category\_id/0\__100--1\__101/field\_author\_name/John*
> 1 votes

# Answer
Looking at your sample URL (= `http://example.com/books?type=fiction`) I think you should try to make the value (= `fiction`) of the URL argument (= `type`) available as a new variable to Rules. To do so, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.
> 0 votes

---
Tags: views, .htaccess
---


# Question
Title: How do I set administrator menu to be the same as this Drupal 7 menu?
I upgraded my site from Drupal 6 to Drupal 7.

The administrator menu is looks differently with Drupal 7 aministrator menu.

How do I set it same as the default Drupal 7 menu?

***Drupal 7 administrator menu after upgrading***

***I want it became this administrator menu***

# Answer
To disable the menu shown in your first image, go to *Structure \> Blocks* and disable any menu blocks you don't want to display (e.g., Management, Navigation, User). (Thanks, @leymannx!)

To have the menu shown in your second image, enable the core Toolbar module.
> 3 votes

---
Tags: 7, routes
---


# Question
Title: Is it possible to stop a webform form during submission?
The webform module is being used for a form that takes a payment. The data is validated as much as it can and then **in a submit handler** it is finally sent to the payment processor.

The result can be a failure (wrong card number, or no funds etc.), which should result in the form being re-presented giving the user the opportunity to check their fat fingers didn't type in the wrong card details, try another card etc.

In a vanilla Drupal form I could do a `$form_state['redirect'] = FALSE;` and it would return the form as-is, but this does not work when working within webform because it deals with that itself.

So this is a weird one because it's basically validation done in a submit handler. This is because we need to make sure everything's valid before submitting it to the third party, but there are clearly two ways to frame this question:

1. As the title says, is it possible for a submit handler to tell webform to stay on this page and not consider it complete?

*or*
2. If I move the submission code into a validation handler, how can I ensure my validation handler happens after all the others, and then check that there aren't any other validation errors before I proceed with the payment submission?

# Answer
First is I'm not sure if it's best practice to do validations in the submit handler because as you've said, you need to validate **first**. So I can only answer your second question.

To make your validation run after every validation present for that form, you need to add it in the end of the #validate attribute. Example is like:

`$form['submit']['#validate'][] = 'your_last_needed_validation_func';`

To check if there are validation errors before your validation function, you can use the form\_get\_errors function.
> 7 votes

---
Tags: webforms
---


# Question
Title: How to attach a JS library to page or block with #attached?
I have seen something like the following document for forms:

```
$form['myelement']['#attached']['libraries_load'][] = array('myAwesomeLibrary');

```

However, this does not work in render arrays for pages or blocks. At least, not in Drupal 7. When attaching a JS library to a render array in a page or block, should I use the 'libraries\_load' or 'library' key within the '`#attached`' array? Neither seem to work.

Of course, it's possible to use the 'js' key along with libraries\_get\_path, but I'm not sure that's best practice for Drupal 7, and it doesn't really take advantage of the path in hook\_libraries\_info.

# Answer
> 3 votes
This might be a simple case of misunderstanding. The difference between `libraries_load` and `library` #attached keys can be confusing.

`['#attached']['libraries_load']` is for libraries defined through `hook_libraries_info` which is in turn a part of the Libraries API module. If a module has defined a hook `hook_libraries_info` but your installation doesn't have the Libraries API module installed, then that library will never load. The `libraries_load` key of #attached will not fire for the same reason. Ideally though, this module with the `hook_libraries_info` should have a dependency on the Libraries API module if it was written correctly.

`['#attached']['library']` is for libraries defined through drupal core library api `hook_library`. This should always work without any additional modules, provided you've defined a `hook_library` in your module (and not `hook_libraries_info`)

Hope this helps you get a clearer idea of what's exactly wrong. You can't have these interchanging, and just trying `libraries_load` or `library` randomly to see if they work. Both require a certain prerequisite (see above) to function correctly.

# Answer
> 0 votes
There are two ways to do this that come to my mind. The first is registering a `hook_library()` within a custom module. This will allow you to include multiple JS/CSS files.

However, a more common approach would be:

**BLOCK**: `drupal_add_js()` or `drupal_add_css()` in the `hook_block_view()` implementation.

**PAGE**: If this is a page you are defining through code, you could use the BLOCK implementation above **or** you could do a `template_preprocess_page()`.

hook\_library: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_library/7

drupal\_add\_js: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7

drupal\_add\_css: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_css/7

template\_preprocess\_page: https://api.drupal.org/api/drupal/includes%21theme.inc/function/template\_preprocess\_page/7

---
Tags: 7
---


# Question
Title: Get proper block title from block object
I have a block object in drupal 8 that I am trying to get the title of. I tried `$block->label()` and it seems to work for some block types, but not for Views blocks. On those, it returns the block's admin label, not the configured title.

If it matters, I am trying to find this information from `hook_preprocess_region()`.

# Answer
If you were using `hook_preprocess_block()` it would be much easier to get the title, you would simply load the block by its id and get the label from the returned block object like this:

```
function hook_preprocess_block(&$variables) {
  $variables['new_title'] = \Drupal\block\Entity\Block::load($variables['elements']['#id'])->label();
}

```
> 1 votes

# Answer
The label of the block entity is the admin label. It might or might not be used as the label that is actually printed out.

First, there is a setting that allows to control if a label should be printed or not. Second, block plugins can return a label from their build() method that will override the one used in the UI. See the code in template\_preprocess\_block() for reference:

```
  $variables['label'] = !empty($variables['configuration']['label_display']) ? $variables['configuration']['label'] : '';
  // A block's label is configuration: it is static. Allow dynamic labels to be
  // set in the render array.
  if (isset($variables['elements']['content']['#title']) && !empty($variables['configuration']['label_display'])) {
    $variables['label'] = $variables['elements']['content']['#title'];
  }

```

That said, I don't think you can access that in the region preprocess however, because the blocks haven't been built yet and their output might be cached, so the block preprocess will never be called in that case.
> 0 votes

---
Tags: views, blocks, 8
---


# Question
Title: How to get the default value of radio button from database?
I have **5 check-box**. For each check-box, **5 radio buttons get generated.** These radios value get saved to **database**. Now what I want is, when I select check-box, and if the selected check-box has some database value already saved in database, **that radio button should show saved database value**, mean to say, it should be shown **selected**. 5 check-box are like: 1. **A** 2. **B** 3. **C** 4. **D** 5. **C**

All check-box has radio options like: **Male** or **Female**

If(say) I choose "**Male**" for "**A**" and submit my form. when I again go to that form and choose "**A**", "male" radio button should be shown selected.

*some code implementation:*

```
foreach ($check-box-options as $key => $value) {

        $form['radio_'.$key] = array(
            '#type' => 'radios',
            '#title' => t('abc'),
            '#options' => $filter_radio_options,
            '#default_value'=> ???,
            '#states' => array(
                'visible' => array(
                    ':input[name="filter_criteria_options['.$key.']"]' => array('checked' => TRUE),
                ),
            ),
        );
}

```

`$check-box-options` is an array of check-box *A,B,C,D,E*. For each check-box, I have radios.

```
$serialized = unserialize($radio_buttons_database_values);

```

`$serialized` contains all selected radio button values. If I replace `$check-box-options` with `$serialized`, I got **correct radio button selected** as **default**, but if I loop `$serialized` as **nested** inside `$check-box-options`, it is throwing *last selected value* from database for every check-box. I am not getting the exact problem with my code or approach.

Can anyone please help me understanding the exact problem behind this?

# Answer
As the radios are separate field in itself, default value should be as easy as follow

```
foreach ($check-box-options as $key => $value) {
        //A. A function to query database to get default value
        $default_value = _my_module_helper_get_default_radio_option($key);

        //B. Or if its a system setting form, all values are inside the variables, in that case all you have to do is variable_get()
        $default_value = variable_get('radio_'.$key);

        // Depending on form type use option A or B.

        $form['radio_'.$key] = array(
            '#type' => 'radios',
            '#title' => t('abc'),
            '#options' => $filter_radio_options,
            '#default_value'=> $default_value,
            '#states' => array(
                'visible' => array(
                    ':input[name="filter_criteria_options['.$key.']"]' => array('checked' => TRUE),
                ),
            ),
        );
}

// In case option A is what you needed.
function _my_module_helper_get_default_radio_option($key) {
  return db_select('your_table','yt')
         ->fields('yt',array('field_name'))
         ->condition('yt.field_is',$key,'=')
         ->exectue()
         ->fetchField();

 }

```
> 4 votes

---
Tags: forms
---


# Question
Title: Do i really need to hack core to install Amazon S3 Module?
I want to run my site through Amazon's Elastic Beanstalk but to do so i need to configure an S3 bucket and the Drupal Amazon S3 module requires that i have to hack core. Surely there must be a way around this? Would Storage API module be a way around this?

# Answer
> 5 votes
I think you should give a try to S3FS module

> S3 File System (s3fs) provides an additional file system to your drupal site, which stores files in Amazon's Simple Storage Service (S3) or any other S3-compatible storage service. You can set your site to use S3 File System as the default, or use it only for individual fields. This functionality is designed for sites which are load-balanced across multiple servers, as the mechanism used by Drupal's default file systems is not viable under such a configuration.

---
Tags: cdn
---


title: Drush SSH Port 22 Error

text:
# Question
Title: Drush SSH Port 22 Error
I've been trying for quite some time now to get my drush to play nicely with my Drupal configuration and I'm having some problems. I'm attempting to perform cc all and uli on my Drupal directory and I keep getting the following error:

```
ssh: connect to host site.dev port 22: Operation timed out

```

The command I'm running is "`drush @site.dev cc all`" and "`drush @site.dev uli`"

Whenever I run uli I get a slightly longer version of the same error:

```
The external command could not be executed due to an application     [error]
error.
Illegal string offset 'site' backend.inc:1030                        [warning]
The command could not be executed successfully (returned: ssh:       [error]
connect to host site.dev port 22: Operation timed out
, code: 255)
current() expects parameter 1 to be array, null given                [warning]
user.drush.inc:415
parse_url() expects parameter 1 to be string, array given            [warning]
exec.inc:427
 does not appear to be a resolvable hostname or IP, not starting     [warning]
browser. You may need to use the --uri option in your command or site
alias to indicate the correct URL of this site.

```

I'm not really sure where to start with getting this to work. I've poked around in my Vagrant configuration and I'm able to SSH on port 22, so I don't really know where else to look to correct this error.

This is what my alias configuration looks like:

```
Vagrant.configure("2") do |config|
  mc_settings = {
    :domain => 'site.dev',
    :docroot => '/home/vagrant/docroot',
    :host_docroot => '../docroot',
    :database_name => 'site_dev',
    :vbox_name => 'site_dev'
  }

```

# Answer
> 2 votes
It's really hard to answer specifically, since it really depends on how you have set your vagrant up.

Long story short

You need to setup your drush alias so that it's using SSH settings to access your vagrant box. The issue is probably that your vagrant box doesn't expect connections on port 22 or that you haven't setup the correct IP/domain for SSH connection in your alias.

If you want to use Vagrant for Drupal development I can recommend parrot. It has all you want for Drupal developetment, uses puppet, which makes it pretty easy to change PHP versions etc, and has Varnish, Solr etc.

If you are using parrot you should be able to access the Vagrant box by doing.

```
ssh vagrant@site.dev

```

Assuming that your site is located on the site.dev url.

---
Tags: drush, virtual-machine
---


# Question
Title: Redirect to main view URL when no contextual filters are set
I have a view in drupal 7 with **no contextual filters at all** set.

Let's say it is a simple list of nodes of the type "item" and that the url is http://example.com/listofitems

I also have pathauto patterns set for the individual nodes. So if an item titled "my item" is created the url would be http://example.com/listofitems/my-item This is important to know because I don't want to set another view for the path `listofitems/%`.

Given that no view or URL alias exists for `listofitems/foo` I expected that this URL would give a 404 error: http://example.com/listofitems/foo

Instead it shows the full view with no errors. This is confusing and bad for SEO. If a bot hits http://example.com/listofitems/foo/bar/foo/bar/foo/bar/blahblahblahblah they should get a 404 message. Or better yet, they could get a 301 redirect to the main view url. In any case, they should not be allowed to stay on the non-existant URL and see the view with no errors.

How can I accomplish this? Is there a trick I'm missing or a reason that this is the default behavior?

# Answer
> 5 votes
The problem lies in Drupal's menu system, which for the most part asserts itself as a safety mechanism, so if you or someone else mis-spells a URL it will give you the next best option.

**Admin Menu Example**

admin/structure/blocks = Manage Blocks Page

admin/structure/blockss = Structure Page

Drupal does this so it won't "disrupt" the user-experience, but it can also be a confusing if you don't know what just happened.

It's generally there to prevent human error and other problems that arise when managing a live website.

**The Options**

1. Keep the default set, so users are accommodated and instead focus on structuring the robots.txt (and perhaps .htaccess) file correctly, so you can let Search Engines know what's happening.
2. Look into the Rules and Context contributed modules to see if you can create a solution using those interfaces. You may or may not be able to find a solution there, but it might be a good start.
3. Create a module, which will handle non-existent URL's and correctly reroute them to 404 page.

# Answer
> 0 votes
Check the box to specify valdation criteria in the settings for the contextual filter. If one of the basic options works, great, or worst case, you can choose "PHP Code" and have it do whatever you want.

# Answer
> 0 votes
I think you should be able to get this to work by using the Rules module (suggested as one of the options in another answer also already).

Depending on how the format of your URLs look like, you may want to also use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For more details, refer to my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?".

---
Tags: 7, views, redirection, path-aliases
---


title: Block layout - List of all blocks

text:
# Question
Title: Block layout - List of all blocks
I'm having a question about the Block layout in Drupal 8. A couple of months ago (I don't know which beta it was) the block layout looked like this:

As you can see there's a list of blocks at the right of the page. Now in the current beta of Drupal 8 (beta 14) it looks like this:

The list of all blocks is gone. Why did they deleted this? And is there an easy way to get this back?

# Answer
> 3 votes
The same list shows up when you click on Place block. Doesn't look quite the same, but it is.

It was moved because they did UX testing and not a single person managed to place a block in D8, they all completely ignored the right sidebar. So a different solution had to be found, which is currently definitely not very nice yet.

This is the issue: #2513580: Implement the new block layout design to emphasize the primary interaction of placing a block

---
Tags: blocks, 8
---


# Question
Title: Web Services - GET Request Article (HAL+JSON)
I'm trying to make a **GET request** to a specific article on my drupal 8 website (local). These are the steps I've done:

1. Enabled all 4 Web Services modules at the modules page
2. Created an article (url: http://dp8studyxb14copy.dev/node/4)
3. Changed permissions for **Access GET on Content resource** for all users (also Anonymous Users)
4. Installed REST UI module.
5. Changed settings for content nodes (admin/config/services/rest/resource/entity%3Anode/edit)
    6. Make a GET request

But the problem is as you can see is that he returns HTML... . Now when I make a REST export view with a list of articles it works ... But not from a node itself.. .

What am I doing wrong?

# Answer
> 2 votes
Drupal 8 doesn't use accept headers for this anymore because it was problematic for caching.
Use *?\_format=hal\_json* instead.

---
Tags: services, 8
---


# Question
Title: Where does the variable for the left sidebar get set in Drupal 6?
I have a Drupal 6 site where I've added a submenu for a new set of products:

```
products
-old products set 1
-old products set 2
-new products set
--new product 1
--new product 2
--new product 3

```

that goes to a page where that link then becomes a main menu item:

```
new products set
-new product 1
-new product 2
-new product 3

```

I found the code:

```
$variables['layout'] = 'none';
if (!empty($variables['left'])) {
  $variables['layout'] = 'left';
}

```

in the template\_preprocess\_page function in the theme.inc file.

On the main menu page, the left sidebar appears with the menu block in it ($variables\['left'\] is turned on) but on the submenu page, it is not appearing ($variables\['left'\] is turned off). The menu block has both pages listed on the 'page specific visibility settings'. I'm trying to figure out why the difference but the problem is I cannot find where $variables\['left'\] ever gets set prior to that in the code. Any idea ??

# Answer
I ended up changing the menu block settings from having the 'fixed parent item' at the top level with 'starting level' set to 2nd to having the 'fixed parent item' at 'new products set' with 'starting level' to 1st. Now they both work fine.
> 0 votes

---
Tags: theming, configuration
---


# Question
Title: Entity reference : show fields instead of Label
Each user has a personal calendar (tab in profile from Views) where they can add "Event" content-type. I have a Entity reference field where the user can add 5 different "friends" to this "Event".

With Entity Reference view Widget I have a view (Picture and user name) from which the user can add up to 5 people. And it works, but...

How can I have more than just the Label? I would like to have the user picture and his name.

I've tried for 2 days... Please help. Maybe Entity Referennce is not the solution.

Thanks.

# Answer
> 1 votes
Might want to check the display settings (IE: Manage Display) of both the referencing and referenced entity. Haven't used it in a while, but definitely worth a look.

---
Tags: entities
---


# Question
Title: How do I add onclick Google Analtyics custom event "add to cart" to add to cart button in Drupal Commerce?
I want to fire a Google Analytics custom event called "add to cart" when someone adds a product to the cart.

I am using classic Google Analytics, not Universal.

I tried adding this to the `commmerce_add_to_cart_confirmation.js`:

```
_gaq.push(['_trackEvent', 'Button', 'Add to Cart']);

```

Didn't work.

Then I found the module that builds the add to cart form, commmerce\_cart.module, and updated it to go from this:

```
else {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add to cart'),
    '#weight' => 50,
  );

```

to this:

```
else {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add to cart'),
    '#onclick' => "_gaq.push(['_trackEvent', 'Button', 'Add to Cart']);"
    '#weight' => 50,
  );

```

That didn't work either. I would have preferred the former because the confirmation overlay only is presented when the add to cart is successful, whereas the latter would fire the custom event every time the add to cart button is clicked, even if there was an error.

Any help would be appreciated.

# Answer
> 0 votes
Sorry for updating, but you can easily add code before sending form!

It's in **sites/all/modules/uc\_ajax\_cart/js/uc\_ajax\_cart.js:70**

Just put your request after

```
beforeSubmit : function () {

```

---
Tags: commerce, javascript, google-analytics
---


# Question
Title: What happens to Webform data when a component is deleted? Can I change a component type?
I inherited a complicated Webform with several hundred submissions. One of the components was a Textfield used to capture the email address of the form submitter. For some reason this is a Textfield and not an E-mail field which prevents me from using the E-mail address to send a confirmation email.

If I were to delete the textfield email component what would happen to all the data? I'm assuming it would be erased.

Is there any way to change the type of a form component while still preserving the data?

Update: I am using Drupal 7 and Webform 3.19

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

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

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

# Answer
Consider if you really need the data structure intact or not, or if you just need the data preserved. Are you using the webform data in a view? Is anyone dependent on the automated 'Analysis' that Webform provides?

If you only need to send confirmation emails for new submissions, then add the new field with the same labeling, a different key and the correct type, and then suppress the original field by marking it as 'Private' in the field settings.

Private fields are shown to users who have access to results, so this may not work for your use case.

Alternatively, use the Node Clone module to clone the webform and change that field without either losing data or having to re-key everything.
> 2 votes

# Answer
If the field you delete is unique to a content type, then the field is gone from the database (that includes it's data). If you delete a shared field from, the field is removed from that content type along with the data unique to the content type.

If you find that you need to keep the data associated with the field but you need a different type of field for the data, you need to plan ahead.

* Create the new field.
* Devise a way to migrate the data from the old field to the new field.
* Delete the old field.

A good solution might be to use Feeds module (to import to fields) and Views Data Export Module (to export fields to the spreadsheet). The procedure would be:

Setup a view that lists all of your textfield values and displays all of the fields you want to migrate. Then data export and choose CSV format.

Use feeds to import the data to D7. Just map each exported field to your preferred field.

on the other hand you might want to read this tutorial too
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How do I show a list of users and display only partial email addresses?
I have created a list of users with views and I can add the user email field. However, I don't want to show the full email address. Instead, I would like to show the first few letters followed by \****@domain.com. (e.g. patr\***@gmail.com or kell\******@yahoo.com)

The purpose is to help users remember what email address they used when creating an account without revealing the full address.

# Answer
My solution for this is to go with adding a Views handler to the email field. The idea is to add a checkbox maybe saying "Mask part of the email address".

So you need to:

1. Check the Views field handlers page for reference.
2. You will see that there is a field handler for the user email which is called views\_handler\_field\_user\_mail. So this is what we need to add some settings and logic to "mask" parts of the email address.

That would be it. All you need to study now is how to structure and create the handlers and you can search for the guide you understand most but this(Drupal 7 Views 3 custom field handler) contains a good sample code too.

Of course the logic of masking the string/email will be all you already depending on your preferences or requirements.
> 0 votes

---
Tags: views
---


title: Reset the cart if same product is added

text:
# Question
Title: Reset the cart if same product is added
I am using Drupal Commerce in that user can add a product to cart. If user add same product for five times, cart contains same product for five times. What I need is when user adds same product again and again it should reset to 1. I have include the following lines still I am getting the same.

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

   $form_state['line_item']->data['context']['add_to_cart_combine'] = TRUE;

   return $form;

}

```

# Answer
> 1 votes
Here you can find the solution for restricting duplicated items to the cart.

Solution is

1. Create rule, name it; Event: before adding a product to the cart
2. You can add there conditions if you wish. I am chcecking here is product is digital or not.
3. In Actions add Loop through commerce-order:commerce-line-items
4. Create component, single rule, name it
5. Create following variables of the component and name them as you wish:
    * Commerce line item (line item of the order from the loop of the main rule)
    * Commerce product (product added to the cart)
6. Add condition to the component: Entity has field, Entity: \[line-item-in-order\], Field: commerce\_product. this will bring us the product from actual line item in current order (shopping cart).
7. Add condition to the component: Data comparison. Data to compare: line-item-in-order:commerce-product with product-added-to-cart (variable brought from the main rule)
8. Add action to the component: Remove an item from a list. List: \[order:commerce-line-items\], Item to remove: \[line-item-in-order\]. This will completely remove duplicated product from the shopping cart and from the order as well.
9. Eventually add another actions. At least Display some message to the user to inform him/her that the item has been removed sounds sensible.
10. Come back to your main rule created in step 1. Add action to the loop and select the component you have just created in steps 4. - 9. and set the variables.
11. You are done. Chcek it, it should work

---
Tags: 7, commerce
---


title: Module admin configuration permission

text:
# Question
Title: Module admin configuration permission
I have a custom module, `saidbakr_tools` and I want to apply permissions to access its administration page found `admin/config/administration/saidbakr_tools`. All what I have to got from the official module tutorial is to prevent access to it by preventing access to the admin pages.

The code I am using is the following one.

```
function saidbakr_tools_menu() {
  $items = array();

  $items['admin/config/administration/saidbakr_tools'] = array(
    'title' => 'SaidBakr Tools',
    'description' => 'Settings for SaidBakr Tools!',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('saidbakr_tools_form'),
    'access arguments' => array('administer saidbakr_tools'),
    'type' => MENU_NORMAL_ITEM,
  );

/**
 * Implements hook_permission().
 */
function saidbakr_tools_permission() {
  return array(
    'administer saidbakr_tools' => array(
      'title' => t('Access content for the SaidBakr Tools module'),
    )
  );

```

I cannot prevent other users with access to administrative pages to access the configuration form for my module.

Is there any error in my code? How can I achieve what I am trying to do?

# Answer
> 1 votes
Since you're not declaring an access callback, the access callback defaults to the `user_access()` and passes your access argument into it based on the `hook_menu()`.

Now, when we check the code of `user_access()`, we notice the following code.

```
// User #1 has all privileges:
if ($account->uid == 1) {
  return TRUE;
}

```

So the first created admin account will always have access. You then said:

> But I could not able to prevent other Role's users that has access to admin pages from accessing its configurations,

If you added another user with the Administrator role, and the permission is unchecked for the Administrator role in the Permissions page, your code should work and I can confirm it. So please check if:

1. You have the permission unchecked
2. You have cleared all caches or maybe just the menu cache
3. The admin user you are currently using to test the page's access is NOT the first admin user created

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


# Question
Title: How to get the nid for a newly created node?
If I've created a node in an install hook, how can I immediately get a reference to the `nid` property? It doesn't appear to be set on the entity during save.

```
use Drupal\node\Entity\Node;

function my_frontpage_install() {
    $node = Node::create(array(
        'type' => 'page',
        'title' => t('Welcome'),
        'body' => array(array(
            'value' => 'Hi there'
        )),
    ));

    $node->save();

    $siteConfig = \Drupal::service('config.factory')->getEditable('system.site');
    $pageConfig = $siteConfig->get('page');
    $pageConfig['front'] = 'node/' . $node->getId(); // this returns null
    $siteConfig->set('page', $pageConfig);
    $siteConfig->save();
}

```

I've tried variations on the theme of `getId`, `getNid()`, `get('nid')`, `getOriginalId()`, but if I dump out the node object afer saving, the nid property is clearly not set.

# Answer
> 11 votes
The nice thing about Drupal 8, is that it's object oriented, with interfaces, abstract classes etc.

This means that all entities share a lot of methods. To get the id of a node, use the `id` method

```
$nid = $node->id();

```

This also works for users, taxonomy terms and any other entities you create yourself or get from contrib modules modules.

For Drupal 8 development, using an IDE becomes really powerfull as it can help you with what available methods, various instances of classes has.

---
Tags: nodes, entities, 8
---


title: Media 7.0-2.x and Plupload

text:
# Question
Title: Media 7.0-2.x and Plupload
Is there any combination of Media module in version 2.x for Drupal 7 which works with Plupload Integration of any version?

I installed the newest `dev` versions of `File entity`, `Media` and `Plupload` but they don't work togheter.

Is there any other Bulk upload for Media which already works with version 2.x?

Are there any patches I can apply to get Media togheter with Plupload working?

# Answer
> 1 votes
It's been a little while for me and it was tricky at the time, but enabling these modules should help:

There was an additional patch to Media and a plethora of other issues (mostly related to permissions and editing files) that I noted as resolved as of 2014-Sep.

As you point out in the comments, a patch to the Media Multiselect module was still required to get the most recent dev versions of Plupload and Media 2.x working together by changing the widget type to that provided by Media Multiselect:

Patch (required for now but under review): Issue #2216273: Latest media changes break the multiselect (Comment #52)

Cheers -

# Answer
> 0 votes
maybe the file field sources module works with media - i did not check yet.

# Answer
> 0 votes
For the media module, I believe the issue to follow is https://www.drupal.org/node/951004

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


title: Reorder Javascript loading in theme?

text:
# Question
Title: Reorder Javascript loading in theme?
Some modules insert JavaScript at top of list. I put my $sctipts variable at the bottom of html.tpl.php file just before the closing of body tag. Due to this, some scripts do not work as they get called before jquery or drupal.js . Please provide steps to reorder list of js. I tried this code in my template.php but with no effect:

```
function MYTHEME_js_alter(&$javascript) {
  $javascript['sites/all/modules/syntaxhighlighter/syntaxhighlighter.min.js']['group'] = 500;
  $javascript['sites/all/modules/syntaxhighlighter/syntaxhighlighter.min.js']['weight'] = 500;
}

```

**Solved. I did this**: enabled AdvAgg Modifier, Advanced CSS/JS Aggregation. Then I visited settings page /admin/config/development/performance/advagg/mod where I checked options: Enable preprocess on all JS, Move all inline scripts to the bottom of the execution order, Move all browser conditional JavaScript to the bottom of the group, Move JS to the footer - All. And now i have all JS in the bottom (as google recommends), without need to chane html.tpl.php

# Answer
Solved. I did this: enabled AdvAgg Modifier, Advanced CSS/JS Aggregation. Then I visited settings page

/admin/config/development/performance/advagg/mod

where I checked options:

* Enable preprocess on all JS,
* Move all inline scripts to the bottom of the execution order,
* Move all browser conditional JavaScript to the bottom of the group,
* Move JS to the footer - All.

And now i have all JS in the bottom (as google recommends), without need to chane html.tpl.php
> 0 votes

---
Tags: javascript
---


title: How to show field in snippet?

text:
# Question
Title: How to show field in snippet?
I use PHP filter module, and write this in other field in my node:

```
<?php
  $node = node_load(52);
  $field = field_view_field('node', $node, 'myfield');
  print $field;
?>

```

It doesnt work. And how i can load id for node?

# Answer
field\_view\_field returns a renderable array for the field value. So you should use render() function:

```
<?php
  $node = node_load(52);
  $field = field_view_field('node', $node, 'myfield');
  print render($field);
?>

```
> 2 votes

---
Tags: entities
---


# Question
Title: Why is file_create_url() returning inconsistent values?
I'm experiencing an inconsistent behaviour in Drupal 7 on the function `file_create_url()`. I have one field collection with 4 fields in it. On the first field the function provides the correct file url. For the other 3 fields it displays only first part of url. How can I get rid of this?

Here is my code:

```
<video controls="controls"  autoplay="autoplay" poster="<?php print file_create_url($content["field_poster"][0]["#item"]["uri"]); ?>" style="width:100%"   >
  <source src="<?php print file_create_url($content["field_mp4"][0]["#item"]["uri"]); ?>" type="video/mp4" />
  <source src="<?php print file_create_url($content["field_webm"][0]["#item"]["uri"]); ?>" type="video/webm" />
  <source src="<?php print file_create_url($content["field_ogg_theora"][0]["#item"]["uri"]); ?>" type="video/ogg" />
</video>

```

And here is the result: *field\_poster* is fine but the others fail;

```
<?php print_r($content["field_poster"][0]); print_r($content["field_mp4"][0]); ?>

```

leads to...

```
            Array
(
[#theme] => image_formatter
[#item] => Array
    (
        [fid] => 288
        [uid] => 1
        [filename] => Transgourmet_Waldputen_MASTER.jpg
        [uri] => public://Transgourmet_Waldputen_MASTER.jpg
        [filemime] => image/jpeg
        [filesize] => 65241
        [status] => 1
        [timestamp] => 1440456242
        [type] => image
        [rdf_mapping] => Array
            (
            )

        [image_dimensions] => Array
            (
                [width] => 1008
                [height] => 573
            )

        [alt] =>
        [title] =>
        [width] => 1008
        [height] => 573
    )

[#image_style] =>
[#path] =>
)
Array
(
[#theme] => file_link
[#file] => stdClass Object
    (
        [fid] => 289
        [uid] => 1
        [filename] => Transgourmet_Waldputen_MASTER.m4v
        [uri] => public://Transgourmet_Waldputen_MASTER.m4v
        [filemime] => video/x-m4v
        [filesize] => 34256348
        [status] => 1
        [timestamp] => 1440457177
        [type] => video
        [rdf_mapping] => Array
            (
            )

        [display] => 1
        [description] =>
    )

)

```

Is it possible that is has to do with the mime-types?

Thanks in advance.

# Answer
> 1 votes
For each of the video files, this (for example):

```
$content["field_mp4"][0]['#item']['uri']

```

should be this:

```
$content["field_mp4"][0]['#file']->uri

```

Change `#item` to `#file` and change the syntax to reference an object instead of an array.

---
Tags: uri, media, files
---


title: Slow running script in IE8

text:
# Question
Title: Slow running script in IE8
So I've got this "nice" Drupal 7 site and there is a node with a large (70is) fields that the user fills in. There is a script that hides and shows certain questions depending on the previous answer. It works fine in IE9, FF, Chrome and Safari but in IE8 it gives this error:

> A script on this page is causing Internet Explorer to run slowly. If it continues to run, your computer might become unresponsive.
>
> Stop running script? YES/NO

There are only around 10 lines of my code being run, the rest is written out by Drupal. Is there a way to split up the script or speed it up? Or should I avoid using Drupal to write javascript and custom code it?

**EXAMPLE**

In the node/add I have code like this:

```
$form['group_section_one']['field_permit_number']['#states'] = array(
        'visible' => array(
            ':input[name="field_do_you_have_a_permit[und]"]' => array('value' => '1'),
        )
    );

```

To show the "permit number" field if they answer Yes to "Do you have a permit?". I do a similar thing for another 60 fields sometimes they depend on up to 4 field values.

That then writes out javascript which equates to around 100 lines all up. I wouldn't have thought that would freeze up the browser though...

# Answer
The tough thing here is that IE 8 is notoriously poor in terms of JS performance (compared to recent versions of FireFox, Chrome, Safari and even IE), and there's not a whole lot you can do to fix that.

However, in this case, I would consider one of two options:

1. Try to use different (faster) selectors besides `:input[name="field_name[und]"]` with Drupal's AJAX form states. If fields have IDs (they should, if the form is generated by Drupal), use the id instead, like `field_name`.
2. (If the above doesn't work) Try coding the visibility yourself (forgoing Drupal's FAPI #states system). You can optimize selectors and overall memory usage and performance by hand-tuning the jQuery or JavaScript yourself.

I'm guessing following #1 could fix your problem, though. For more reading on jQuery selector performance, see:

However, for a form as large as yours, even hand tuning the JS might not be enough to get rid of that warning in IE. I have one form on a site I work on that always pops up that warning, and we sadly just have to tell users to ignore it. It's annoying, but it's acceptable to tell users to dismiss the warning in this particular case.
> 4 votes

# Answer
i have used multistep module Multi Step to split long form into shot forms step by step.

I hope this helps you.
> 0 votes

---
Tags: 7, javascript, performance
---


# Question
Title: Filter condition for entity reference field
I am trying to create filter condition for entity reference field added, but i am unable see the data when i give input in created filter condition text, i am trying from long ago searching in all possible way but dint got the reason please let me know what could be the issue,i will be very thankful.

# Answer
> 0 votes
you can use **Views Reference Filter** Veiw Reference Filter Module for reference fileds.

---
Tags: views
---


# Question
Title: hook_menu shows in menu but not show page
I made module, and want to add settings page.

Menu Item appear in settings dashboard, but when try access page it display dashboard with menu items again, thought URL is correct.

```
return array(
    'admin/store/settings/vsl_spl'=> array(
        'title' => 'SPL Settings',
        'description' => 'SPL Settings Page',
        'page_callback' => 'vsl_spl_page_test',
        'type' => MENU_NORMAL_ITEM,
        "access arguments" => array('access administration pages'),
        'position' => 'left',
        'weight' => 10,
    ),
)

```

and callback function is just for test yet

```
function vsl_spl_page_test(){
    return '<h1>Test</h1>';
}

```

Page opens with status 200 but content is wrong.

# Answer
> 2 votes
It's just a typo. Remove the underscore from `page_callback`.

---
Tags: 7, routes, hooks
---


# Question
Title: Line breaks are stripped by ckeditor after saving a node programmatically
I'm setting a value to a long text using this code :

```
$node->language = $language->language; // Or e.g. 'en' if locale is enabled
$node->field_job_description[$field_langcode][0]['value'] = $description;
$node->field_job_description[$field_langcode][0]['format']  = 'filtered_html';
$node->field_job_description[$field_langcode][0]['save_value']  = $description;

```

When viewing the node the line breaks are showing, when I edit this node using ckeditor all link breaks are automatically removed

# Answer
> 1 votes
I would try disabling the Advanced Content Filter in CKEditor as a starting point.

In a typical scenario, most people are exclusively using CKEditor to set and update their field values, so the content stays exactly the same between viewing and editing the node, which is the behavior you're expecting.

However, since you are setting the field programmatically, when you edit the node it's the first time CKEditor is seeing the field value (i.e. the first time CKEditor filters are being run). CKEditor will filter and "correct" your HTML to its standards, so it's not safe to assume your field value will be untouched if it's the first time CKEditor is seeing it.

Your options are to 1) tweak how CKEditor filters your HTML, or 2) conform the HTML you're programmatically saving to the CKEditor standards.

# Answer
> 0 votes
I have the same problem from importing from a CVS. I was using wysiwyg module and wysiwyg linebreaks module mentioned above but needed to switch to ckeditor for Media 2.0 module.

I found that you can patch ckeditor module include includes/ckeditor.utils.js

here is the thread on drupal.org with the patch \[D7\] Linebreaks converter for CKEditor toggle mode https://www.drupal.org/node/1084924

this works when opening the node edit form. you can't switch to plain text however as the break and paragraph tags added are retained.

# Answer
> 0 votes
Under `admin/config/content/formats/filtered_html` add the breaks tag at the very bottom inside the **Allowed HTML tags** vertical tab.

---
Tags: wysiwyg, nodes
---


# Question
Title: How to send email to multiple recipients on creation of new node using rules module?
I have created one node type. Now, I want to send an email to multiple recipients on creation of new node using rules module.

# Answer
> 2 votes
To send emails to multiple persons on creating a new node, you have to create a new rule and follow these steps :

1. Create an event `After saving a new content type` and then select that particular content type.
2. After that add an action from `Select the action to add` select list and choose `Send Email`.
3. After that you can add multiple email ids in the `To` textarea separated by comma and space like this :

first\_email@mail.com, second@mail.com, third@mail.com

---
Tags: rules
---


title: Theming node add form

text:
# Question
Title: Theming node add form
I have a content type 'project' and I want to theme the node add form for this content type, I tried to create a page--node--add-project.tpl.php but I don't have the list of form element to render in this file. devel\_themer don't print the variables list in the node add page thanks

# Answer
> 0 votes
You can use following code in your template.php

```
/**
* Implements hook_theme().
*/
function mytheme_theme($existing, $type, $theme, $path) {
    return array(
        'project_node_form' => array(
        'render element' => 'form',
        'template' => 'project-node-form',
       // this will set to module/theme path by default:
       'path' => drupal_get_path('theme', 'mytheme') . '/templates',
     ),
  );
}

```

Place project-node-form.tpl.php in your themes templates directory.

# Answer
> 0 votes
On the page level forms are rendered and so you cannot get its elements. You will need to implement a hook\_theme function in template.php file where you define the path of the template file and also implement preprocess function if required.

You can see a detailed explaination here .. Theming Forms with Template file

---
Tags: theming
---


# Question
Title: Item pagination - fatal error: allowed memory exhausted
I have an `$items` array that I was displaying with my template file. Now I want to add a pagination, therefore the code looks like this:

```
    $current_page = pager_default_initialize(count($items), 4);
    $chunks = array_chunk($items, 4, TRUE);

    return theme('activit_item_list_block', array('title' => $title, 'subtitle' => $subtitle, 'items' => $chunks[$current_page])).
           theme('pager', array('quantity', count($items)));

```

but now im getting error:

> Fatal error: Allowed memory size of 1342177280 bytes exhausted (tried to allocate 40961 bytes) in C:\xampp\htdocs\grantexpert\includes\theme.inc on line 1514

Can't find out what I'm doing wrong, the code is identical with few examples that i found on internet. There is only 5 items in `$items` array.

**activit\_item\_list\_block:**

```
    <?php $countinrow = 0; $itemcount = count($items); $counter = 0; ?>

    <div id="item-list">

            <div class="description"><?php echo rip_tags($subtitle); ?></div>

            <div class="cont">

                <?php foreach($items as $item) { ?><!--

                row

            --><?php $countinrow++; $counter++; if ($countinrow==1) { ?><div class="row"><?php } ?><!--

                        item

                 --><article class="item one-quarter">

                            <img src="http://lorempixel.com/300/110/">

                            <div class="cont">
                                <header>
                                    <h3><?php echo $item['title']; ?></h3>
                                </header>
                                <div class="text">
                                    <?php echo $item['text']; ?>
                                </div>
                            </div>

                            <a class="button btn-small" href="/<?php echo $item['link']; ?>">Viac informácií</a>

                        </article><!--

                        END OF item

             --><?php if ($countinrow==4 || $counter==$itemcount) { $countinrow = 0; ?></div><?php } ?><!-- END OF row

                <?php } ?>

     --></div>

    </div>

```

# Answer
I'm not sure what theme\_activit\_item\_list\_block() is but I suspect you want this:

```
theme('pager', array('quantity' => count($items)));

```

instead of this:

```
theme('pager', array('quantity', count($items)));

```
> 1 votes

---
Tags: theming, paging
---


title: Adding <a href ..> around link or mail

text:
# Question
Title: Adding <a href ..> around link or mail
I have a custom module which prints html in *hook\_block\_view*. The text that my *hook\_block\_view* returns(in *block\['content'\]*) might contain links and mail addresses. Is there a drupal(or PHP) function that wraps the links/mail id in  ?

# Answer
> 1 votes
You can configure one of your text formats to use the "Convert URLs into links" filter, then to apply that text format to some text you can use the check\_markup() function like this:

```
// Run text through the Filtered HTML text format.
$formatted_text = check_markup($original_text, 'filtered_html');

```

You can change 'filtered\_html' to be whichever text format you want to apply.
Note that it will run all the other filters of that text format on the text also.

---
Tags: navigation
---