title: call js in html.tpl.php

text:
# Question
Title: call js in html.tpl.php
I want to add smoothstate script to my pages. I have to call 2 files at the bottom just before closing body-tag. Smoothstate.js and Functions.js. How can I call those 2 js in my html.tpl.php

```
<script src="js/jquery.smoothState.js"></script>
<script src="js/functions.js"></script>

```

Smoothstate.js

# Answer
Its too simple my friend. For these types of manipulations template\_process\_html(&$variables) comes handy. This is provided by theme.inc located in includes/ folder of your drupal directory.

You can put this function in your template.php file of your custom theme directory

```
/**
 *Implementing template_process_html()
 */

function custom_theme_process_html(&$variables) {
    $path = drupal_get_path('theme','custom_theme');
    $variables['scripts'] .= '<script src="' . $path . '/js/jquery.smoothState.js"></script>
<script src="' . $path . '/js/functions.js"></script>';
}

```

> This will append these new scripts to your scripts variables that is rendered to `html.tpl.php` as `<script>` tags while processing it. Provided that you put these scripts in the js folder located in your theme folder . So the file path should be like this - `sites/all/custom/themes/custom_theme/js/functions.js`.

Don't forget to `clear the cache` as its a `new hook` in your `template.php` file and drupal won't execute that hook until you do that.

Hope that helps.
> 1 votes

# Answer
If you want the script available on every page and you are creating your own theme or sub theme, then you might as well add it to your theme.info file like this :

```
scripts[] = js/jquery.smoothState.js

```

more information about the .info file formatting here https://www.drupal.org/node/171205

But if you only want it to appear on a certain page you can use a preprocess function with some logic to decide when it should be called like this :

```
<?php
function MYTHEME_preprocess_page(&$vars) {
  if (arg(0) == 'node' && arg(1) == 99) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/js/jquery.smoothState.js', 'file');
  }
}
?>

```

However, as you stated you want them to be called at the bottom of the page, it is important that you state that in the drupal\_add\_js() call like this :

```
<?php
drupal_add_js($theme_path.'/js/jquery.smoothState.js', array('type' => 'file', 'scope' => 'footer')); ?>
?>

```

then it will be called in the footer rather than in `<head>`

There are plenty of example on the drupal\_add\_js docs page https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: Do I have to set a 'safe_value' with each textarea's field value when I set it programmatically?
Do I have to provide both 'value' & 'safe\_value'?

# Answer
No.

If you are adding field programmatically you only need to set `value`.

The `safe value` is generated when the field is loaded. It is the *value* passed through the function `_text_sanitize()` which in this case i think is called through `text_field_load()`

More information on the difference between them here :

Differences between value and safe\_value
> 2 votes

---
Tags: entities
---


# Question
Title: Is it acceptable to modify Drupal's composer.json file?
Drupal adheres to the best-practice of never modifying core.

Drupal 8 has a composer.json file built into core, if you need to add a third-party library, should you modify composer.json, or is there a better way to do this?

# Answer
It is possible to consume Drupal 8 into your own `composer.json` file:

```
{
    "name": "davidbarratt/mydrupalproject",
    "require": {
        "drupal/drupal": "8.*"
        "composer/installers": "1.*"
    },
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "drupal/drupal",
                "type": "drupal-core",
                "version": "8.0.0-dev",
                "source": {
                    "url": "http://git.drupal.org/project/drupal.git",
                    "type": "git",
                    "reference": "8.x"
                }
            }
        }
    ],
    "minimum-stability": "dev"
}

```

There's a pull request to `composer/installers`will allow installation of `drupal-core` project types: http://github.com/composer/installers/pull/38

Would love your input on the above pull request, as well as this other one in the queue that allows installation of modules/themes/profiles.

Another solution that currently works is the Composer Manager module, which facilitates `composer.json` use for modules. It's currently available for Drupal 7, and will be available for Drupal 8 once the Drupal 8 alpha releases are close.

Thanks a lot, Rob
> 5 votes

# Answer
There is also the Composer module that is a Drush wrapper to Composer. Your module can then supply its own composer file which Drush will use to download additional dependencies for your module -- or site if you use say at least 1 "custom" module for your drupal site.

I also recommend watching this Drupal8 / Composer seminar from DrupalCon Munich 2012: http://munich2012.drupal.org/content/drupal-has-dependencies-lets-manage-them
> 1 votes

# Answer
Yes.

It is acceptable to use Composer the way it's supposed to be used. :-)

Edit:

This package exists to help you manage your Composer-based Drupal project: https://github.com/drupal-composer/drupal-project
> 0 votes

---
Tags: 8, composer
---


# Question
Title: Commerce File won't let anyone download files
I've got a website running Drupal 7.32 with Drupal Commerce. I want to let users download files so I've got the Commerce Licence and Commerce File modules installed and I've them working for a while, and then I updated everything to the latest versions and now I can not download any files that have been licensed - even as the administrator. All I get is an access denied page whenever I try to click the download link, but the link does appear in the View for licensed files.

I have checked the permissions and everything there seems correct - and I've also look at the following issue, which is the issue I am having, with no avail: https://www.drupal.org/node/1288156

Does anyone have a solution to this problem or even a work around?

Thanks in advance

# Answer
> 0 votes
In case anybody else runs into this problem, I managed to solve this issue by applying a patch for the generation of the access token, found here.

In breif, the patch is needed because the latest update to the File Entity module (which Commerce File utilises) changes the way that access tokens are generated and Commerce File has not yet been updated to account for this.

---
Tags: 7, commerce, files
---


# Question
Title: Module recommendation needed for recurring monthly membership plan?
I’m building a site that features yoga/excercise videos and will require users to sign up as members which will require a recurring monthly payment. Could someone recommend which modules to use for this? i see there are a few different options available. Any experience with something like this or advice would much appreciated, thanks!

i also need to make these videos inaccessible to non-members, something else to consider

# Answer
> 1 votes
There are a few options available.

I've seen this: https://www.drupal.org/project/commerce\_recurring which integrates with Drupal commerce. It doesn't have a stable version though.

For something more stable, and which is independent of the Drupal commerce module, try Recurly https://www.drupal.org/project/recurly

Recurly is a 3rd party subscription billing system.

Using the Recurly roles module: https://www.drupal.org/project/recurly\_roles

You can have people subscribe to your website, and assign a paid membership user role after signup and subscription. If a user stops the subscription, then you can take away the role.

Then configure your videos to only be accessible to the paid member role.

---
Tags: commerce
---


# Question
Title: Drush installation problem - Non-empty values for magic_quotes_gpc
I have successfully installed and configured Drush and i am able to work with it.

Unfortunately, I am getting an error like this:

> The following restricted PHP modes have non-empty values: magic\_quotes\_gpc. This configuration is incompatible with drush.

I have tried this

```
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off

```

in my `php.ini` and still I am getting the error. What could be the reason? How can I fix this?

# Answer
> 5 votes
Here is how i managed to fix it.

Go to `drush/includes/environment.inc`

Changed the line 91 from

```
$ini_checks = array('safe_mode' => '', 'open_basedir' => '',
'disable_functions' => array('exec', 'system'), 'disable_classes' => '',
'magic_quotes_gpc' => '', 'magic_quotes_runtime' => '');

```

to

```
$ini_checks = array('safe_mode' => '', 'open_basedir' => '',
'disable_functions' => array('exec', 'system'));

```

# Answer
> 9 votes
Be sure you are editing the right php.ini file. As far as I recall the file used from PHP CLI could be different from the one used from PHP when running as Apache module; plus, Drush could use a completely different file, basing on its options, or settings.

To see which php.ini file Drush is using, use `drush status`. Drush can use a php.ini file that is saved in the $HOME/.drush, or /etc/drush directory; it can also use a drush.ini file present in the same directories. Alternatively, the path of a php.ini, or drush.ini file to use are taken respectively from the PHP\_INI, and DRUSH\_INI environment variables. (See the content of the README.txt file for more information.)

The function that checks the PHP settings in the php.ini file is \_drush\_environment\_check\_php\_ini(), which contains the following code.

```
  // Test to insure that certain php ini restrictions have not been enabled
  $prohibited_list = array();
  foreach ($ini_checks as $prohibited_mode => $disallowed_value) {
    $ini_value = ini_get($prohibited_mode);
    $invalid_value = FALSE;
    if (empty($disallowed_value)) {
      $invalid_value = !empty($ini_value);
    }
    else {
      foreach ($disallowed_value as $test_value) {
        if (strstr($ini_value, $test_value) !== FALSE) {
          $invalid_value = TRUE;
        }
      }
    }
    if ($invalid_value) {
      $prohibited_list[] = $prohibited_mode;
    }
  }

```

On my computer, the directive for which the error message is reported is set with the following line.

```
magic_quotes_gpc = Off

```

When I execute `dpm(ini_get('magic_quotes_gpc'));` I get 0 as output.

# Answer
> 1 votes
As your path suggests you are using PHP 5.4.4. and since PHP 5.4.0 the magic quotes are removed, so you should not even have this settings in you php.ini.

Try to comment them out and see if it helps.

Source: http://www.php.net/manual/en/security.magicquotes.php

# Answer
> 1 votes
I had to make sure to put the following in my `~/.drush/drush.ini` file.

```
magic_quotes_gpc = 0

```

instead of

```
magic_quotes_gpc = Off

```

# Answer
> 0 votes
While I know this is old and has been answered by some people, I have just installed the beta2 of Drush 6 and no longer have this issue.

```
pear channel-discover pear.drush.org
pear install drush/drush
pear install drush/drush-6.0.0

```

See http://drupal.org/project/drush for more info.

# Answer
> 0 votes
I know this is an old question. I was trying to setup Drupal 7.28 with Drush and facing same issue on my GoDaddy hosting. This is what I found and how I solved it:

# Found:

GoDaddy uses /web/config/php.ini which has set magic\_quotes\_gpc = On. Even when I switch between PHP 5.2 and 5.3 cli, it uses same .ini.

# Did not work:

1. Overwriting `magic_quotes_gpc = Off`, also`magic_quotes_gpc = 0` in /drush.ini, but still same error
2. Copied /web/config/php.ini to ~/html/drush-cli-php.ini (~/html is web root in GoDaddy), commented out/removed `magic_quotes_gpc` statement, and used php command:

```
php -c ~/html/drush-cli-php.ini

```

to make php use this new ini. drush uses this php. But `php -i` still showed /web/config/php.ini was the first config file.

# What worked:

Now I explicitly coded `magic_quotes_gpc = Off` in ~html/drush-cli-php.ini, and viola, it worked! This was the **only** parameter I coded in this ini, btw.

What I observed was, if the `magic_quotes_gpc` was overwritten to `Off` in drush.ini, it didn't work, possibly because the validation failure in drush happens before the override.

Hope this helps somebody. :)

# Answer
> 0 votes
I know this old post but what remove the error message for me was commenting out the "disable\_functions =" in the "Language Options"

---
Tags: drush
---


# Question
Title: Webform-CiviCRM integration: autocomplete employer
I set up a Webform for a Membership Application. I followed the instructions on this page for setting up an Autocomplete for the Organization the new Member belongs to:

http://wiki.civicrm.org/confluence/display/CRMDOC/Webform+CiviCRM+Integration#WebformCiviCRMIntegration-CurrentEmployer

This works fine when I am logged in (as an administrator), and it auto completes the organization name with options from the database.

But when I test the form when I'm logged out, it doesn't recognize any organization names that I know are in the CiviCRM. Furthermore, when I try to add a new organization it doesn't get added to the database.

Any ideas why this might be happening?

# Answer
> 10 votes
The anonymous user does not have permission to view contacts in your database. Be thankful for this default, it can save you from accidentally exposing your entire database to the world!

You can override this default by editing the "existing contact" field (from the webform tab) and unticking "Enforce Permissions". Typically you would also set one or more filters on that form (e.g. pick a group) to limit the autocomplete to just the organizations you want to expose.

---
Tags: webforms, ajax, civicrm
---


# Question
Title: context block visibility - disable block for certain role
I use drupal 6. I want to show a block for all users (anonymous, authenticated, all roles) except role XY and some paths. I use context module where it is easy to set path rules. However, setting rules does not work - I want to disable block for role XY but enable it for all other authenticated users. So I check all roles I have + authenticated users and leave role XY empty. This way it does not work, probably drupal thinks that all authenticates are all roles. What would be the way of achieving this? Thank you.

# Answer
> 14 votes
Perhaps this module might do the job for you https://www.drupal.org/project/hide\_block\_by\_role doing a quick google search suggests that this would be the ideal module for you

Hope that helps

Seamus

---
Tags: 6
---


# Question
Title: Cannot load array items in Views template
I am currently struggling to alter the output of a field inside a specific view template. I have a Taxonomy term I want to render using a `<h3>` over the default `<div>` that Views default gives us, and to accomplish this a Field template needs to be implemented, that encapsulates this field with said `<h3>`.

Okay, not a problem. But when I work with the template's row output, it gets hairy. I can't find a catch-all print statement that drills down into the field (which is a taxonomy term value) and retrieves the #title attribute.

```
$data = $row->{'field_field_article_type'};
print_r($data);

```

The Print\_R of the $data, which itself polls the field inside each row statement is as follows:

```
Array
(
    [0] => Array
        (
            [rendered] => Array
                (
                    [#type] => link
                    [#title] => Health
                    [#href] => taxonomy/term/18
                    [#options] => Array
                        (
                            [entity_type] => taxonomy_term
                            [entity] => stdClass Object
                                (
                                    [tid] => 18
                                    [vid] => 3
                                    [name] => Health
                                    [description] =>
                                    [format] =>
                                    [weight] => 0
                                    [vocabulary_machine_name] => content
                                    [rdf_mapping] => Array
                                        (
                                            [rdftype] => Array
                                                (
                                                    [0] => skos:Concept
                                                )

                                            [name] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => rdfs:label
                                                            [1] => skos:prefLabel
                                                        )

                                                )

                                            [description] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:definition
                                                        )

                                                )

                                            [vid] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:inScheme
                                                        )

                                                    [type] => rel
                                                )

                                            [parent] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:broader
                                                        )

                                                    [type] => rel
                                                )

                                        )

                                )

                            [attributes] => Array
                                (
                                    [typeof] => typeof="skos:Concept"
                                    [property] => property="rdfs:label skos:prefLabel"
                                    [datatype] =>
                                )

                        )

                    [#access] => 1
                    [#printed] => 1
                    [#pre_render] => Array
                        (
                            [0] => drupal_pre_render_link
                            [1] => drupal_pre_render_markup
                        )

                    [#markup] =>

```

I've tried a few variations to access the variable, but it typically returns null and with the mix of StdClasses and Arrays, its becoming tumultuous to access.

Does anyone here know any surefire ways to theme a field output? Am I going about this in the wrong manner? Should I alter an additional theme call in Views to accomplish this simple goal?

# Answer
> 0 votes
You should be able to do that inside the view itself instead of using a template. Click on the field of the term. Scroll down a little you will see `Rewrite results`. Expand that and click `Rewrite the output of this field`. Then expand `replacement patterns` and you will see tokens that are able to be used. Your rewrite would look similar to this:

```
<h3>[field_term_field_name]</h3>

```

---
Tags: 7, views, theming
---


# Question
Title: Create a node programmatically then reference an existing node to that node?
I'm using Drupal 7 and trying to create a node programmatically. Once the node has been created I would like to reference it to an existing node

I'm creating a node programmatically like below

```
$node = new stdClass();
$node->type = $type;
$node->title = $title;
$node->uid = $user->uid;
node_object_prepare($node);
//set field values
node_save($node);

```

Which works.

I would then like to update an existing node to reference the newly-created node. I basically load the existing node, get the node id from the newly created node and update the reference field, like below

```
$node2 = node_load($node2);

$node2->field_reference['und'][0] = array(
  'target_id' => $node,
  'target_type' => 'node',
);

node_save($node2);

drupal_goto("node/$node->nid");

```

I get two errors when I add the second part to the code Notice: Undefined property: stdClass::$nid in node\_tokens() Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase-\>execute()

The first part works, the second does not. I'm getting the id of $node2 through tokens.

How can I make this work?

# Answer
As for the second part, you need to pass node ID or array of node IDs to `node_load` function first argument.

Your code should look like the following:

```
$node2 = node_load($nid); // pass integer node ID or array of integers

$node2->field_reference['und'][0] = array(
  'target_id' => $node->nid, // pass integer node ID not node object
);

node_save($node2);

drupal_goto("node/{$node->nid}");

```
> 1 votes

# Answer
If you are using Drupal 7, I suggest to use `entity_type`, so you can easly create nodes by fetching a type of entity you have to add\[here in your case it is **node** type\]. Easy way and much suitable for your requirement.

If you are interested, look at my answer to the question Fetching more than id's of an entity using EntityFieldQuery on Drupal Answers. Once if you have created an `etity_type`, then it is up to you. You are always welcome to the world of entities.

Thank you.
> 0 votes

---
Tags: nodes
---


# Question
Title: Theme based altering of default image-style for the same node-type and view-mode
OK, After some research and since Domain\_views module seems to be a little bit buggy (printing always default Domain ID no matter what), I think this is the base question solving my problem the other way around with 2 domains and 2 themes using the same nodes from same node-type, but they both need different image-styles because of their 2 different themes:

***How do I alter the given image-style of a given node-type in its default full-node view-mode in the .tpl files of a theme, to have 2 different used image-styles in 2 different themes by the same node-type and the same view-mode?***

I've tried to find example themes doing it and I heard of Entity view mode to add custom view modes, but I am still not sure if I am on the right tracks. Actually I only need another image style (size) for the same node-type and the same view mode but in 2 different themes since Domain Access gives me hard times to solve this with conditional view modes or Views displays.

From what I understood there are 2 ways:

* a custom view mode for the same node type and a function in the theme telling the node-type to rather use this view mode
* or only a image-style altering in the node--full.tpl.php but I can't find a good example explaining it.

The very basic question to research for me is: how to alter image-styles in the code of the theme layer? Is this correct?

Any help would be very appreciated! Thank you very much for any hint.

# Answer
Well after reforming my question 3 times and rethinking what the actually question should be like to find a solution, I came to the conclusion that the Domain\_views module is completely broken (ALL Domain views fields always output the default Domain ID/name/path no matter what), and that the theme layer node--view-mode.tpl.php altering approach is not generic enough to have this functionality in other use-cases.

So I found a nice trick, which maybe also helps others to change field styles in a given steady node-type and same view mode under certain conditions, but it needs Views module:

Use the Views\_conditional module and use your fantasy to get the needed result. :-) That easy!

In my case I was able to turn off the Domain\_views module completely (finally!) and have used the absolute path setting from the content:path views field to change the image-style under the condition, that the path includes a given pattern of one of my domains. I have 2 image fields (excluded in Views) and a conditional field showing one of them if needed, e violá! :-) My image style changes in the 2 different domains by the same given node-type and node-view-mode! Awesome

Views as a full node view mode designer... I never stop learning. ;-)
> 0 votes

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


# Question
Title: Is it possible to disable (or reject) selection of parent terms in taxonomy reference fields at node creation or edit?
for instance, for a particular Vocab. and User Role..

Is it possible to achieve that in code? That parent terms will be rendered only as labels and not checkboxes?

Thanks.

# Answer
Taxonomy Term Reference Tree Widget allows you to disable the selection of parents. Hope this helps you out.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to show all terms with are used in Content?
I have Content type: Products. It has field (Brand) on taxonomy base. I use Views and want to see list of terms (all brand names) wich are used in my materials on the Product type base. I understand that it is possible to chose Taxonomy as base for Views building, but I want to build View on Content base.

# Answer
> 9 votes
Is this in Drupal 6 or Drupal 7? In Drupal 7, you should create a content view, use fields, and then in the fields section and select the relevant content field. This should then display all the various options that are selected.

# Answer
> 0 votes
I'm not sure which version you're running but using Drupal 7 and Views 7.x-3.7+ something like this would work:

1. Add a new view for you custom content type.
2. In the views edit screen under `format` change `show` from `content` to `fields`.
3. Under `fields` click add and search for `Content: All taxonomy terms`. In the popup for the new field you can check `Limit terms by vocabulary` and select the correct vocabulary.

In your case you could use the actual field `brand` instead of `Content: All Taxonomy Terms`.

# Answer
> -1 votes
I found that necessary point is using the Aggregation option; it will give only unique terms. The main point is taking out the "Sorting by date" option.

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


# Question
Title: unable to extract dumped files in .tar extention on my site
I can't extract my backup dumped with .tar extention. so i can't work with features can I download features in .zip ?

# Answer
> 1 votes
No. Tar is what's supported.

Downloading the files I generally feel is a pain though, I would encourage you to look at managing the features with Drush instead. It's often a lot faster as it mostly enables you to skip the whole download step.

---
Tags: migrations, features, importing-exporting, backups
---


# Question
Title: Is it possible to provide logins based on purchases?
There shall be an online shop with drupal commerce. It is required that a visitor can buy a digital product, i.e. a ticket with a barcode that he can print out. The visitor shall not be able to create an account.

The visitor must provide his email when buying a ticket. When the visitor finishes the payment process a pdf (a ticket with a barcode) and a unique id are generated (an id for that purchase if you will). A visitor can buy multiple tickets, but everything that is bought in one process has the same purchase id.

Is it possible to let that user "login" with his email and the generated id, given an overview of all the tickets the user bought related to that purchase id?

Background of this is: a user shall be able to see the bought tickets to be able to print them again. But one email address can be used several times, not meaning its everytime the same user.

**Example:**

Visitor `foo@bar.com` makes a purchase with 2 tickets, *`t1`* and *`t2`*, id *`abc`* is generated.

The visitor can then "login" using the credentials `foo@bar.com` and *`abc`* "as password", seeing tickets *`t1`* and *`t2`*.

Two days later, another visitor with the same email address makes another purchase, buying a ticket *`t3`* and generating the id *`def`*. Hours later, he wants to print the ticket again, he can login using the mail `foo@bar.com` and the "password" *`def`*, showing ticket *`t3`*.

If he used password *`abc`* instead, he would be shown tickets *`t1`* and *`t2`*.

# Answer
> 1 votes
YOu don't need a real login, just an access to a certain node. For this, you can use the Node autorize link module:

> Generates link for view, edit, or delete content without login

So, when someone pruchases something you must create a node tieh the data tue user can view. Add the view authorize link to the purchase email notification and the customer will have access to the node with data just following the emailed link.

---
Tags: commerce, users
---


# Question
Title: Adding new fields using hook_field_schema_alter()
I have an entity whose field schema is already defined and now I am trying to add couple of fields to it.

But I am not sure how to code it up using schema\_alter.Below is an example on how I would code the schema for the field using hook\_field\_schema().

```
function hook_field_schema($field){
  $columns = array();
  if($field['type'] == 'some_field_name'){
  $columns = array(
              'col1'=>array(
                     'type =>'text'
                     'size' => 'big'
                     'not null' => false),
              'col2'=>array(
                     'type =>'text'
                     'size' => 'big'
                     'not null' => false),
              );
  }
 //Similar for other fields
}

```

Confusion is on how to decompose this schema according to schema\_alter.

I am following this article to implement `hook_field_schema_alter()`

**Edit:** I am using an update function to create the field (`field_create_instance`), since this is an already an existing module and I do not want to disable it and enabled it again.

# Answer
You would need to call the `field_create_instance()` function passing a new array.

```
 $instance = array(
    'field_name' => 'field_my_custom', // ** This already exists, or check with field_info_field()
    'entity_type' => 'node',
    'label' => 'a label',
    'bundle' => $content_type,
    'widget' => array(), // if you're not sure about your widget settings, take a glimpse at an existing field instance using debug(field_info_instance(...));
);
field_create_instance($instance);

```

More links to read and better understand the above functions:

https://api.drupal.org/api/drupal/modules%21field%21field.info.inc/function/field\_info\_field/7 https://api.drupal.org/api/drupal/modules%21field%21field.info.inc/function/field\_info\_instance/7 https://api.drupal.org/api/drupal/modules%21field%21field.crud.inc/function/field\_create\_instance/7

Also, take a look at the Examples for Developers module, node example and field example.
> 0 votes

---
Tags: entities, database
---


title: A node in two different points

text:
# Question
Title: A node in two different points
I am using Drupal 7 and i have the following problem:

I have

* The content type: issue,
* Two views (which select nodes from the content type issue) with each view appearing from a different menu link
* Two menu blocks, each one of them appearing based on the view i have selected from the corresponding menu link

I want the titles of my view nodes to be links to the content of type issue. I want, by clicking on this title, one menu block (from the previous two) to be appearing based on the view I have clicked the title.

I can't solve this problem with two different aliases. Any ideas??

Examples: Here is the first case: I have a view which lists Issues nodes and the activity block is appearing on the left. By clicking on the titles, i go one more level inside and i have this result: Now, another view which lists the same Issues nodes,as above, exists in my site in a different point:. With this view, the resources menu block is appearing on the left. By clicking the titles from this view, i want to go one more level inside (as above) and display the resources menu block and not the activity menu block, as in the first case.

---

Following the instructions with **Contextual Filters** as follows, I have the following results:By clicking on a title from the first view : and by clicking on a title from the second view:

As we can see, although the appropriate blocks appearing in each case, but i don't see the original content that includes each view node.

*I thought that having two different url aliases for each view node the problem could be solved. But this couldn't be a solution, sine by testing this case if i click the title from any view, only the resources block is appearing. Apart from this, i want the URL aliases to be defined automatically and Pathauto module doesn't allow this functionality: for a content type to define two different patterns*

Any other ideas please???

# Answer
What if you rewrite the title field of your node results with HTML so that each title links to the view you have created? Your view already displays all nodes with category "issue".

**Edit:** To link your titles to the view, I assume that in your view fields you are able to see a filed that looks like "Content: Title (Title)". Click on the field and on the field edit for visit the section "Rewrite results" and check "Output this field as link". In the "Link path" field, fill in the path to your view. I think this will work

Now for your blocks you can configure them to appear only when your view is being displayed, e.g.

1. Configure block
2. Show block on specific pages:
3. Check "Only the listed pages":
4. In the field below enter "path\_to\_your\_view/\*"
> 1 votes

# Answer
It is not proper to have two paths for same node

You better create two different views with both listing of node and Details page connected by **Contextual filter**

Let me describe it

**In Existing View**

* Add `content:nid` field and exclude it from display
* In your node title listing page edit the field title and create a link to it as follows

**Create new View For Node Details Display**

* Now create another view with **Format:Content**
* Add a contextual filter `content:nid` which you get from the URL and define this new path as activities/%
* Repeat the same process for the other view too. So now you can get two different path to render your block
> 1 votes

---
Tags: views, nodes, blocks
---


# Question
Title: Taxonomy vocabulary not showing up as existing field in new content type
I have 2 taxonomy vocabularies which I want to reference in new content types but I cannot see them under "add existing fields" when creating a new content type. Also tried referencing one taxonomy vocabulary from another and couldn't.

Saw this post on drupal forum and followed the suggestion of changing admin theme but it didn't work for me.

BTW, I'm using Marinelli theme.

Kind regards,

Jio

# Answer
> 0 votes
To use taxonomy with your content nodes, you have to add fields to your content types that allow you to assign taxonomy terms. To add a field for your taxonomy to a content type:

1. Go to **Structure \> Content types**.
2. Find the listing for the content type you want to modify, and then click its **manage fields** link.
3. In the Add new field section, enter text for the **Label** and **Name** columns.
4. In the **Field type** column, select **Term reference** from the drop-down menu.
5. In the **Widget** column, use the drop-down menu to select from the following widgets:

```
  Check boxes/radio buttons - The taxonomy terms are listed in a check box on the content creation page for this content type.
  Select list - A list of the taxonomy terms are displayed on the creation page for this content type.
  Autocomplete term widget (tagging) - A text box is added to the content creation page for this content creation page.

```

Selected or entered taxonomy terms are assigned to the content node when the node is saved or published.
6. Click **Save**.
7. In the **Vocabulary** drop-down menu, select the vocabulary you want to use with this content type.
8. Click **Save settings**.

A taxonomy term field is added to your content type, using the label you chose. When you create content of this type, you will now find a field on the creation and edit forms that allows you to assign taxonomy terms to the content node.

Thank you.

---
Tags: nodes, taxonomy-terms
---


# Question
Title: How can I overwrite taxonomy field link output?
I am using Drupal 7 and the Views module. I made a very simple page showing nodes with the Views module, where I want to show only one field, which contains taxonomy terms.

I want to rewrite standard link from this page to my own variant. I selected "Rewrite results" and wrote my link. In the view, those links are not changed: they are going to taxonomy term pages.

I know that if I used a view showing taxonomy terms (not nodes), I could checkout the field for standard taxonomy output, but in a node view there is no such possibility.

# Answer
> 0 votes
You can do that like follows.

Go to your view and click on filed (having taxonomy) to change the settings.

1. Change the **Formatter** option to *plain text*. (If you choose Formatter as 'Link' that won't work even you write Rewrite Results')
2. Check *output this filed as link* and enter your path. Or you can also use'Rewrite the output of this filed'

That's it.

# Answer
> 0 votes
1. Find the machine name for your vocabulary. (`Hint`: go to admin/structure/taxonomy and click "edit" next to the vocabulary. The vocabulary's machine name will appear in the URL).
2. Copy **page.tpl.php** into your theme folder and rename it **page--vocabulary--\[machine name\].tpl.php**. Of course replace "\[machine name\]" with the actual machine name.
3. If **page.tpl.php** doesn't already exist in your theme folder, grab a copy from your base theme, if you are using one, or the modules/system folder. (If you are customizing more than one vocabulary, just repeat this step for each.)
4. Open **template.php** in your theme folder (create it if it doesn't exist) and paste in the function below. Replace "THEME" with the name of your theme.

By adding the below code, you are "suggesting" a new template be used that deals specifically with the vocabulary being loaded.

```
function THEME_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $term->vocabulary_machine_name;
  }
}

```
5. Clear all caches.

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


title: How to use cookies in Drupal?

text:
# Question
Title: How to use cookies in Drupal?
I am writing a module that allows users to put comment on each paragraph. So in my module I have added a new field to comment table called "paragraph\_id" and I have also added a new field to comment form that say:

```
 Which paragraph do you want to put comment on?

```

After each paragraph I have added a link saying:

```
  Put comment on paragraph 1 (2,3, ...., the number changed based on the number of the paragraph.

```

in order to this, I have written the following in node.tpl.php:

```
        for ($i=1;$i<$number;$i++) {

        print render($paragraphs[$i]);
       ?>

      <a href="#commenting">Put comment for Paragraph <?php echo $i?><br></a>

    <?php

```

I want to do one the following options:

1) Eliminate the new field which asks for the number of the paragraph from comment form, and do something that when a user for example clicks on a link like:

```
   Put comment on paragraph 1

```

, the number "1" automatically got save in comment table in "paragraph\_id" field.

2) Or keep the field that asks for paragraph number in comment form and when user clicks on a link like

```
 Put Comment on Paragraph 1

```

while he is getting directed to the comment form, the value of that field (paragraph\_number in comment form) sets to 1.

How can I do it?

# Answer
> 0 votes
Drupal automatically ensures that a user has a session, so your script can simply read and write to the $\_SESSION superglobal array.

# Answer
> 0 votes
To set the expiration value for your website's session cookies: Go to **Configuration \> Session expiration**.

Select from the following expiration options:

1. **Default (3 weeks 2 days)** \- Removes the session cookie from the user's computer 3 weeks and 2 days after creation.
2. **When the browser session is closed** \- Removes the session cookie from the user's computer when the user closes their browser.
3. **After a specific period of time** \- Removes the session cookie from the user's computer after an elapsed time period. Enter a time value that's based on your selected date unit (such as minutes or weeks).

Click **Save configuration**.

---
Tags: comments, cookies
---


# Question
Title: Drupal aligning blocks and content next to each other
i have a view page and two blocks which i want to display next to each other. I want view content on left and two blocks on right, with one block on top and other just below it. But i am having trouble in achieving the same. My html guy says its not possible to do that without a wrapper container as we need to have things in center as well.

I have omega 4 installed, so sidebar is also below the content block. Also i don't have consistent layout view, as on some pages i have only content with full screen background, and with no side content and on some i have content in which i am facing a problem.

I have searched on google and SO but every solution says to have a wrapper, which is not possible as placing a wrapper globally will limit the display on every screen, which i can't have.

One solution i can think of is use javascript to add classes on page load where i have two column display but it is not a good way to do that i believe.

How can i solve this, can anyone please help??

# Answer
You can make use of Panels Module to achieve any kind of Complex Layouts
> 1 votes

# Answer
My friend.

Your Html guy is right about the wrapper things.

Don't worry in drupal it is very simple to create a custom 'block-table-type' layout .

It is can be achieved by Panels and Minipanels.

Now, How will you do it ?

This markup your HTML guy needs will be generated in three easy steps

1. Download and enable the Panels and Mini panel module by going to admin/modules page. (You will get 5 new modules with this main module - panels\_node, panels\_mini, panels\_ipe, i18n\_panels, panels).

All these 5 modules hold their dependencies on \[ctools\] module which you need to download and enable before enabling these modules
2. Then go to Structure \> Mini Panel \> Add mini panel button and complete the simple creation wizard. **STEPS**. settings - Add the Administrative title for the minipanel. Hit next -\> Context- (Here You add the context for the mini panel - In our case we don't need it). Hit next. Then , Select the layout from the drop box.
3. Finally , Add the blocks or fields you want that minipanels in the different frames by selecting Add Content link comes when you will click on the cogwheel placed on the top right part. And hit save. Now you will get this mini panel as a block in your blocks list . Just go to structure \> blocks . This block will be a div which will wrap your other blocks (That you have added to it) in the proper markup your HTML guy needs ;). Now you just need to place this block to some region.

The beauty of this module is that you can add a minipanel into another mini panel and can accomplish any complex grid design. Moreover if you enable Panel Node module than you can add new node specific grid page , called panel variant n drupal way of speaking.

Hope this helps . Have fun !
> 1 votes

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


title: Migrating to a Field Collection

text:
# Question
Title: Migrating to a Field Collection
I'm working on a project that requires a CSV of speaking engagements to be migrated to Drupal. With Migrate, I've been able to migrate over basic fields, like name, title, etc.

However, the `speaker` field is a field collection, which is driving me nuts. While the field collection allows unlimited speakers, the CSV only has one per event. I've tried using the `node_insert` hook, as described here but to no avail. Is there a better/easier way to migrate a single speaker into the speaker field collection?

# Answer
There is a Field Collection issue with a Field Collection Migrate destination (in the patch in comment #222). The added `field_collection.migrate.inc` file contain a bit of documentation on how to use it.

In you case, I guess you have a speaking engagements migration class which load your CSV file and create Speaking engagement nodes. You will then need a speaker migration class to load the same CSV file and create Speaker field collections. This second migration class depends on the first one, so when a Speaker is created, it will be linked to its Speaking engagement.

Something like

```
class SpeakerMigration extends Migration {

  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->dependencies = array('SpeakingEngagementMigration');
    $this->source = new MigrateSourceCSV('path/to/speaking/engagement.csv', array(), array());
    $this->destination = new MigrateDestinationFieldCollection('field_speakers',array('host_entity_type' => 'node'));
    $this->map = new MigrateSQLMap($this->machineName, array(
      'id' => array(
        'type' => 'char',
        'length' => 40,
        'not null' => TRUE,
        'description' => t("Speaking Engagement's identifier"),
      )), MigrateDestinationFieldCollection::getKeySchema());
    $this->addFieldMapping('host_entity_id', 'id')
      ->sourceMigration('SpeakingEngagementMigration');

    // ... Add field mapping here.
  }
}

```
> 5 votes

# Answer
Another option is the implement the `complete` method of the `Migration` class and populate the field collection programmatically there.

```
public function complete($entity, $row) {

  // load the newly created node (just in case entity isn't fully populated).
  $node = node_load($entity->nid);

  // set the values of all field collection fields
  $values = array(
    'field_name' => 'FIELD_COLLECTION_ITEM_FIELD_NAME',
    'field1'     => array(LANGUAGE_NONE => array(array('value' => 'VALUE'))),
    'field3'     => array(LANGUAGE_NONE => array(array('value' => 'VALUE'))),
  );

  // create the field collection item entity
  $item = entity_create('field_collection_item', $values);

  // attach it to the node loaded above
  $item->setHostEntity('node', $node);

  // save the entity
  $item->save();
}

```

**NOTE**: If you are adding files to the field collection item, they will not be removed on a rollback unless you explicitly do that.
> 2 votes

---
Tags: 7, migrations, entities
---


# Question
Title: Migration into multi-value field collection
I am attempting to use the patch in comment #222 of this issue (https://drupal.org/node/1175082#comment-7625869) to migrate data into a multi-value field collection.

I create an array of the objects in prepareRow() but when the migration completes and I review the nodes, only the first item in the array has populated the field collection and no subsequent items have been added. Am I missing something important?

```
<?php
class IngredientsMigration extends BasicMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = t('Migrate recipe ingredients from the source database into field collections.');
    $this->dependencies = array('Recipe');

    $query = Database::getConnection('default', 'legacy')
      ->select('recipes', 'r')
      ->fields('r', array('id', 'ingredients'))
        ->condition('r.id', array(2), 'IN');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationFieldCollection(
      'field_collection_ingredients',
      array('host_entity_type' => 'node')
    );

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id' => array('type' => 'int',
          'length' => 11,
          'not null' => TRUE,
          'description' => 'Recipe ID',
          'alias' => 'r',
          ),
      ),
      MigrateDestinationFieldCollection::getKeySchema()
    );

    $this->addFieldMapping('host_entity_id', 'id')
      ->sourceMigration('Recipe')
      ->issueNumber(16);
    $this->addFieldMapping('field_ingredient_text', 'ingredients')
      ->description(t('See prepareRow method'))
      ->issueNumber(16);

    $this->addUnmigratedDestinations(array(
      'path',
      )
    );
  }

  public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    $ingredients_array = preg_split('/$\R?^/m', $row->ingredients);
    $row->ingredients = array();
    foreach ($ingredients_array as $ingredient) {
      $row->ingredients[] = $ingredient;
    }
    return TRUE;
  }
}

```

# Answer
I ended up writing a drush command to run before the migration that would take the 'ingredients' field from the source db and create a new table with the ingredients each parsed into their own row and a delta column to keep them in order. I then configured the ingredients migration to point to this table instead of the recipe table.

My DB connection for this migration ended up looking like the following:

```
$query = Database::getConnection('default', 'legacy')
  ->select('_recipe_ingredients', 'i')
    ->fields('i', array('id', 'recipe_id', 'ingredient'))
    ->orderBy('i.recipe_id')
    ->orderBy('i.delta');

```
> 1 votes

# Answer
You can also try this (also answered on this question: Migrating to a Field Collection):

Another option is the implement the `complete` method of the `Migration` class and populate the field collection programmatically there.

The following code will save a single field collection item to a node.

```
public function complete($entity, $row) {

  // load the newly created node (just in case entity isn't fully populated).
  $node = node_load($entity->nid);

  // set the values of all field collection fields
  $values = array(
    'field_name' => 'FIELD_COLLECTION_ITEM_FIELD_NAME',
    'field1'     => array(LANGUAGE_NONE => array(array('value' => 'VALUE'))),
    'field3'     => array(LANGUAGE_NONE => array(array('value' => 'VALUE'))),
  );

  // create the field collection item entity
  $item = entity_create('field_collection_item', $values);

  // attach it to the node loaded above
  $item->setHostEntity('node', $node);

  // save the entity
  $item->save();
}

```

You can modify it to save multiple field collection items fairly easily.

```
public function complete($entity, $row) {

  // load the newly created node (just in case entity isn't fully populated).
  $node = node_load($entity->nid);

  // loop values to add as field collection items (assumes you have them in a $values array).
  foreach ($values as $key => $value) {

    // set the values of all field collection fields
    $values = array(
      'field_name' => 'FIELD_COLLECTION_ITEM_FIELD_NAME',
      'field1'     => array(LANGUAGE_NONE => array(array('value' => 'VALUE'))),
      'field3'     => array(LANGUAGE_NONE => array(array('value' => 'VALUE'))),
    );

    // create the field collection item entity
    $item = entity_create('field_collection_item', $values);

    // attach it to the node loaded above
    $item->setHostEntity('node', $node);

    // save the entity
    $item->save();
  }
}

```

**NOTE**: If you are adding files to the field collection item, they will not be removed on a rollback unless you explicitly do that.
> 1 votes

---
Tags: 7, entities, migrations
---


# Question
Title: Using Drush site-install with multisite and a single database
I am trying to make a script that will create and configure a new multisite in a drupal 7 install using drush 5.8.

I have scripted creating the site folder and settings.php file manually and adding the database information (to get around a bug i was having with --db-url and sql server).

I am setting the dbprefix to be $newSite so that all the tables can live in the same database. The first thing drush site-install tries to do is drop ALL the tables in the database. This includes all the tables created with a different prefix in a previous install.

Is there any way to stop this from happening?

Thanks for your help in advance!

Joe

# Answer
this is how I do mine...

drush -y site-install standard --db-url=mysql://$username:$pass@127.0.0.1:3306/$dbname --site-name="$sitename" --sites-subdir="$sitename"

sitename for instance could be test.drupalserver.com and to keep it in good practice for dbs i strip out the periods and the $dbname would be test\_drupalserver\_com.

I believe the way my drush command works, it creates a new db that matches the name of the site.
> 4 votes

# Answer
FYI I am attempting to get this fix into the main Drush branch by adding the switch "db-drop-existing-tables" to the site-install method.

Here is the issue for you to follow: https://github.com/drush-ops/drush/issues/134
> 1 votes

---
Tags: drush, multi-sites, installation
---


title: Search result theming

text:
# Question
Title: Search result theming
I have problems configuring the search-result.tpl. Is it so, that the fields set in Search result view mode are always snippet'ized as plain text? I have for example a taxonomy term on each node, which I set to appear as link in the Search result view mode, yet it is always output as plain text.

I'm using Custom Search and Search API, if that matters.

# Answer
Assuming Drupal 7 here, which thankfully has more options for you that Drupal 6.

I don't recall the last time I fully traced this out (and it's complicated), but search\_excerpt does call strip\_tags and check\_plain.

You can take a look at search-result.tpl.php, template\_preprocess\_search\_result(), hook\_node\_search\_result() to see what your options are.

Personally, I would build up my own entries in `$variables` in the preprocess, and display them in the template. One option is to make a custom node view for the search results, uild it up with the UI, and then use this,something like:

```
function mytheme_preprocess_search_result (&$variables)
{
  $result = $variables['result'];
  $node = $result['node']; // not 100% positive that this is the right place in D7
  $variables['my_custom_search_result_view'] = node_view($node,
    'my_custom_search_result_view');
}

```

and then use `$my_custom_search_result_view` in search-result.tpl.php.

Not a full solution for you, but it should be a decent start.
> 1 votes

# Answer
You can learn much more about this issue here https://www.drupal.org/node/1166114
> 0 votes

---
Tags: search
---


# Question
Title: how to alter only one set of specific forms?
Consider I have 3 content type. The problem is that if I use form alter in a module , when I use:

```
drupal_set_message(t($form_id), 'status', FALSE);

```

in the mentioned hook, it shows me different set of form-IDs as message on showing each node add/edit form.

For example if I go to node type A add/edit form, drupal\_set\_message shows:

```
A_node_form

```

if I go to node type B add/edit form, drupal\_set\_message shows:

```
A_node_form
B_node_form

```

if I go to node type C add/edit form, drupal\_set\_message shows:

```
A_node_form
B_node_form
C_node_form

```

Showing them means that I can not really make an specific effect for each content type add/edit form by form\_alter.

Note: I use OG module and B and C are the content types and A is the group type.

How should I solve it?

# Answer
> 2 votes
In the case you need, so you can easily use control flow in your hook\_form\_alter

You know that the hook runs everytime a form is willing to be rendered, so you can easily do something like

```
hook_form_alter(&$form, &$form_state, $form_id){

if($form_id == 'A_node_form'){...}//alter form A

if($form_id == 'B_node_form'){...}//alter form B

if($form_id == 'C_node_form'){...}//alter form C

}

```

---
Tags: 7, forms
---


# Question
Title: Pull webform submissions in different webistes to one end-point
hypothetical example:

website1 has 2 webforms, I need to access the submissions of the 2 webforms in another website2

So if an user send the webform in website1 I need to log in as admin in website2 and see that submission. In few words, pull the webform submissions to one endpoint website (without the necessity of click a button or run a command), Master-Slave where the slave is the endpoint website that is only going to show results of webforms.

is this possible?

My use case: I have a lot of surveys in different websites hosted in different servers, I need an endpoint where to collect all the results and show it to my users, so I need have the submissions stored in my endpoint website for show results to my users.

Thanks

# Answer
A stupid and simple approach (that scales badly) would be to use drush sql-sync.

Since you can give it the `--tables-list` option, you can get it to transfer only the appropriate tables. And because drush will use rsync for transfer, the network transfer is not going to be very large, since only changes well be moved.

It will however drop and recreate the tables everytime, and this might not be acceptable.
> 1 votes

# Answer
Ultimately, there are several ways to accomplish a 'sync' across multiple sites. However, without more technical information the options are generic at best. Webforms that include uploads or images may require additional work to configure.

Bottom line, the webform data lives in a table in the database, on each site. The best solution may not be a module but rather a cron job pulling that data and serializing it on a collection site. This would be a custom script collating and creating webform content on the collection site. As such, the webform Node ID would not necessarily be preserved.

Another approach, if the cron job is not preferred... might be to use the built-in mail function from webform, or to create a Rule to send the webform data to a mailbox. The collection site can be configured to create node content processed from that mailbox. One benefit is that this could be a non-webform content type. As such, you can add fields and act on that data in a way to manage it and you could also in this way preserve a record of the original Node ID so that a reference to the source site is possible. Other fields might be the site URL, notes, if action is required... and so forth.

Here are some references that might be useful in the latter approach:

* Add content to your site via email using https://www.drupal.org/project/mailhandler - Mailhandler
* http://drupal.stackexchange.com/questions/69134/send-mail-to-email-addresses-from-webform-when-a-content-is-saved - Send mail to email addresses from webform ...
* https://www.drupal.org/project/webform\_rules - Webform Rules module

Of course, it matters if you're using D6 or D7. Mailsave & Mailhandler are both included in one popular approach using D6 and Mailsave doesn't have a D7 version.
> 1 votes

---
Tags: 7, webforms, drush
---


# Question
Title: Date format on user profile form shown incorrectly - how to change
I added a date to the user profile form under admin/config/people/accounts/fields. The field is of type 'date', the widget of type 'select list' and I only collect year, month and day.

Without altering anything the date entry widget is shown on the form in the order year-month-day.

Since the order in the Netherlands should be day-month-year, I set out to change the date format by:

* Adding a new custom format d/m/Y under admin/config/regional/date-time/formats
* Create a new date type called 'test' and referencing the custom format from the previous step under admin/config/regional/date-time
* Changed the date display format to the 'test' type, under admin/config/people/accounts/display - press update and save the settings

In the date preview of admin/config/people/accounts/display, the date is shown as DD-MM-YYYY which is the format I want.

Now, going to the user profile page under user//edit, the date order shown as month-day-year.

I have tested this on a clean installation of Drupal 7.33 and the only module added is the date module 7.x-2.8.

How can I change the display order for this specific field?

Kind regards, Eric van der Staaij

# Answer
> 0 votes
Date entry format is configurable, what you did was changing the way the date will display on content but not on create content form. To change it go to your field configuration page on content type then find more settings and values collapsed fieldset and inside it look for date entry options and change to whatever.

https://docs.google.com/a/srijan.in/file/d/0B9FG53CLjf-YdEFfdzVEV1hmcWc/edit?usp=drivesdk

# Answer
> -1 votes
Please refer the Community Documentation of **Usage example of date elements within forms** in the Date API form elements for the solution.

Thank you.

---
Tags: users, datetime
---


# Question
Title: How Can I Enable a Multi-Lingual Catalog Block on Drupal 6.32 + Ubercart 6.x-2.13
## Description of Problem

No matter what I try, I cannot get my Ubercart Catalog Block to change languages when I use the Language Switcher. You can test this behaviour for yourself at:

**holistichorsecare.com/zh/products/aromadog-arf-ritis-pain-relief-1oz**

Regardless of the language context (English or Chinese, "en" or "zh-hant"), the shopping cart block on the left margin of the page, under all circumstances, displays this text:

**Shopping cart**

**There are no products in your shopping cart.**

**0 Items Total: HK$ 0.00**

Go ahead and give it a try. Load the page and click on English or Chinese as they appear in the page header. The shopping cart block does not change languages- and I'd like it to.

## The Localization Files are Installed - I Think...

I've installed the following localization strings packages using the Administration front end and they appeared to be loaded correctly.

* ubercart-6.x-2.13.zh-hant.po
* uc\_ajax\_cart-6.x-1.0.zh-hant.po

## Checking out the Module Code

Looking into:

holistichorsecare.com/www/content/sites/all/modules/ubercart/uc\_cart/translations/zh-hant

I see the following entry around line 1926:

msgid "There are no products in your shopping cart." msgstr "ä½ (å¦³)ç è³¼ç©è»è£¡æ²æä»»ä½åå."

(the garbled text is the multi-byte characters breaking up in my shell)

Looking into

holistichorsecare.com/www/content/sites/all/modules/ubercart/uc\_cart/cart.module

I see the following call around line 706:

```
$output = '<p class="uc-cart-empty">'. t('There are no products in your shopping cart.') .'</p>';

```

So it appears that there is a call to t() to translate the string, but none is forthcoming from whatever system there is that serves up the alternatives.

Can someone please tell me where I need to go in the administration front end to enable localization/translation for the shopping cart block (ajax cart) in Ubercart?

I'm thinking I just missed a check box somewhere to turn on the translation, or have to tell Drupal/Ubercart that the strings in the Shopping Cart Block are to be translated, but I don't know where to go or how to do this.

P.S.: When I called i18n\_get\_lang() in troubleshooting code I got the right answer back (i.e. "en" or "zh-hant"), so the system knows what language context it is in.

Thank you.

# Answer
Sorry but you CAN NOT HAVE Ubercart multilingual because the project was started on the wrong way and now the developer team have no interest/possibility/capability to rewrite a lot of code!
> 0 votes

---
Tags: ubercart, i18n-l10n, ajax
---


# Question
Title: Drush Omega Guard - "command could not be found" or "could not locate Gemfile"
I have a multisite installation on Windows 7. I am now trying to execute the `drush omega-guard` command on an Omega sub-theme.

When I am in the theme folder (sites\all\themes\theme\_name) I get the response "The drush command 'omega-guard' could not be found."

When I am in the site folder (sites\site\_name.com) omega-guard prompts me with "Which theme do you want to run Guard for?" Once I choose the number for my sub-theme, it responds with "Could not locate Gemfile." I think the Gemfile should be in my theme directory.

What am I doing wrong?

# Answer
Answer from the comments above, documented here per Molot's request:

In the case where your settings.php file is not in the 'default' folder, Drush needs you to specify --uri=site\_name.com, unless it can determine the site to use via your cwd (e.g. if you have set your working directory to sites/site\_name.com, as described in the question). --uri is not necessary if you have a 'default' site, but it is necessary if you use any other name for your site folder, even if you only have one site in the Drupal installation.

Seems that the problem with finding the Gemfile was resolved by always setting the working directory to the theme directory, where the Gemfile was located. Doing this while using --uri with Drush solved the problem.
> 1 votes

# Answer
I had this problem just now, and running `drush cc all` fixed it for me. I'm running `drush omega-guard` from within the custom theme's directory.
> 0 votes

---
Tags: drush, theming
---


title: Disabling user/register

text:
# Question
Title: Disabling user/register
I want to disable the user/register page in Drupal 7 but I still want registrations possible, but only through other links. I've tried altering the access to it through a module like so:

```
my_module_menu_alter(&$items) {
     $items['user/register']['access callback'] = FALSE;
}

```

but it does not seem to work. I know I can alter the form permission and set it to false but I need the form for other modules I have installed. Is there any way to do this with a already existing module or programmatically?

# Answer
> 4 votes
Your implementation is most probably correct, I use the following code to customize access to the register page in some projects:

```
function MYMODULE_menu_alter(&$items) {
  $items['user/register']['access callback'] = 'MYMODULE_user_register_access';
  unset($items['user/register']['access arguments']);
  $items['user/register']['type'] = MENU_CALLBACK;
}

```

Make sure that the custom module is enabled, make sure that the module name is spelled correctly, also make sure that there really is an `&` prepended to the `$items` parameter. It happened to me in the past that I forgot the reference operator on `hook_X_alter` implementations. Also flush caches after adding new hook implementation functions.

# Answer
> 0 votes
Did you try doing this with configuration itself. Go to `admin/config/people/accounts`. Under Registration and Cancellation find out Who can register account? and set it to Administrator.

https://docs.google.com/a/srijan.in/file/d/0B9FG53CLjf-YeW9XcEs0SjRBcDQ/edit?usp=drivesdk

---
Tags: users
---


# Question
Title: How can you expose a Quantity update / delete field in the checkout cart?
Currently when adding items to cart, I have all users redirected straight to /checkout, but the problem arises is when users want to modify their cart contents.

I tried adding the **Quantity Text Field**, but no update button shows up. And I tried adding the delete button, but it doesnt delete anything.

# Answer
> 1 votes
It actually isn't possible, at least using the Views Forms functionality that we use to create the shopping cart form at /cart. The issue is that using a Views Forms field in a View turns the entire View into a form - as in, you get a new form element in the DOM that wraps around the entire View HTML. Because the cart contents checkout pane is already part of a form, you end up nesting a form within a form - which just doesn't work.

You have two basic options to work around:

1. Alter your checkout form to embed custom quantity editing fields in that part of the checkout form. Difficult, not sure it's possible. (In the same vein, you could also figure out how to make Views Forms embeddable inside other forms - even more difficult, but probably more possible.)
2. Use a custom block on /checkout to show the cart contents with a Views Form that saves updates asynchronously (not the default behavior). The idea there would be you'd have a form with quantity edit fields outside the checkout form that you'd be using to update the cart contents completely separate from whatever happens on the checkout form. I say you'll want to use AJAX to save the updates because you don't want to have someone submitting a cart update form after putting data into the checkout form elements below and losing data.

These two options work with the existing Views powered cart contents pane. If I had this scenario and owned the feature, I'd probably just create a custom checkout pane and eschew the Views powered form entirely.

# Answer
> 0 votes
Did you look into the Commerce Extra module. It gives the following features

> Improve quantity field by wrapping it with decrease/increase button links.

Also there is Commerce Add to Cart Extras

> The initial version provides a views field handler ("Commerce Product: Quantity input field") that relies on the Views Form API (a part of Views 3 since RC1) to output a quantity textfield that turns the view into an add to cart form. The default quantity can be configured, and only products with a quantity larger than 0 are added to the cart.

# Answer
> 0 votes
This seems to work ok to solve this problem. https://www.drupal.org/project/commerce\_cart\_form\_checkout\_pane

Have done some preliminary testing. Not sure how your meant to be able to include your own view as it suggests on the module page.

---
Tags: 7, commerce
---


# Question
Title: Would I be in "Blacklist" to send bulk mail by Simplenews?
We have thousands of subscribers who sign up through our Simplenews. Now, we would like to send newsletter(eblast) through Simplenews with Simplenews Content Selection too all subscripbers. Will our server getting "blacklisted" by doing this?

PS: The newsletter has unsubscribe URL on footer

# Answer
> 0 votes
As far as I'm aware, your ip gets blacklisted if a couple of people click 'report spam' in the email browser. Consider setting the SMTP on your server to use a web service such as MailJet who have all kinds of advice on what to do and what not to do.

---
Tags: emails
---


# Question
Title: Can users switch to different Profile2 profiles?
I'm trying to implement a membership site and am considering using a Profile2 profile form as an application for membership.

So I'd make a profile type for Membership A. The user would apply for Membership A, get admin approval, then be given an account with Membership A.

Later, they might want to upgrade their membership to B. Can they just switch their Profile type to a different one? Or submit a request for this and an admin changes their profile type?

Note that Membership A has fields 1,2,3,4 and Membership B has 1,2,3,4,5,6,7,8,9. So maybe just add a second profile type (B, with fields 5,6,7,8,9) rather than switch?

# Answer
> 1 votes
It's up to you whether it is better to duplicate fields 1 - 4 or not. That depends on your specific requirements, what the fields are, etc.

In my experience I generally go with A (1, 2, 3, 4), B (5, 6, 7, 8, 9) and the fields are usually logically grouped into each profile. For example there might be 2 profiles like "Personal information" and "Employment information" or something like that, which obviously will have their own different grouping of fields, but I can see there may be cases where you might want to go the other way.

One annoyance that you might have to deal with if replicating fields is that when a user switches types they have to enter information into fields they already filled out in the other profile. That would annoy me as a user. You could work around that though and auto fill the fields.

Either way, you can control access to different profile types based on user role.

So the easiest solution would be to configure a role for each of the profiles and then have an administrator add/remove the roles from users as required.

If your use case allows for it there are also modules that allow users to change their own roles (you can limit it to specific roles so they can't make themselves an admin), for example role delegation. This might be appropriate for some websites. Just make sure they can't give themselves any dangerous permissions.

---
Tags: users
---


title: jQuery UI is missing in all pages

text:
# Question
Title: jQuery UI is missing in all pages
I am having the errors in console for jQuery UI. The jQuery Update module (7.x-2.4) is being used in my theme, and I have no idea why it is not including the jQuery UI. The following is the screenshot of the errors I get. In the view source I don't find jqueryui.js.

It happens in all the browsers. I also tried using the files from the jQuery CDN, but it didn't work at all. These errors are creating many troubles in the admin area. Many things aren't working: The Views interface is broken and the MD Slider is broken.

# Answer
> 1 votes
jQuery UI is not included on every request by default. Drupal only adds it when it is requested. You can ask Drupal to include the libraries you want on some or all pages with a custom module inside a hook\_init or hook\_preprocess\_page. Something like this would work:

```
function MYMODULE_init() {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.widget');
  ...
}

```

For a full list of all system libraries see the API documentation here.

Also, new versions of jQuery do not play nice with many system forms (views as you noted but also rules & panels can have issues). Newer versions of the jquery\_update module have the option of setting a different version of jQuery for administration pages. You will probably want to set that to 1.5 (the version D7 ships with), or add the jquery.migrate script to your theme to allow older jQuery to run on newer versions.

---
Tags: javascript
---


# Question
Title: Create node link in views header and open in popup
Is there any option to include "Node Add" link in **Views header**, which to be opened in popup?

# Answer
I think you are looking for hook\_menu\_local\_tasks\_alter to create the 'add node' link. As for the popup... perhaps you are speaking of the administrative overlay? If that is the case and you have the overlay enabled, the 'add node' task should open in the overlay automatically.

You're probably looking for something like this (taken from this post):

```
function YOURMODULENAME_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  switch($root_path){
    case 'path_of_your_page' : // for example 'page/view/news'
      $item = menu_get_item('node/add');
      if ($item['access']) {
        $data['actions']['output'][] = array(
          '#theme' => 'menu_local_action',
          '#link' => $item,
        );
      }
    break;
  }
}

```
> 2 votes

# Answer
You could add a normal `Global: Text area` header, using the *PHP code* text format, and in it put the following code:

```
<?php if (user_access('create article content')): ?>
<a href="<?=url('node/add/article')?>">Add new article</a>
<?php endif ?>

```

Darvanen is correct that the overlay will be used if you have that module enabled.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: Domain Access - restrict content for only authenticated users (and keep domain specific settings)
I have a site using domain with multiple subdomains.

I want to display some of the particular domains. I can do this with the "Publish to \*" field in the domain access options. How do I also restrict access to some content types so that only authenticated users can access these content types and also work with domain access?

I had the module content\_access installed to prevent ANONYMOUS USERS from viewing specific content types but this was causing problems with domain as it would write to the node\_access table realm=all & view=1 for all content types. This meant that all domains could get access to the content even though the check boxes were set to one specific domain. I think the node\_access permission logic is connected with OR.

Any guidance would be appreciated!

# Answer
> 0 votes
Actually I found the issue was with the content\_access module. It was overriding the settings for the domain access.

Once this was turned of domain was able to operate as designed with just the 'publish to ...' settings.

---
Tags: users, domain-access
---


# Question
Title: Set the menu link as disabled by default
When I create a new node its menu link is enabled by default. I would like to enable it manually only in case if I need. Is there a way to set the checkbox in menu tree as uncheked by default?

# Answer
Have a look at this module, I guess that is what you want.

http://drupal.org/project/default\_menu\_link

Some details from the module's project page:

> Provides the user with a check box on all content types to set the "provide a menu link" value to true by default.
>
> This is basically a nice way to ensure the menu system is adhered to by all content authors.
>
> There is a similar module called menu\_force that does just that. Whereas Menu Force mandates menu assignment, Default Menu Link merely changes the status of "Provide a Menu Link" to true. The user can still create content and choose to un-check this box. However, the default state (on node creation) will be true, and as long as you've set a default menu parent item, all content will be filed under that parent.
> 1 votes

# Answer
I found the solution: Disable Node Menu Item Module drupal.org/project/disable\_node\_menu\_item, I don't know is it enough stable version but I hope it will work
> 1 votes

# Answer
By default, all menu items are "enabled." This means they display. Menu items can also be disabled though. A disabled menu item knows who its parent is, so the related sub-menu and breadcrumb will display. But - you don't have to necessarily clutter up your menu with another visible link. (Note: this is only really applicable to the main menu since that's what drives the sub-menu and breadcrumb.)

To create a **disabled menu** item:

1. Put the page/webform/list into the menu using the menu settings section of that content's edit form.
2. Click "Main menu" in the gray shortcut bar.
3. Find the menu item you want to disable.
4. Uncheck "enabled" next to it.
5. Click save at the bottom.

If you want to create a sub-menu below a page that doesn't display in the top menu, *just disable the top menu item and leave it's children enabled.*

Thank you.
> 0 votes

---
Tags: 7, routes
---


title: Problem with menu position module

text:
# Question
Title: Problem with menu position module
I have a menu like this:

In the first sidebar you see the `main menu` with links.
The second sidebar is a block that is visible on pages that begin with `stocklijst/`.

The link in the first sidebar links to the first link in the second sidebar. So the menu items both have class `active`. But when I click on the second link in the second sidebar the menu link in the first sidebar won't be active anymore.

I've installed the Menu Position module to make sure the link is active but it doesn't work. I added a rule like this:

But the menu item isn't active when the path is equal to `stocklijst/gezocht`.

What am I doing wrong?

**UPDATE:**
This is my view:

# Answer
> 0 votes
From your comments, I came to know that you have added a new menu and used it as Menu Block in second sidebar region.

But Menu position module doesn't support new menus.

See the following points from Menu Position module page

> *This includes affecting*:
>
> * The main links of the theme
> * The secondary links of the theme
> * The breadcrumb trail
> * Menu blocks provided by core's Menu module
> * Menu blocks provided by the Menu Block module

So inorder to work with your new menu, you need to install *Menu Block* Module.

*Menu Position* module works well with *Menu Block* module.

So if you install Menu Block module you can use your custom menus also.

> So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
>
> Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!

I've tested this scenario and it works perfect.

# Answer
> 0 votes
For content with many individual entries - people, events, and articles - creating disabled menu items for each of them isn't practical. So we use a module called "menu position" to create fake disabled menu items for groups of content. Any content that matches the menu position rule (say - is an event) will "appear" to be in the menu where ever the menu position item is placed.

In the example above, all events will appear to be in the menu below Calendar. "Calendar" is the parent menu item of all events. This means that the event lists will display as options in the sub-menu on every individual event.

Menu position rules are created during site development, and content administrators cannot add new ones. However, if you remove the parent menu item, menu position rules will get really confused. If you see a menu item like the one above and are considering removing it's parent, talk to someone in Arts & Sciences Computing.

---
Tags: 7, routes, navigation
---


# Question
Title: Email Customer if Order Contains a Disabled Product
I have Drupal Commerce configured on my site. Customers can purchase tickets to classes. However, if a class gets canceled, I need to notify any customers who purchased said class that the class is canceled.

I am thinking the best way to cancel a class is to set its status from "active" to "disabled". Once I do this, an email would be sent to any user who purchased said class.

I just don't know how to do this with Rules. Any help would be appreciated.

# Answer
You can probably rig this up via Rules to automatically send the notification when the class is disabled, but I think it would be easier and probably better to separate out the disabling of the class and the notification of users. I'm not typically a fan of automatic side effects on entity updates - just imagine what would happen if that product somehow got re-enabled and you had to disable it a second time.

I'd create a line item View using Views Bulk Operations with an exposed filter that let me choose what product SKU to use to filter the results. You can do that either based on the line item's label value (since it initializes to the product SKU) or add a relationship to the referenced product if you've altered those labels somehow. You'll also want to add a relationship to the line item's order so you can filter it by orders in a certain status.

You can then use VBO to call a custom rules component that takes the line items from the View as arguments and then sends a notification out to everyone in the list. You may need to figure out either a Views query based method or a Rules variable based method to prevent sending the notification multiple times to the same user in the event that the account purchased the product more than once.
> 1 votes

---
Tags: commerce, rules
---


# Question
Title: Lightbox2 image formatter in view not adding click event
I have a view with an image field in it. I also have two different image styles, "timelinr" and "timelinr-modal". What I want is the thumbnail image to be the first style, and when its clicked on have it come up in a modal with the second style.

I have setup my settings on my image like the following,

For some reason though, this is not adding a click event to my image in the view. Am I doing something wrong here, or should I go about this a different way?

# Answer
> 2 votes
1. Create a view and do settings as per the screenshot below.
2. Choose Formatter as described below for **content:image**

Now you will have thumbnail image of the style **"timelinr"** and when clicked it will come up with image style **"timelinr-modal"**.

I tested above and it is working.

---
Tags: views, javascript
---


title: How to add nodereference link to a view

text:
# Question
Title: How to add nodereference link to a view
I have two content types.

* Images
* Question

The **question content type** is meant to allow users to ask questions about the photos in the **images content type**.

I added a *node reference field* with "*reference from url*" type selected to the question content type. I checked "create link on the full view" during the setup. This works correctly if I go to an "images" node.

However, I am displaying the "image" type in a view. So far I can not figure out how to get a link to the question content type to show on the view. I have tried this using a "references" display type of the view, but still nothing.

# Answer
**Set up the relationship**:

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

**Add a field**:

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

# Answer
In your view you need to add your question type in the **References** in Advanced Settings.

Then as you add your field to the view you create, in the **Relationship** drop down, chose your *relationship name* (the default is **Do not use relationship**)
> 0 votes

---
Tags: nodes
---


title: Need for Complex Sort Criteria Views

text:
# Question
Title: Need for Complex Sort Criteria Views
I have a challenging task of making an HTML List into a View within Drupal.

The original list is alphabetical EXCEPT for the first 40 entries which are organized essentially in chronological order as well as most popular items on top.

I believe i took care of the most popular items (5 of them) buy utilizing the sticky option within Drupal.

The next 35 items... 30 of them need to be organized by the release date, in this case a "special event #" in the node title is what is used to signify its chronological order.

Example:

```
 Cool Party - Special Event 1
 Fun Shindig - Special Event 2
 Quiet Gathering - Special Event 3
 Funny Picnic - Special Event 4

```

I want to know how i can sort the list within Views to get the special event listings in order from 1-30 at the top of my list (just after the sticky top 5)

# Answer
You are able to create a single block or page in views with **different sort criteria** using **attachments** in views

* So create a view with some criteria and add an attachment like above and override the sort criteria as you need
* Then add your attachment to your page or block as below

Here is a post which explains this in detail.
> 1 votes

---
Tags: views
---


# Question
Title: Content: Has taxonomy term ID depth modifier
Answer to my question was found here: Show all child nodes of a taxonomy term D7.

But I'm not able to understand the use case of the second option: "Content: Has taxonomy term ID depth modifier" as in the figure.

# Answer
The taxonomy term ID depth modifier option allows you to reuse the same view to query nodes according to varying depths in the taxonomy tree. For example let's say this is your taxonomy.

```
North America (term id:7)
- Canada
- Mexico
- United States
-- California
--- San Francisco
--- Los Angeles
--- etc

```

With a term id of 7 and a depth modifier of 0 your query would include nodes tagged with "North America". With a depth modifier of 1 your query would include nodes tagged with "North America", "Canada", "Mexico" and "United States", and so on. The term depth modifier is passed as the second argument (Contextual Filter in Drupal 7) to the view separated by a slash. So if the term id is 7 and the depth modifier is 2 the arguments for the view are '7/2'.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Gather all broken links (Link-checker) in view
I just installed the Link-checker module which seems nice for my needs. But I don't see a way to gather all the nodes with broken links, for example a view or block.

Is there any way to collect all these nodes with broken links in a view/block?

# Answer
> 1 votes
Normally this would involve either a custom module, or a patch to the link-checker module, with an implementation of hook\_views\_data. This requires some coding skills and understanding of databases.

One option is to try the Data module, which supposedly is capable of automatically deriving the required information by looking at the table structure. I've never tried it though, so whether or not it works, or how well it works, I cannot say. From looking at the modules schema, it looks like the interesting tables are:

D7 "linkchecker\_block\_custom", "linkchecker\_comment", "linkchecker\_node", "linkchecker\_link"

D6 "linkchecker\_boxes", "linkchecker\_comments", "linkchecker\_nodes", "linkchecker\_links"

# Answer
> 0 votes
You can achieve that using the Link checker Views module

> Link checker integration with Views module, so to be able to produce custom reports of the data collected by linkchecker

For example you can create a new report sorting the links by "last date checked desc" and show that date, or you could filter the report at your pleasure.

Right now there is a dev version available. So test it on local before use on live sites.

---
Tags: 7, navigation
---


# Question
Title: site-install error: /var/www/drupal7 does not contain a valid installation
I am running on Windows 7 Enterprise and have done to following to set up my site:

1. Downloaded and installed Virtual Box VirtualBox-4.3.18-96516-Win.exe
2. Downloaded and installed vagrant\_1.6.5.msi
3. Downloaded vdd-8.x-1.0-alpha4.zip
4. Extracted the zip file and copied the vdd folder to /Test so I have /Test/vdd as my vdd directory
5. opened a command prompt and went to /Test/vdd
6. Ran vagrant up and it seemed to work.
7. Accessed the vm by using vagrant ssh
8. Changed permission on all directories to 777 (i.e. chmod -R 777 sites and I verified that all directories are 777)
9. The drupal7 directory did not have a setting.php file. I copied default.setting.php from default directory to the drupal7 directory and named it settings.php.
10. Also copied settings.php to default directory so default has both settings.php and default.settings.php

Now when I run `drush @drupal7 site-install -y` I get the following:

> Command site-install needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. The drush command 'site-install' could not be executed. The directory /var/www/drupal8 does not contain a valid Drupal installation

A couple of things worthy to note is that my drupal7 directory has no files other than settings.php.
I don't know if that is the way it is supposed to be.
mysql is up and running. If I run `mysql -u root -proot` it connects to the db.
I am assuming apache and php are working because 192.168.44.44 returns the proper landing page.

# Answer
> 1 votes
The Documentation shows the steps you should do are:

1. Start with empty directory and prepared empty database (or user with permission to create database)
2. `drush dl drupal --drupal-project-rename=example`
3. `cd example`
4. `drush site-install standard --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' --site-name=Example`

You **should not** manually create, copy, move config files before executing `drush site-install`. And you **should not** use aliases like `@drupal7` unless they are defined. In case of installation, I always set up site first, and aliass for it later, and it worked all right.

---
Tags: 7, drush
---


# Question
Title: Visualization API + Highcharts Options per chart
It's possible to create good visualization graphs with Visualization API + Highcharts library but it seems overriding the chart options is not possible.

Highcharts API has tons of options such as (http://api.highcharts.com/highcharts#xAxis.tickInterval).

I want to set options for some charts not for all of them.

I created a views and visualize it. It's OK. I made some changes on highcharts.inc (modules/visualization/includes/plugins/highcharts.inc).

```
if (!empty($x_axis)) {
  $highchart->xAxis = (object) array(
    'categories' => $x_axis,
    'tickInterval' => "10",

  );
}

```

I added the `'tickInterval' => "10",` line and it's working... but it's working for all charts. I want to set this options for only some charts. Is there a way to do this by for example adding a if clause with the views name I wanted to set the options?

I tried to add a line to the file ( `if ($view->name == 'myview') {` )

```
if ($view->name == 'myview') {
if (!empty($x_axis)) {
  $highchart->xAxis = (object) array(
    'categories' => $x_axis,
    'tickInterval' => "1",

  );
}
}

```

But it gives error as I expected: **Undefined variable: view**

Yes, here how could I made the highcharts.inc file understand the view variables or is there any other way to do this?

EDITED (the highcharts.inc is below ):

```
<?php
/**
 * @file
 * Library plugin for Visualization implementing support for Highcharts.
 */

class HighchartsHandler implements VisualizationHandlerInterface {

  protected $addedJavascript = FALSE;
  protected $available = FALSE;

  /**
   * Constructor for the Highcharts plugin.
   */
  public function __construct() {
    if (module_exists('libraries')) {
      module_load_include('module', 'libraries', 'libraries');
      $path = libraries_get_path('highcharts');

      $this->available = is_dir('./' . $path);
    }
  }

  /**
   * Renders a chart using Highcharts.
   */
  public function render($chart_id, $data, $options) {
    // Chart options.
    $highchart = new stdClass();

    // Chart.
    $highchart->chart = (object) array(
      'plotBackgroundColor' => NULL,
      'plotBorderWidth' => NULL,
      'plotShadow' => FALSE,
    );

    // Set title.
    $highchart->title = new stdClass();
    $highchart->title->text = $options['title'];

    $x_axis = array();
    if (!empty($options['xAxis']['labelField'])) {
      foreach ($data as $row) {
        $x_axis[] = check_plain(strip_tags((string) $row[$options['xAxis']['labelField']]));
      }
    }

    if (!empty($x_axis)) {
      $highchart->xAxis = (object) array(
        'categories' => $x_axis,
        'tickInterval' => "10",

      );
    }

    if ($view->name == 'myview') {
    if (!empty($x_axis)) {
      $highchart->xAxis = (object) array(
        'categories' => $x_axis,
        'tickInterval' => "1",

      );
    }
    }

    if (!empty($options['yAxis']['title'])) {
      $highchart->yAxis = (object) array(
        'title' => (object) array(
          'text' => $options['yAxis']['title'],
        ),
        'min' => "0",
      );
    }

    // Series.
    $highchart->series = array();
    foreach ($options['fields'] as $name => $column) {
      if (!empty($column['enabled'])) {
        $serie = new stdClass();
        $serie->name = $column['label'];
        $serie->type = $options['type'];

        $serie->data = array();
        foreach ($data as $row) {
          $value = (int) $row[$name];

          if (!empty($column['enabled'])) {
            $serie->data[] = (object) array('name' => check_plain(strip_tags($row[$options['xAxis']['labelField']])), 'y' => $value);
          }
          else {
            $serie->data[] = $value;
          }
        }

        $highchart->series[] = $serie;
      }
    }

    $highchart->plotOptions = new stdClass();
    $highchart->plotOptions->pie = (object) array(
      'allowPointSelect' => TRUE,
      'cursor' => 'pointer',
      'dataLabels' => (object) array(
        'enabled' => TRUE,
        'format' => "<b>{point.name}</b>: % {point.percentage:.1f}"
      ),
      'showInLegend' => TRUE,
    );
    $highchart->plotOptions->bar = (object) array(
      'dataLabels' => (object) array(
        'enabled' => TRUE,
      ),
    );

    $highchart->credits = new stdClass();
    $highchart->credits->enabled = FALSE;

    // Rendering.
    $highchart->chart->renderTo = $chart_id;

    $information = array(
      'library' => 'highcharts',
      'options' => $highchart,
    );

    // Add Drupal.settings for this chart.
    drupal_add_js(array('visualization' => array($chart_id => $information)), array('type' => 'setting'));
  }

  /**
   * Includes global Javascript required by Highcharts.
   */
  public function postRender() {
    if (!$this->addedJavascript) {
      module_load_include('module', 'libraries', 'libraries');
      $path = libraries_get_path('highcharts');
      drupal_add_js($path . '/js/highcharts.js');

      drupal_add_js(drupal_get_path('module', 'visualization') . '/js/highcharts.js', array('scope' => 'footer'));

      $this->addedJavascript = TRUE;
    }
  }

  /**
   * Whether or not the plugin is avialable.
   */
  public function available() {
    return $this->available;
  }

  /**
   * Returns an array with supported chart types.
   */
  public function supportedTypes() {
    return array('line', 'column', 'pie');
  }

}

$plugin = array(
  'name' => 'highcharts',
  'label' => t('Highcharts'),
  'handler' => new HighchartsHandler(),
);

```

# Answer
A few points on this:

1. I recommend not hacking drupal modules like that. You will quite possibly cause yourself troubles later on .
2. There are patches in the issue queue that allow you to better override charts without hacking the module. See https://www.drupal.org/node/1809850
3. It may be worth checking out other patches in the issue queue. There are a bunch of patches in there that are useful... which brings me to the most important point:
4. I would personally recommend not using the visualization module because it is not very actively maintained. In my experience you need a lot of patches and even then there are issues. I recommend instead using the charts module, which has better support for overriding charts and is more actively maintained.
> 2 votes

---
Tags: views, charts
---