# Question
Title: Link it's node link to the node:body in views
I can only link it to it's node when its a node:title field when making a certain view. how can I link it to the node:body? Is there are reference id?

# Answer
In all seriousness, you could do this by first including the node:nid in your view and then rewriting node:body as a link to node/\[nid\] in the configuration. What might happen with all the content of that body inside of that though is undetermined. I would hope views would check\_plain it or remove tags etc so that just text is linked but I've never done it to see.
> 1 votes

# Answer
There is a module to achieve: https://drupal.org/project/linked\_field

Then you can add any link to any field in manage display page admin/structure/types/manage/\[node\_type\]/display
> 0 votes

---
Tags: views, navigation, nodes
---


title: hook_node_insert and FileField Paths

text:
# Question
Title: hook_node_insert and FileField Paths
I'm using hook\_node\_insert to process some data from node.

This code returns image URL, BUT i'm using FileField Paths and i can't manage to get the final image URL. Is there any way to solve this issue?

```
$fid = $node->field_imagen['und'][0]['fid'];
$imgpath = file_load($fid)->uri;
$url = file_create_url($imgpath);

```

Thanks

# Answer
> 1 votes
Filefield Path uses hook\_entity\_insert() to operate with file directory. The hook\_node\_insert is called before hook\_entity\_insert, so the file isn't processed yet there. See: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_save/7

```
module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

```

You should use that hook as well. Just make sure, your module have higher weight than ffp. (Check (and increase if necessary) the weight field of your module in the system table.)

---
Tags: 7, media
---


# Question
Title: How do I tell hook_block() about placement
I may have a disconnect and I'm just not sure if what I'm asking is possible. I'd like to tell Drupal where to place a block. So far I'm using a Context with a path condition to `user/*` and `stream`.

Can't I accomplish the similar thing with the following?

```
function hook_block($op = 'list', $delta = 0, $edit = array()) {

  if ($op == 'list')
  {
    $blocks[0] = array(
      'info'      => t('Social Login Block'),
      'region'    => 'sidebar_last',
      'pages'     => 'stream\nusers/*',
      );

```

Is this possible or is it better form to just let the maintainer set the block manually? Or a larger question, how might I translate this context rule into code?

# Answer
You should use hook\_block\_info\_alter() instead of hook\_block(). For example:

```
function YOURMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['MODULE']['BLOCK']['visibility'] = BLOCK_VISIBILITY_LISTED;
  $blocks['MODULE']['BLOCK']['pages'] = 'user/* \n stream';
}

```

Where `YOURMODULE` is the name of your module, `MODULE` is the module generating the block, and `BLOCK` is the name of the block. You should list all paths where the block should be visible separated by `\n`, `\r` or `\n\r`.
> 1 votes

---
Tags: blocks, 7
---


# Question
Title: Does using Views & Panels on every page will effect site performance (speed)?
I am building a community site. The site would have A LOT of data on it.

I thought about creating a lot of content pane with views, and use them with panels - for every page.

I will be happy to hear your thoughts about this idea.

* It will make my site much slower?
* Or it depends entirely on different things? if so, I will be happy to get more information. I know I need to cache, but I don't really know how to do that on the user's computers.

Thanks!

# Answer
Panels is actually sometimes faster than core is on it's own.

http://www.codeenigma.com/en/blog/performance-panels

And that's without utilizing caching, something Panels can do much better than core, because it allows you to do it from on a page by page basis, down to on a block by block basis.
> 2 votes

---
Tags: views, panels, performance
---


# Question
Title: How to grant user User Points after publishing content, while content's default is unpublished?
I'd like to grant users User Points when their added content of the content type 'Content', which is unpublished by default, is published. I tried this with the Rules module: \- Event: After saving new content \- Elements: * Content is of type: Content * Content is published \- Actions: Grant points to a user

So, when a user adds 'Content' content, they don't get any User Points and their content is unpublished. My idea was that they'd be granted the points after I - as moderator - had published their content. But apparently, they don't get points after I've done that with the rule I set up. What did I do wrong and how can I solve this?

# Answer
> 0 votes
I solved my problem by doing this:

1. Create flag and give flag name as **Publish node and grant points to user**
2. Add new rule with event **A node has been flagged, under "Publish node and grant points to user"**
3. For actions **publish this node** and **grant points to user** use this data `selector: flagged-node:author`

Special thanks to oneng on Stackoverflow!

---
Tags: 7, rules, userpoints
---


# Question
Title: Why not programatically created nodes in the simpletests?
Most core and many contrib simpletest test create nodes by preparing the interface, logging an admin in and then filling out the form on `/node/add/foo`. Not only is this terribly slow, it fails at the most basic rule of Testing: only test your own concerns; mock and stub the rest.

For a test, all I need is N nodes with X tags (taxonomy-terms) attached to them. I am (in no way) interested in whether or not some "Save" button exists somewhere; which is what I am testing when I follow along with core tests, e.g my helper function `createNodesWithTags()`.

This helper is modeled after `TaxonomyRSSTestCase` which has the same concern as my: make sure there are some nodes with tags, so that some interface can then be tested using these nodes. The helper first creates an entity-field on the node type "article", required because otherwise one cannot add tags to that node. It then proceeds to open up the `node/add/article`-page, attaches the term and presses `Save`.

```
  private function createNodesWithTags($amount) {
    $field = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    field_create_field($field);

    $this->instance = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'bundle' => 'article',
      'entity_type' => 'node',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance);

    //Create N nodes and attach all N to tag1, N-1 to tag2, N-2 to tag3 etc.
    $attachable = $this->tags;
    for ($i = 0; $i < $amount; $i++) {
      // Post an article.
      $edit = array();
      $langcode = LANGUAGE_NONE;
      $edit["title"] = $this->randomName();
      foreach($attachable as $tag) {
        $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $tag->tid;
      }
      $this->drupalPost('node/add/article', $edit, t('Save'));

      //remove one tag, so the next node gets one less tag attached.
      array_shift($attachable);
    }
  }

```

Why do core tests test this way? Why is TaxonomyTestCase concerned with whether or not saving a node works (i.e. an admin can be created, logged in and finds the Save button)? Why don't they just call `node_save()` or some other API?

Is there a reason why I should implement it this way too, instead of just dropping records in the database, possible trough the `node_save()` API?

# Answer
> 4 votes
Here is what the Drupal documentation says on it's simpletest page.

> **Testing methodology** Drupal testing focuses on functional testing instead of unit testing. What this means is that the tests are written in such a way that they test the interface as a whole instead of testing individual functions or finite pieces of code. Drupal focuses on functional testing because it is more effective for the way Drupal is written. Functional testing ends up being just as effective if not more effective than unit testing and especially so due to the code style used in Drupal. The testing framework is geared towards this type of testing and the documentation focuses on writing functional tests.

Drupal tests are almost always functional tests and not unit tests. As quoted above, Drupal was coded in such a way (e.g. hooks system, forms api, etc) that Unit tests generally don't make sense.

---
Tags: 7, taxonomy-terms, testing, nodes
---


title: Views slideshow with two pagers

text:
# Question
Title: Views slideshow with two pagers
I want to have a views slideshow as the following:

* Two content types which one has image field and the other has video field.
* I need to have two pagers for the slideshow, one pager for content type (**image**) and one for content type(**video**).

I searched for a solution but i couldn't fine one, also tried to make the pager as a views then using views field view module but no luck.

This photo will explain what i looking for:

Any tips?
Thanks

# Answer
> 0 votes
You could do this using three views.

1. Make the center part of the screen a view which uses a URL argument to know which node to pull the image/video from.
2. Make the listing of possible photos a view. Make each link to view #1 and passes in the node id.
3. Make the listing of possible videos a view. Make each link to view #2 and passes in the node id.

To put all three views on one page you have several options. You could use the module Panels or make each view a block and put them into different regions.

---
Tags: 7, views
---


# Question
Title: How can I display more than 5 nodes on a taxonomy view for one vocabulary?
I have a web site where videos are posted and each video is a part of a series. The series name is a taxonomy term in a vocabulary. Many of the series have more than 5 parts and I cannot figure out how to have the taxonomy view page for these to either add a "more" link, use a pager, or display all nodes referenced by the particular taxonomy term within that vocabulary.

You can see an example of this at http://www.clctc.org/discussion-series/desperation

There are 6 nodes tagged with the "Desperation" term from the "Discussion Series" vocabulary. The page only shows 5 and there is no pager or more link.

Thanks for any help you can provide.

# Answer
> 0 votes
There is two things you should check.

* Re-check if the taxonomy(tags) are referenced correctly in each content.
* Secondly check the pager section in views, for pages, offset and more link settings.

---
Tags: taxonomy-terms
---


# Question
Title: Is the ckeditor or other editor supposed to be automatically installed?
In a fresh install of Drupal 7, when you create and article or page, is there supposed to be an editor? When I create an article or page, it's just the text area where you type in the content. There is no editor so I can bold, upload an image, justify, etc.

Did I do something wrong?

admin/config/text formats, Full html, Administrator; I am the administrator.

# Answer
> 2 votes
No there's no WYSIWYG editor included with Drupal, you need to install one of the contrib modules.

WYSIWYG is the standard solution as it gives you a choice of editors, but there are others like the standalone CKEditor module.

# Answer
> 1 votes
you can also install WYSIWYG and from :

Configuration \> Wysiwyg profiles

see a list of editors (ckeditor,TinyMCE, ...) that you can install. there is also download link as well, simply download and extract them.

now create a folder in sites/all and rename it to libraries and copy the extracted folder there.

the .js files which are described in the list must be in your editor folder in the right place

---
Tags: wysiwyg
---


# Question
Title: Strange behavior of block display mode of views when the pager displays a specified number of items
I've encountered a problem that I've never seen that before (not even in my searches on google). for the sake of simplicity I explain it in an abstract model. I have 4 content types with a title; they are named ct1, ct2, ct3, and ct4. Every content type has 4 nodes.

I made a view\_**N** view for ct**N**, whose display mode is block. I allocated a block on the page p, and view\_**N** must display the last 4 titles of ct**N**. I used the following settings.

* Use pager: Display a specified number of items | 4 item
* Offset : 0

Only view\_1 displayed 4 items; the other views were empty. I changed "4 items" to 8, and view\_1 and view\_2 displayed output.

Finally, I found two solutions:

1. view\_2's offset must be set to 4, view\_3's offset must be set to 8, and view\_4's offset must be set to 12.
2. I must set the number of items to display to 16

This is very strange because views and blocks must be totally independent but from what I saw these results are totally depend on each other. I think it is going to be very difficult to handle such independence when there are many blocks and views on the page and each one may have different number of outputs (or all the items).

Is there any general solution for it?

If that makes any difference, I am using Drupal 7.

# Answer
Try using unique pager IDs for each block display here:
> 0 votes

---
Tags: 7, views
---


# Question
Title: how to import cck data from drupal6 to drupal7?
Now I have to upgrade to drupal7 website from drupal6, but there has been a new during the upgrade of the old site data, mainly CCK and taxonomy, what would I do for the way to the input of CCK in 6 to 7? How can I do this?

# Answer
> 1 votes
You could use the Migrate module along with the Drupal-to-Drupal data migration module

Migrate

> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

Drupal-to-Drupal data migration

> migrate\_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7

Another option would to use the feeds API to import data. You could create feeds of the contents in drupal 6 and use feeds API to create the required contents in Drupal 7

Data export import is another module that does import and export of content.

Node export this another module that can be used along with Feeds

---
Tags: nodes, importing-exporting
---


title: Where is Twig service defined?

text:
# Question
Title: Where is Twig service defined?
In `twig_render_template()`, I see this `drupal_container()->get('twig')->loadTemplate($template_file)->render($variables)`. But I can not see where the twig service is defined.

# Answer
The class that registers the Twig service is `CoreServiceProvider` which, in CoreServiceProvider::register() (the method that every service provider needs to implement), uses the following code.

```
  // The 'request' scope and service enable services to depend on the Request
  // object and get reconstructed when the request object changes (e.g.,
  // during a subrequest).
  $container->addScope(new Scope('request'));
  $this->registerTwig($container);
  $this->registerModuleHandler($container);

```

The class used for the Twig service is not the `Twig_Environment` class that Symfony implements, but a subclass of it (`TwigEnvironment`) implemented by Drupal.

The other registered service is twig.loader.filesystem, which uses the Symfony's `Twig_Loader_Filesystem` class.
> 4 votes

---
Tags: 8, theming
---


# Question
Title: Insert an article and fields with db_insert function or SQL
I want to add an article to the db using db insert along with its field like tags and image.

A sample code i tried(below) is adding data to the db but I can't find any entry in the

```
db_insert('node')
  ->fields(array(
    'title' => "hello world",
    'created' => REQUEST_TIME,
    // 'body' => 'you did it!',
    'uid' => 1,
    'vid' => 5,
    'type'=>'article',

  ))
   ->execute();

```

If not this, can it be done using a normal sql query?

**Why I want to do this way instead of `nodesave`?**

* I don't want any hooks working on this process.
* This is a temperory fast solution I want for a project.

# Answer
> 2 votes
If you need to save a node without invoking any hook, then use the same code node\_save() uses, excluding the part invoking hooks.

```
  $transaction = db_transaction();

  try {
    if (!empty($node->nid) && !isset($node->original)) {
      $node->original = entity_load_unchanged('node', $node->nid);
    }

    field_attach_presave('node', $node);
    global $user;

    if (!isset($node->is_new)) {
      $node->is_new = empty($node->nid);
    }

    if (empty($node->created)) {
      $node->created = REQUEST_TIME;
    }
    $node->changed = REQUEST_TIME;
    $node->timestamp = REQUEST_TIME;
    $update_node = TRUE;

    if ($node->is_new || !empty($node->revision)) {
      if (!isset($node->log)) {
        $node->log = '';
      }
    }
    elseif (!isset($node->log) || $node->log === '') {
      unset($node->log);
    }

    if (!$node->is_new && !empty($node->revision) && $node->vid) {
      $node->old_vid = $node->vid;
      unset($node->vid);
    }

    if ($node->is_new) {
      drupal_write_record('node', $node);
      _node_save_revision($node, $user->uid);
      $op = 'insert';
    }
    else {
      drupal_write_record('node', $node, 'nid');
      if (!empty($node->revision)) {
        _node_save_revision($node, $user->uid);
      }
      else {
        _node_save_revision($node, $user->uid, 'vid');
        $update_node = FALSE;
      }
      $op = 'update';
    }
    if ($update_node) {
      db_update('node')->fields(array('vid' => $node->vid))->condition('nid', $node->nid)->execute();
    }

    // Call the node specific callback (if any). This can be
    // node_invoke($node, 'insert') or
    // node_invoke($node, 'update').
    node_invoke($node, $op);

    // Save fields.
    $function = "field_attach_$op";
    $function('node', $node);

    $delete = $op == 'update';
    node_access_acquire_grants($node, $delete);

    unset($node->is_new);
    unset($node->original);
    entity_get_controller('node')->resetCache(array($node->nid));

    db_ignore_slave();
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('node', $e);
    throw $e;
  }

```

I didn't remove the call to node\_invoke(), since that calls the hooks implemented by the module implementing the content type, and those hooks are necessary for the content type to work correctly.
I also left the call to `db_transaction()` because, in the case one of the operations fails, all the operations are rolled back, and the database is left in a consistent state, which means (for example) that every table will refer to the same node version ID.

# Answer
> 1 votes
Although strongly recommended to use `node_save` instead (e.g via Batch API ), if you're going to manually add nodes that way you'll need to insert into the `node_revision` table as well.

---
Tags: 7, database
---


title: Add a custom id in textarea

text:
# Question
Title: Add a custom id in textarea
I need to add an ID into a `textarea` of body field on my custom "node-form.tpl.php". Now this body field will be rendered like this:

```
<textarea class="text-full form-textarea" id="edit-body-und-0-value" name="body[und][0][value]" cols="60" rows="20"></textarea>

```

I want to add a ID `redHat` into the texarea, that output should be:

```
<textarea class="text-full form-textarea" id="edit-body-und-0-value redHat" name="body[und][0][value]" cols="60" rows="20"></textarea>

```

To do this i have used `hook_form_alter()` in my `template.php` with no luck!

```
function bartik_form_alter( &$form, &$form_state, $form_id ) {
if($form_id == "article_node_form"){
    $form['body']['und']['0']['value']['#attributes']['#id'][] = 'redHat';
}
}

```

what i am missing? Thanks

# Answer
> 1 votes
Each element should have only one ID and it should be unique. You can change the body texarea `id` with the `hook_form_alter()`

**Example**

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

  if (isset($form['#node']) && $form['#node']->type == 'article') {
    // body textarea ID
    $form['body']['und']['0']['#attributes']['id'] = 'redHat';
  }
}

```

but you cannot add the next one.

---
Tags: 7, theming, forms
---


# Question
Title: How to calculate the sum of a list of integer in Rules
In a Rules component I have a list of integer (as variable data type). I have to calculate the sum of items and to expose the result. Any suggestions?

# Answer
> 1 votes
I found the solution.

1. Add a variable (integer) "total", for example.
2. Loop the list of integers:

* Calculate a value, input 1: `[total]`, input 2: `[line-item]`, return: "result".
    * Set a data value, data: `[total]`, value: `[result]`.
3. Outside of the loop, the `[total]` value is still available.

# Answer
> 0 votes
this is my suggestion, create the following function in your template file:

```
function <theme>_preprocess_node(&$variables)
{

}

```

and by **kpr()** function from devel module try to catch where these outputs are positioned in the page array. now you can take them by a **foreach** loop and cast them to integer.

---
Tags: rules
---


# Question
Title: Is there any case where a module needs to implement a class using ServiceProviderInterface?
Drupal defines the CoreServiceProvider class which is used to add the twig, twig.loader.filesystem, and module\_handler services.

Since the Drupal 8 way to register a service from a module is using the .services.yaml file, is there any case where a class similar to `CoreServiceProvider` should be used?

# Answer
> 2 votes
In short, no: The Twig service registration is written by Fabien Potencier himself. Nobody will probably need to write anything as complex as Twig to necessitate this level of complexity in the service registration.
The module handler is just fanciness: An override for the module handler could have been written during install time.

Unless you are writing an install profile which uses a service, you won't face this problem.

---
Tags: 8, symfony-services
---


title: Contextual filter in taxonomy

text:
# Question
Title: Contextual filter in taxonomy
I have vocabularies "destinations" and vocabulary "places". Destinations vocabulary is for example : Europe\>France\>Paris Place vocabulary is: museums, restaurants, pubs...

I set the path pattern (url alias) for destination content type: \[node:field-destinations:parents:join-path\]/\[node:title\]

I also have Place content type \[node:field-destinations:parents:join-path\]/\[node:field-destinations:name\]/\[node:field-place:name\]/\[node:title\]

Every Destinations content is tagged with destination term and every Place content is tagged with destination term (where is that museum, pub or... located) and also with place term (what kind of place is, is it museum, pub...)

Basically, I want to make views page so when user is visiting Paris page (url alias is europe/france/paris) he should have All places link (in the menu block) pointing on the All places page where he will see listed and grouped museums(3), restaurants(7), pubs(9) or as much as exist for that destination...

I tried everything, I'm sure there is the way to achive it, but I'm missing something...Or am I doing something wrong from the beginning. I'm still not so familiar with Drupal API so I cannot make my own module at this moment.

I suppose that i need views page for all places (grouped by taxonomy term from location vocabulary) and then somehow to pass destination term filter from previous page (europe/france/paris) when the user click to paris he will go on views page europe/france/paris/all-places where he should see Museums (number of museums) and other locations. All that links should link to separate page europe/france/paris/museums views page with, again, listed place content for that destination.

I know this is more than one question but I needed to explain what kind of things I'm trying to achieve.

So, short resume: Can I pass filter term from previous page (term paris) and is there I way to make this grouped place link (Museums (8) Restaurants (22)...) and make them link to separate term page. And, the crucial is to preserve url in views pages, for example all-places page: europe/france/paris/all-places, and for specific place page: europe/france/paris/museums

Can this be done with views module, contextual filters and with some kind of arguments in views url (but Drupal dont allow argument at the first position in url).

Any advice would be helpful, if you have any idea how to achieve this... Thank you very much for your time and help!

# Answer
> 1 votes
This is how I have gotten this working:

* First thing you need to do is install the References module
* Update your Place content type:

1. Rather than add a Destination term reference field, you should create a Destination *node reference* field.
* Configure your view.

1. Under Format \> Settings, select Grouping Field Nr. 1 as Content: Places (or whatever you called your places term reference field).
    2. Assuming you have no relationships added, create a Relationship on Content: destination (field\_destination) (or whatever you called your node reference field).
    3. Save your relationship.
    4. Assuming you have no contextual filters added, create a Contextual Filter on Content: Nid.
    5. Select the relationship on field\_destination (or whatever you called your node reference field).
    6. Select Provide default value with a Type of Content ID from URL.
    7. Save your filter.
    8. Save your view.
* Configure View Block

1. Go to Structure \> Blocks
    2. Configure your View Block
    3. Add to region and set Content-Type to Destination.
    4. Save the block.

Now if you go to one of your destination pages, you will see a list of places grouped by place type.

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


title: How to use tokens in Integer field?

text:
# Question
Title: How to use tokens in Integer field?
I'd like to add a 'Year of birth' field to the build-in registration form. Therefore, I created the Integer field 'Year of birth' at `Administration > Configuration > People > Account settings`.

I set the minimum value to 1900 and the maximum value to 2013. But, instead of '2013', I'd like to use the token `[site-date-yyyy]`, so that I don't have to change the maximum value every year. Unfortunately, only integers are accepted. How can I use a token?

# Answer
Try the Date module

1. Install the module
2. Go to Configuration \> Account Settings \> Manage Fields tab
3. Add a date field of type "Date" and widget "Select list"
4. Hit Save
5. Deselect every date piece except year
6. Hit Save field settings.
7. Check Display on user registration form.
8. Expand More settings and values
9. Set starting year and ending year and default value.
10. Save settings

If you must use a text field, the date field gives you that option as well. You wont be able to set a start or end date, but the module will validate the date is in the proper format.
> 1 votes

---
Tags: 7, tokens
---


# Question
Title: Extra fields in 'manage display' for content types
On my old website, there were extra fields such as 'Author', 'Last modified', 'Tags', 'Post date', 'Read more', 'User picture', and 'Comments' available in the 'manage display' section of content types.

I'd like to have these fields on my new website too, but I really can't remember anymore how they got there. Does anyone perhaps know if they were provided by a certain module?

# Answer
When using Display Suite, you have to first save the layout you're going to use, then the fields will appear.

Under the "Current Template" section, "None" is probably selected. For a default display, select the "One Column layout" and click save. These fields should then populate.
> 6 votes

# Answer
Display Suit provides those extra fields.
> 1 votes

---
Tags: 7, entities, display-suite
---


title: css not working in node reference view

text:
# Question
Title: css not working in node reference view
i am working on a development site. i am on hold because of two problems.

1. i have two content type A and B. i created a view for B content type. i used node reference in content type A and call the created view so it display view fields rather than only title of nodes. my problem is that when i start type any title in this field it display the options in autocomplete but it display white spaces, i add css but it is not working

so the main question is css not working in node reference view result
2. i added a view in the same manner for a field. i want to add radio button on each result of view ,and when we click on radio button it's value copy in another field of content type.

Thanks , plz help me

# Answer
1. Can you get the regular node title to show up? Is the node title important? I am wondering if Automatic Entity Label could help you at all. Formerly Auto Node Title. https://drupal.org/project/auto\_entitylabel
2. You may want to look at Rules and VBO. Creating a Rules Component "Action Set" and adding it to a Views Bulk Operations could handle this use case. Make sure you set the permissions properly when you create the Action Set (there is a collapsed field set called "Settings" when you edit a Rules Component that contains permissions settings for each Component)
> 0 votes

---
Tags: views, nodes, entities
---


# Question
Title: hook_form_alter won't save options cck field from custom form
I have created content type named "site\_profile", and form named "add\_website\_form". The content type includes cck fields and one of the fields is "field\_operators" which is select box field. I have hooked options of the field to display variable that contains array of specific users with some mechanism. The hook\_form\_alter is:

```
function lcm_form_site_profile_node_form_alter(&$form, &$form_state, $form_id) {
    $relevant_users = lcm_get_relevant_users();
    $form['field_operators']['und']['#options'] = $relevant_users;
}

```

Now I am trying to get functionality that stores data into the node through node\_save() function from the "add\_website\_form" (costume form).

the code that supposed to insert the data is:

```
function lcm_add_website_form_submit($form, &$form_state){
    $website_name = $form_state['values']['website_name'];
    $url = $form_state['values']['url'];
    $operators_for_site = $form_state['values']['operators_for_site'];
    lcm_add_website_form_insert_to_db($website_name, $url, $operators_for_site);
}
function lcm_add_website_form_insert_to_db($website_name, $url, $operators_for_site){
    // Create a node object, and add node properties.
    $new_website = new stdClass();

    $new_website->type = 'site_profile';
    $new_website->title = $website_name;
    $new_website->uid = $GLOBALS['user']->uid;
    $new_website->field_url['und'][0]['value'] = $url;
    $new_website->field_operators['und']['value'] = $operators_for_site;
    $new_website->created = strtotime("now");
    $new_website->changed = strtotime("now");
    $new_website->status = 1;
    $new_website->comment = 0;
    $new_website->promote = 0;
    $new_website->moderate = 0;
    $new_website->sticky = 0;
    $new_website->language = 'und';

    node_object_prepare($new_website);
    // Save the node.
    node_save($new_website);
}

```

the problem is that the data that supposed to save on field\_operators doesn't save... Any ideas?

# Answer
> 0 votes
Ok, new answer, replace:

```
$new_website->field_operators['und']['value'] = $operators_for_site;

```

with this

```
$new_website->field_operators['und'][0]['value'] = $operators_for_site;

```

---
Tags: 7, forms
---


# Question
Title: Getting the selected option value of a radio button in form_state storage
I'm trying to make a step form which redirects to a special form depending on a radio button option chosen by the user.

My form always go to the default option value. I think I'm doing it wrong with the $form\_state\['storage'\] getting the selected option.

```
function multiform_second_form(&$form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  $options = array(
  '0' => t('Simple'),
  '1' => t('Multiple'),
  '2' => t('Custom'),
);

  $form['qtype'] = array(
  '#type' => 'radios',
  '#title' => t('question'),
  '#options' => $options,
  '#description' => t('Chose a question type.'),
  '#default_value' => $options['0'],
);

  $option_value = $form['qtype']['options'];
  $form_state['storage'] = array(
      'qtype' => $option_value,
    );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
  );

  $form['#submit'][] = 'multiform_second_form_submit';

  return $form;
}

function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['next']) && $values['op'] == $values['next']) {

  switch ($form_state['storage']['qtype']) {
    case 0:
    $form_state['storage']['step'] = 'multiform_qsimple_form';
    break;
    case 1:
    $form_state['storage']['step'] = 'multiform_qmultiple_form';
    break;
    case 2:
    $form_state['storage']['step'] = 'multiform_qcustom_form';
    break;
}

  }
}

```

If somebody can give me some advices, it would be really great !

# Answer
> 1 votes
Try using a string for the step id, something like this:

```
function multiform_second_form(&$form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  $options = array(
  'simple' => t('Simple'),
  'multiple' => t('Multiple'),
  'custom' => t('Custom'),
  );

  $form['qtype'] = array(
  '#type' => 'radios',
  '#title' => t('question'),
  '#options' => $options,
  '#description' => t('Chose a question type.'),
  '#default_value' => 'simple',
  );

  $option_value = isset($form_state['values']['qtype']) ? $form_state['values']['qtype'] : 'simple';
  $form_state['storage'] = array(
    'qtype' => $option_value,
  );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
  );

  $form['#submit'][] = 'multiform_second_form_submit';

  return $form;
}

function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['next']) && $values['op'] == $values['next']) {

  switch ($form_state['storage']['qtype']) {
    case 'simple':
    $form_state['storage']['step'] = 'multiform_qsimple_form';
    break;
    case 'multiple':
    $form_state['storage']['step'] = 'multiform_qmultiple_form';
    break;
    case 'custom':
    $form_state['storage']['step'] = 'multiform_qcustom_form';
    break;
  }

  }
}

```

---
Tags: 7, forms
---


title: I cant use $account in a block

text:
# Question
Title: I cant use $account in a block
I'm using drupal 6, I wanted to give feed back on a simple quiz (that is answered during user registration - to be a profile field). I made a template for the profile page: user-profile.tpl.php

And the code (at the bottom of the page) works fine, but it doesn't work when I try the same code in the template(for the specific block I want): block-block-10.tpl.php

I added this function to template.php, to (TRY) make $account avaialble to block-10

```
function blockaccess() {
// access globals
global $account;
global $node;
}

```

**What do I need to change?**

the code in block-block-10.tpl.php:

```
<div class="block-content-inner">
    <?php
    blockaccess();
    dsm($node);
    dsm($block);
    dsm($account);
  $correct_ans = "3) I'm from Spain.";
  $quiz_ans = $account->profile_quizoffer_ans;
  print $quiz_ans;
  print "--------------------------------------------</br>";
  print '<h3>チラシの裏のクイズ:</h3><table><tr><th border="1">Q: Where are you from?</th><th>Result</th></tr>';
  if ($quiz_ans == $correct_ans) {
    print '<tr><td width="200"><p style="color:green">';
    print $quiz_ans;
    print '</p></td><td><strong><p style="background-color:green"><font color="white">CORRECT</font></strong></p></td></tr><tr><td>You passed the quiz!</td></tr>';

  }
  else {
    print '<tr><td width="200"><p style="color:red">';
    print $account->profile_quizoffer_ans;
    print '</td><td><strong><p style="background-color:red"><font color="white">INCORRECT</font></strong></p></td></tr><tr><td>You didn'."'".'t pass the quiz!</td></tr><tr><td>The correct answer was:</td><td>';
    print $correct_ans;
    print "</td></tr>"  ;

  };
  print "</table>"; ?>
      </div>

```

# Answer
> 1 votes
Try `global $user;` rather than `global $account;`.

# Answer
> 0 votes
I added $account = user\_uid\_optional\_load(); to block-block-10.tpl.php and its working fine!

---
Tags: 6, blocks
---


# Question
Title: Product variations are causing duplicates to show up in filter results
I'm using Drupal Commerce and have created a different product for every variant combination of color and size. For example, if I'm selling a skirt with multiple colors and sizes I'd have a product for "color:blue size:small", "color:blue size:medium", "color:red size:small", "color:red, size:Large", etc.

I created a view for my products and have added exposed filters for color and size to this view. The problem I'm having is that I'm getting duplicates because of the sizes. I don't mind if the filter results show the same skirt twice in different colors, but I don't want results showing duplicates for different sizes. i.e: "color:blue size:small", "color:blue size:medium".

I've tried adding the filter "Content: Product:delta (= 0)", which eliminates size based duplicates. The problem with this is that it also gets rid of color based duplicates, which cause my color filter to stop displaying different colors for the same skirt. For example, if Content: Product:delta (= 0) is added and I set my color filter to red skirts nothing will show in the results.

Is there a way to add a delta (= 0) filter to only the "size" attribute? I'm guessing this would fix my problem if it's possible to do.

This issue has been killing me and I really need it resolved. Any help would be greatly appreciated.

# Answer
> 1 votes
No, that's not possible, the delta=0 will remove duplicates by restricting to the first product in the product reference field. It won't apply selectively to different attributes on that referenced product.

A better option may be to use the colour filter only, then on the product display node itself, add the value to select the size in the add to cart form.

That way, customers can filter by colour, then select the size they want when viewing the product detail.

---
Tags: commerce, views
---


title: Filter category taxonomy with tabs

text:
# Question
Title: Filter category taxonomy with tabs
i have a node which is of content type "Album", they all have categories defined by terms , and i want the user to be able to choose which category he want to filter by but with tabs instead of a dropdown list.

Cant find anything on the internet so this is my last hope.

Thank you.

# Answer
> 2 votes
Have a look at the quicktabs module. You could use it to embed views in each tab, based on your required filter options there. For example, you can pass a contextual filter option to the quicktab for a single view display to show that content only.

Alternatively, the better\_exposed\_filters module may provide some options for you, such as a list of links, instead of a select box.

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


# Question
Title: Apply a dynamic string to a field before validation
I am attempting to set the "title" value of a content type before it becomes "required" . So what happens is the title field becomes hidden based on user name, after filling in the "first name" and "last name" fields I need to take those values and then apply them to the "title" field, before drupal states that the field is required. Here's what I have so far

```
/**
*  Implements hook_form_alter().
*/

function editorhide_form_alter(&$form, &$form_state, $form_id){
//form id = artist_node_form
//title id = edit-title label: edit-title

global $user;
global $fullTitle;

if($form_id == 'artist_node_form'){
    hide($form['artist_node_form']['edit-title']);
   if( $user->name == 'Editor'){

        // drupal_add_js("jQuery(document).ready(function(){
        //  jQuery('#edit-title').hide();
        // });","inline");
        $form['#submit'][] = "editorhide_form_submit_handler";

     }
}

}

//submit form handler.

function editorhide_form_submit_handler ($form, &$form_state) {

  $fullTitle = array();
  $fullTitle['0'] = $form_state['values']['field_firstname']['und']['0']['value'];
  $fullTitle['0'] .= ' '. $form_state['values']['field_lastname']['und']['0']['value'];
  form_set_value( $form_state['title'], $fullTitle['0'],$form_state);

}

```

With the current code it throws a error:: Recoverable fatal error: Argument 2 passed to drupal\_array\_set\_nested\_value() must be an array, null given, called in

# Answer
> 0 votes
First You should write the these kind logic in validate function rather than the submit function.

So instead of

`$form['#submit'][] = "editorhide_form_submit_handler";`

you should have

`$form['#validate'][] = "editorhide_form_submit_handler";`

Second the first parameter passed to the function `form_set_value` is the form element and not the form state value so the function should look like.

```
form_set_value( $form['title'], $fullTitle['0'],$form_state);

```

I think what you are trying to achieve can be done with a custom module.

Automatic Nodetitles

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.
>
> When the token module is installed it's possible to use various node data for the auto generated title - e.g. use the text of a CCK field (since 5.x).

---
Tags: nodes, forms
---


# Question
Title: How do I output a hidden password field as part of Drupal form?
I want to alter an existing Drupal form built with form API to contain a hidden *password* field. (I.e. I want to create a honeypot field in the form that only 'bots will see and fill in, while humans will leave this field it empty).

The HTML I want included in the form shall be something like this:

```
<input type="password" name="password" style="display:none;" />

```

I've looked at `hook_FORM_ID_alter`, but so far I haven't seen how it can help me with this.

I think I am looking for a way to theme this particular field, some way to manipulate the HTML *after* it has been rendered, but before it shown to the human (or 'bot), but I am open for other answers as well.

(For what it is worth: I am using Drupal 7.)

# Answer
If you don't want Honeypot module as mentioned by Jimajamma, you can do it with Form API `#attributes` all right:

```
$form['pass'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#maxlength' => 64,
  '#size' => 15,
  '#attributes' = array('style' => array('display:none;'));
);

```

Of course it's easy to catch `display:none` in bot's code. It's also common and not so much harder to find out that class applied is styled with it in CSS. There are two methods that are not yet so easy to catch:

* Using box model and overflow to make element hidden under other HTML boxes.
* JavaScript code to move it out of sight or apply `display: none` to it

In both cases you shouldn't use obvious identifiers in html, like `.honeypot` or `.hidden`, as this will be probably easily found by the bot, too. Also, `z-index` usually isn't the way to go, as it tells bot "this element is under other one", or "this element is over other one, hides something".
> 3 votes

---
Tags: forms
---


# Question
Title: Making content available to a user after certain amount of time
I want to restrict content access to subscribers over a period of time. Each user should be allowed to access the content in a sequential manner. So, after one week of membership, users would be able to access "Week 1" material; after 2 weeks users could access "Week 2" material. Membership would just be a particular role.

Something similar has been done in Drupal 6, using PHP as reported in Release Content to Subscribers in a Sequence.

I am wondering if this is possible just using modules, like Rules and Rules scheduler.

# Answer
I yes I think this is possible using Rules and Rules Scheduler

Unpublishing Content

You should check out this tutorial (its also for Drupal 6)

Publish content exactly 24 hours after it was created

What you have to pay attention to is just do the opposite. So in the action you say Unpublish. And then of course you pick the dates.

Hope it helps
> 0 votes

---
Tags: rules
---


# Question
Title: Redirect /user/login to HTTPS, all other requests to HTTP
I'm using Drupal 7. The login page for my users is located at /user/login, so the default login path. I need that page to be encrypted using SSL so people aren't transmitting their passwords in the clear.

I have Apache configured so that the site can be navigated either over HTTP or HTTPS. However, I want to implement some rewrite rules so that all requests other than /user/login are made over HTTP because it is INFINITELY faster and will result in better user experience. I refuse to use Secure Pages at this point in time because of the bugged support in Drupal Core and I'm not going to patch Core manually. That means I'm left with using Apache rewrite rules.

I have the following rules:

```
<VirtualHost *:80>
  ...
  RewriteCond %{HTTPS} off
  RewriteCond %{REQUEST_URI} ^/user/login$
  RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [L,R]
  ...
</VirtualHost>

<VirtualHost *:443>
  ...
  RewriteCond %{HTTPS} on
  RewriteCond %{REQUEST_URI} !^/user/login$
  RewriteRule ^/(.*) http://%{HTTP_HOST}/$1 [L,R]
  ...
</VirtualHost>

```

Now to me, that makes sense, but Drupal doesn't seem to like it.

What's happening is as follows:

1. If I navigate around the site using HTTP to any page other than /user/login, it works fine.
2. If I navigate to /user/login over HTTP, I get redirected to the front page.
3. If I navigate to any page over HTTPS, I get redirected to the front page over HTTP.

# Answer
> 8 votes
You don't really need /user/login to be served via https; you need the user login form to be submitted via https.

You should take a look at the module securepages\_prevent\_hijack -- not to use it directly, since it depends on securepages, but to see how the login form is altered. Like so:

```
function securepages_prevent_hijack_form_alter(&$form, &$form_state, $form_id) {
  // Secure the login form, so that we always have a secure connection to transmit the
  // initial cookie.  Also, protect the password in transit.
  if ($form['#id'] == 'user-login-form' || $form['#id'] == 'user-login') {
    $url = parse_url($form['#action']);

    $base_path = base_path();
    $path = (!strncmp($url['path'], $base_path, drupal_strlen($base_path)) ? drupal_substr($url['path'], drupal_strlen($base_path)) : $url['path']);
    $options = array('secure' => TRUE);
    if (isset($url['query'])) {
      $options['query'] = $url['query'];
    }
    $form['#action'] = securepages_url($path, $options);
  }
}

```

You should also figure out whether the cookie that Drupal is setting for you is secure or not. This will depend on your settings in php.ini. Check to see if you have set session.cookie\_secure to 1. If you have, then the cookie will not be sent to your http sessions, which could be why you are ending back at the home page (no session cookie == no session == no login info == log out). Of course, if the session.cookie\_secure is 0, then it might be possible for other parties to observe your session cookies in transit, and masquerade as your users. Perhaps you have already considered this risk, but it does bear some consideration.

# Answer
> 4 votes
I think the Secure Login module will also do what you want without requiring you to hack the core.

> Secure Login module enables the user login and other forms to be submitted securely via HTTPS, thus preventing passwords and other private user data from being transmitted in clear text.

# Answer
> 2 votes
I think you can try Secure Pages again, as since then they've release the new stable version.

For Drupal 8, check: Secure Login module.

See also: Enabling HTTP Secure (HTTPS).

---
Tags: 7, .htaccess
---


# Question
Title: Create a pager with "Yesterday", "Monday", "Sunday" etc
I have a view which through contextual filters show content created on the current day, and I would like to add a pager to allow users to go back in time one day at a time.

Say we visit the site on a Tuesday. So when viewing today's posts there is one link to the left which says "Yesterday" and no link to the right (since there are no future posts), and when this link is clicked we are show yesterdays content (Monday). The links are now "Sunday" to the left and "Today" to the right. Again we click the left link and are shown the content created on Sunday, and the links now show "Saturday" to the left and "Yesterday" to the right.

I've tried using exposed filters but they only output drop downs and only let me sort by asc/desc.

Is this possible?

# Answer
> 2 votes
Contextual range filter module ( https://drupal.org/project/contextual\_range\_filter ) seems to be the most suitable option as per the above requirement, or you can try the views day of week module ( https://drupal.org/project/views\_dow ).

I have created a view for day archive by using the contextual filter of view (without using the above modules) as below below:

but as your requirement seems to be creating a archive on the basis of week day therefore the best would be to use the above(Contextual range filter module, or the view day of week module), and than you can found the filter in the contextual filter of your view.

# Answer
> -1 votes
Yes it's possible. Just create a new views pager plugin as the default ones:

http://api.drupal.org/api/views/plugins!views\_plugin\_pager.inc/group/views\_pager\_plugins/7

I will need some custom coding to figure out the day of the week but it seems not really hard.

---
Tags: views, datetime, paging
---


# Question
Title: how to set date field not to display past date
In a content I need a date field for which I have used Date module. Widget type used for this is popup calender. But when the calender popup appears I want to display only today's date and future dates, I don't want to display any of the previous date, not even a single day.

How could this be achieved?

# Answer
> 3 votes
You can use the Field validation module to create validation for the date field.

You can follow below step to achieve this.

* Go to Administration -\> Structure -\> Content types and it will display the list of content type.
* Click on 'Manage Fields' links for your content type and it will display the list of fields for your content type.
* Edit your 'Date field' from the list of fields.
* Select '0 years from now' from the drop down 'Starting year' under 'More settings and values'. It will not display the previous year date in the popup.
* You can set the default values for the date field under 'default values' section.
* Save the settings.
* Edit again your fields.
* Click on 'Validation' tab in top of page.
* Click on 'Date range2' link in the page.
* Select 'value' from the drop down 'column'
* Select 'Cycle of date' as global and set '-0 day' for the 'Minimum date' textfield. Now, it will generate the error if date is less than today's date.

---
Tags: entities, datetime
---


# Question
Title: how i can reset the page num to 1 when i change to another exposed filter option?
Now,i have a view page with exposed filter(filter option:filterA,filterB) and full pager

when i go to the 3rd page of **filterA** , change the filter option to **filterB** ,i find the page redirect to the 3rd page of **filterB** ,what can i do to let it redirect to 1st page of **filterB**

# Answer
Create new filter group in the "Filter Criteria" section of view and add move both the exposed filters in the new group and than apply the "OR" operator between them as below:
> 2 votes

---
Tags: paging, views
---


# Question
Title: prompt in IE8 for secure pages produces altered layout
My Drupal 7 website looks fine in most browsers, but in IE8 I am getting the prompt:

> > "Do you want to view only the webpage content that was delivered securely? This webpage contains content that will not be delivered using a secure HTTPS connection, which could compromise the security of the entire webpage."

Then a "Yes" or "No"

If the person selects "yes" they are presented with MOST of the page, but odd things like the sidebar CSS and body content don't display properly. Is this an issue with securepages module or something else? Initially I had secure pages turned off because I moved from a dev server (without SSL) to production. But even after turning it on, I get this message. I have:

* Cleared the cache
* Run the security review module (passes on all points)
* Ensured the core and all modules are up to date.

Also, I have the following lines in my settings.php file:

```
$base_url = 'https://my-website-here.org';

```

and

```
$conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe? g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';
$conf['404_fast_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa-1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>';

```

Also, could jquery menu or Client-side adaptive image be causing a problem? The context module? These were all additions from the previous site that ran fine.

Any help appreciated!

# Answer
> 5 votes
The message you're getting in IE 8 is due to the fact that you're viewing your site through HTTPS, but some of your site's assets / resources are still being loaded through HTTP. If you look at the site in Chrome, you'll notice an icon to the right of the address bar which indicates the same warning about insecure content.

I would recommend going through all your templates / custom modules to make sure that any JS, CSS and iFrames (hope you have none of those heh) are all being served via HTTPs and not HTTP. Once nothing is being served via regular HTTP you shouldn't get that message anymore.

Hope this helps!

# Answer
> 1 votes
As a complement of the previous answer from AlexK and comment from Paul, I have applied this patch : https://drupal.org/node/1595062 in the 'sites/all/themes/omega/omega/templates/html.tpl.php' file and it solved this issue. You might need to know how to add a js file in your omega theme to make this work (https://drupal.org/node/1416128).

---
Tags: security
---


# Question
Title: How to merge two forms (with separate purposes) and have one submit?
**Problem**

I'm trying to combine two forms. A custom form and the user register form. I want the user to be able to fill in both and submit them together. How would I do this?

CONTEXT: The custom form creates a node, but you have to be logged in to do it. To lower the barrier I want users to be able to create the node and register on the same screen.

(Ideally the user register form won't appear if they're logged in.)

**So Far**

I tried calling two forms on the page but they have different submit buttons.

```
function postajob_page_callback() {
    $build = array();

    $build['form_one'] = drupal_get_form('postajob_form');
    $build['form_two'] = drupal_get_form('user_register_form');
  return $build;
}

```

So I called the user register validate and submit handlers in the custom form validate and submit calls.

```
function postajob_form_validate($form, &$form_state) {
     user_register_validate($form, $form_state);
     ...
 }

function postajob_form_submitform, &$form_state) {
     user_register_submit($form, $form_state);
     ...
 }

```

This calls the function but because the form doesn't contain any of the fields (i.e. username, email, password etc.) it throws a horrible error:

```
Notice: Undefined index: administer_users in user_register_submit() (line 3824 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Notice: Undefined index: pass in user_register_submit() (line 3827 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Notice: Undefined index: mail in user_register_submit() (line 3838 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Notice: Undefined index: #user in user_register_submit() (line 3840 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Warning: Creating default object from empty value in entity_form_submit_build_entity() (line 8009 of C:\XAMPP\htdocs\drupal5\includes\common.inc).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created, data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 165 [:db_insert_placeholder_1] => 1379868880 [:db_insert_placeholder_2] => a:6:{s:16:"ckeditor_default";s:1:"t";s:20:"ckeditor_show_toggle";s:1:"t";s:14:"ckeditor_width";s:4:"100%";s:13:"ckeditor_lang";s:2:"en";s:18:"ckeditor_auto_lang";s:1:"t";s:17:"mimemail_textonly";i:0;} ) in drupal_write_record() (line 7166 of C:\XAMPP\htdocs\drupal5\includes\common.inc).

```

So I tried to merge the forms using info from here and I added the following two lines of code just before the submit button in the form.

```
function postajob_form($form, &$form_state) {
      ....

     $extra = user_register_form($form, $form_state);
     $form = array_merge($form, $extra);

     $form['submit'] = array(
       '#type' => 'submit',
       '#value' => t('Submit'),
      );

    return $form;
}

```

This adds the form but seems to break the submit button and both submit buttons call the user\_register submit not the custom form submit. Any ideas?

# Answer
Ok so I've managed this in a little bit of a clumsy way. I didn't end up using `page_callback` at all.

Calling the `user_register_submit` and `validate` from inside the custom form functions works, they just don't have the values, so I added the form elements manually to my form.

Because it was a custom form I was able to copy and paste the respective form elements from `user_register_form`. That form calls `user_account_form` and I ended up having to paste both of them into my custom form.

That's the general answer. Here's the specifics I ended up using.

```
function mycustommodule_form($form, $form_state) {
... MY CUSTOM NODE FIELDS GO HERE....

global $user;

```

The first note here is I've wrapped all the user-register stuff in an if function so it will only run if the user is anonymous. If the user is logged in they'll never see this.

```
if (user_is_anonymous($user) || $user->uid == 1) {

  /*Theres a lot of stuff on the user form which only appears if you're an admin. That's not really important
   *because as an admin you won't be using it here, but i've left it in because I'm not sure entirely how
   *to take it our safely.*/
    $admin = user_access('administer users');

    // Pass access information to the submit handler. Running an access check
    // inside the submit function interferes with form processing and breaks
    // hook_form_alter().
    $form['administer_users'] = array(
       '#type' => 'value',
       '#value' => $admin,
    );

    // If we aren't admin but already logged on, go to the user page instead.

    $form['#user'] = drupal_anonymous_user();
    $form['#user_category'] = 'register';

    $form['#attached']['library'][] = array('system', 'jquery.cookie');
    $form['#attributes']['class'][] = 'user-info-from-cookie';

    // Start with the default user account fields.

```

Here in `user_register_form` it calls `user_account_form`.

```
user_account_form($form, $form_state);

```

This partly works. Unfortunately it doesn't ever display the role selector which appears in the normal register process. I also can't seem to set the role if I mimic the array structure. So instead I just pasted the relevant code from that function.

```
            $account = $form['#user'];
            $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

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

            // Account information.
            $form['account'] = array(
              '#type'   => 'container',
              '#weight' => -10,
            );
            // Only show name field on registration form or user can change own username.
            $form['account']['name'] = array(
              '#type' => 'textfield',
              '#title' => t('Username'),
              '#maxlength' => USERNAME_MAX_LENGTH,
              '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
              '#required' => TRUE,
              '#attributes' => array('class' => array('username')),
              '#default_value' => (!$register ? $account->name : ''),
              '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
              '#weight' => -10,
            );

            $form['account']['mail'] = array(
              '#type' => 'textfield',
              '#title' => t('E-mail address'),
              '#maxlength' => EMAIL_MAX_LENGTH,
              '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
              '#required' => TRUE,
              '#default_value' => (!$register ? $account->mail : ''),
            );

              $form['account']['pass'] = array(
                '#type' => 'password_confirm',
                '#size' => 25,
                '#description' => t('To change the current user password, enter the new password in both fields.'),
              );

              $form['account']['pass'] = array(
                '#type' => 'password_confirm',
                '#size' => 25,
                '#description' => t('Provide a password for the new account in both fields.'),
                '#required' => TRUE,
              );

            if ($admin) {
              $status = isset($account->status) ? $account->status : 1;
            }
            else {
              $status = $register ? variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS : $account->status;
            }
            $form['account']['status'] = array(
              '#type' => 'radios',
              '#title' => t('Status'),
              '#default_value' => $status,
              '#options' => array(t('Blocked'), t('Active')),
              '#access' => $admin,
            );

```

This is the part which works with roles. First the user is set to authenticated.

```
            $roles = array_map('check_plain', user_roles(TRUE));
            // The disabled checkbox sub-element for the 'authenticated user' role
            // must be generated separately and added to the checkboxes element,
            // because of a limitation in Form API not supporting a single disabled
            // checkbox within a set of checkboxes.
            // @todo This should be solved more elegantly. See issue #119038.
            $checkbox_authenticated = array(
              '#type' => 'checkbox',
              '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
              '#default_value' => TRUE,
              '#disabled' => TRUE,
            );

```

Then the role selector is displayed. Normally all the roles are shown at this stage. i.e. admin, other and my two custom roles. I only want my two custom ones so I unset the values I don't want people to select. i.e. admin and other. (authenticated is always unset).

```
            unset($roles[DRUPAL_AUTHENTICATED_RID]);
            unset($roles['3']);
            unset($roles['6']);
            dpm($roles);
            $form['account']['roles'] = array(
              '#type' => 'checkboxes',
              '#title' => t('Roles'),
              '#default_value' => (!$register && isset($account->roles) ? array_keys($account->roles) : array()),
              '#options' => $roles,
            );

```

Finally we have the end of the user\_register\_account function.

```
    // Attach field widgets, and hide the ones where the 'user_register_form'
    // setting is not on.
    $langcode = entity_language('user', $form['#user']);
    field_attach_form('user', $form['#user'], $form, $form_state, $langcode);
    foreach (field_info_instances('user', 'user') as $field_name => $instance) {
      if (empty($instance['settings']['user_register_form'])) {
        $form[$field_name]['#access'] = FALSE;
      }
    }
  }

```

I'm not sure this is a very slick way of doing it, so if anyone has any better ways of doing this, or improving what I've done I'd be really pleased to hear them.
> 1 votes

# Answer
Instead of using custom form you can add fields.
Go to
Administration » Configuration » People » Account settings

And In the manage fields tab u can add fields you want.

You can check the commerce\_auto\_product\_display module tar files which has used similar functionality of adding nodes to the already built form
> 1 votes

---
Tags: 7, forms
---


title: Breadcrumbs not showing proper path

text:
# Question
Title: Breadcrumbs not showing proper path
I have Drupal 7.2 installed, in my site there are menu items like Tech Docs, Doc Tree etc. For example in Tech Docs I have number of nodes.

After going to Tech Docs page, the breadcrumb looks like

```
Home >> Tech Docs

```

After clicking on a node in Tech Docs, the breadcrumb appeared like

```
Home >> node title

```

instead, I need the full path.

> Home \>\> Tech Docs \>\> node title

How can I solve this? Any ideas???

# Answer
An alternative is to use the Menu Position Module.

This module allows you to create a "rule" that says all of the nodes of type "whatever" go under this menu entry.

So, for your specific case, you would go to Structure \> Menu Position Rules and add a new one. Give it a name and location in the menu and specify which content type you want (or pages, or users, or terms).

This is beneficial as it means you don't need to add each node to the menu.
> 2 votes

# Answer
1. Make sure you have set correct patterns for the content type by going to /admin/config/search/path/patterns
2. If the node is not in menu then you will have to either put it in menu or create a Taxonomy that reflects your Main menu and add that to your content type so when creating nodes you select what section they live in. Then you can adjust patterns to something like: \[node:field-tag-section:parents:join-path\]/\[node:field-tag-section:name\]/\[node:title\]
3. Use a module like Easy Breadcrumbs ( https://drupal.org/project/easy\_breadcrumb ) which will give you more control over the breadcrumbs
> 0 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: Filtering Content based on URL arguments from Calendar Module
I have a page for the Calendar module on my site. Below the calendar, I have a table view that displays links based on taxonomy terms that correspond to the year-month format of the calendar module URL arguments (which change when the user changes the calendar month). I'm new to Drupal and can't figure out how to filter these results based on whether or not the content term matches the URL arg from calendar. Do I use contextual filters? Thanks for the help.

edit: I should mention I am using Drupal 7.

# Answer
> 1 votes
I am not exactly sure what you mean. Could your provide an example of what the URL looks like? Off the top of my head I think that you would just want to use view arguments.

# Answer
> 0 votes
You could accomplish this with a PHP filter on the view. Make sure to add Content:nid as a field in the view, set to exclude from display. First load the node info and see what it contains by using dpm():

```
<?php
$node = node_load($row->nid);
dpm($node);
?>

```

You should then be able to access the node's taxonomy term with:

```
$term = $node-> Something Here From dpm();

```

From here you could compare $term to arg(1) and return FALSE if they match.

---
Tags: datetime
---


title: Info on Drupal.settings and #attached

text:
# Question
Title: Info on Drupal.settings and #attached
I'm trying to use Drupal.settings for the first time to pass variables from PHP to JavaScript. The documentation on the topic is sparse and I have a few issues.

Is it possible to use #attached to pass through the settings rather than `drupal_add_js(array('myModule' => $settings), 'setting');`? The reason I am asking is that I've been told that `#attached` is the "correct" way to add settings. ( I know it is also the correct way to add files also, but not sure if it works with settings variables.)

I'm using the following code, but I can't get it to load under the DOM objects and I am stuck.

```
(function ($) {
   Drupal.behaviors.myModule = {
     attach: function(context, settings) {}
   };
});(jQuery);

```

Any advice would be greatly appreciated. Please bear in mind that this is the first time I've set out to use Drupal.settings, so every detail is welcome and appreciated.

# Answer
Many thanks for the responses posted.

As mentioned in the original question, the issue was not how to load CSS & JS files using #attached, but how to pass variables through to Drupal.settings using #attached and not drupal\_add\_js(). There are best practice issues surrounding drupal\_add\_js with regard to caching and availability under the DOM.

After some research I have the solution. The following example uses #attached to load a JS file **AND** to pass PHP variables through by attaching them to the $page array (render array).

```
hook_page_alter() {

  $my_PHP_variable  // or array of variables

  $page['header']['#attached']['js'] = array(
    drupal_get_path('module', 'mymodule') . '/js/mymodule.js' => array(),
    array(
      // Pass PHP variables to Drupal.settings.
      'data' => array('myModuleVarSet' => $my_PHP_variable),
      'type' => 'setting',
   ),
);
}

```

So the reason I want to do this is that I want to pass variable states from PHP/Drupal to a jQuery file, such as booleans etc.. With the example above, I can now access that 'state' using:

```
var myVar = Drupal.settings.myModuleVarSet.my_PHP_variable;

```

This is all done without touching drupal\_add\_js();
> 2 votes

# Answer
#attached can be used as follows.

```
$form['#attached']['js'][] = array(
  'data' => array(
    'xx_system' => array(
        'xx_code' => variable_get('xx_code', 'xx'),
        'xx_key' => variable_get('xx_key', 'xx'),
      ),
    ),
  'type' => 'setting',
);

```

With `drupal_add_js()`, you can use the following code.

```
 drupal_add_js(array('orgs' => $orgs), array('type' => 'setting'));
 drupal_add_js(drupal_get_path('module', 'module_name') . '/module_name.js');

```

In a JavaScript file, you can get the value of the variables as follows.

```
  Drupal.behaviors.module_name = {
    attach: function (context, settings) {
      var cities = Drupal.settings.orgs.cities;// you will get the cities value here
    }
  };

```
> 6 votes

---
Tags: javascript
---


# Question
Title: How to remove link of username in comment submission form
How can I remove the username link which is displayed in the comment submission form?

# Answer
> 2 votes
1. Simple solution is to use CSS. Just add a css rule to your theme's stylesheet.

```
#some .rule {display: none;}

```
2. Alternatively you can use `hook_form_alter` to modify the form and remove the link or change it to something else.

How to do it depends on your Drupal verion, see the API docs for reference or see altering form with hook\_form\_FORM\_ID\_Alter for usage on `hook_form_FORM_ID_alter` which is a specialized version of `hook_form_alter`.

# Answer
> 0 votes
Edit the content type (in Drupal 7 this is under Structure -\> Content types), and choose "Anonymous posters may not enter their contact information".

# Answer
> 0 votes
I would try doing this in the comments.css stylesheet. That was the easiest way for me. In the Zen theme the style was in comments.css

```
.comment .submitted /* The "posted by" information */ a {
        pointer-events: none;
       cursor: default;
       text-decoration:none;
       color:#000;
}

```

---
Tags: comments
---


# Question
Title: How can I theme the Views Exposed Filter Results page?
I'm trying to theme this page

```
http://208.87.22.137:50000/admin/rooms/bookings/list/kiosk/3?name=rest

```

which is the result of an exposed views filter. I have themed the node the views block is on but I'm not sure how to theme this page since it's not using node/NID.

Thanks.

# Answer
> 0 votes
You can use the devils module to get theme help. Also there is the `<?php print $classes; ?>` function that i have for instance on my div with the class container div. And there I see for example the class page-searchresults. Giving away that I can use page--searchresults.tpl.php as a template file for theming that page.

---
Tags: views, theming
---


# Question
Title: Is there a way to call a drupal ajax function on a multistep form without causing the form to resubmit?
I added a drupal ajax element to my multistep form but when it runs, it reloads the entire form.

The problem is, there is logic which is performed via a case structure for each step. When the ajax loads, the next step's logic is ran.

For example, the user is on step 2 of a 4 step form.

The user will cause an ajax call to load in a preview image. Triggering this ajax call loads step 3.

Triggering the same ajax call again will submit the form (step 4) causing very undesirable results. Is there some sort of secret voo doo code or argument I can use to prevent this?

# Answer
> 0 votes
The ajax call has a callback function that has a few commands including what it needs to render again. In this care i image it starts rendering the whole form again. You will see someting like this in the callback.

```
$commands[] = ajax_command_replace('#form', drupal_render($form));

```

And you want something like this

```
$commands[] = ajax_command_replace('#form .ajax-section', drupal_render($form['ajax section']));

```

---
Tags: ajax, forms
---


# Question
Title: How to display results of FormAPI form submitted in same block, minus the button(s) used to submit
I have a custom module that I have created to display 3 different images with a 'vote' beneath each image. The idea is to have the viewer vote on the one they like and it gets ranked against the other 2 images using votingAPI. What I am trying to do on callback is do the voting calculations (which I have), then replace the buttons with the voting percentage for each of the images. Wait 3 seconds and refresh the form with 3 more images.

What I am having difficulty with right now is just redrawing the form after submit, with the same 3 images and the percentage displaying instead of the button.

Here is the code I am using to define the block, block\_view, and form. Any suggestions or help would be greatly appreciated.

```
function steal_or_burn_block_info() {
  $blocks = array();
  $blocks['steal_or_burn'] = array(
    'info' => t('Steal or Burn Homepage Block'),
    'cache' => DRUPAL_NO_CACHE,
  );
return $blocks;
}

function steal_or_burn_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'steal_or_burn':
      $block['subject'] = ("Favorite Image");
      $block['content'] = drupal_get_form('steal_or_burn_form');
    }

  return $block;
}

function steal_or_burn_form($form, &$form_state) {

  $has_cookie = get_cookie('stealorburn');

  // Get the previous Steal or Burn NodeId's as an array
  $prev_sob_nids = get_sob_cookie_nids(COOKIE_NAME);

  // Load the NodeId's of the remaining Steal or Burn images in the database
  $unviewed_nids = load_sob_node_ids('stealorburn');

  // Find the difference between the previously viewed NodeId's against the full database
  // return an array of only those that have not yet been viewed
  if($prev_sob_nids) {
    $stealorburn_raw = array_diff($unviewed_nids, $prev_sob_nids);
  } else {
    $stealorburn_raw = $unviewed_nids;
  }
  // Randomize the array of not-yet-viewed Product images
  shuffle($stealorburn_raw);
  // Select the next 3 images to display
  $stealorburn = array_slice($stealorburn_raw, 0,3, TRUE);

  $i = 1;
  foreach($stealorburn as $value) {

  $node = node_load($value);
  $image = field_get_items('node', $node, 'field_brand_image');
  $image_rendered = field_view_value('node', $node, 'field_brand_image', $image[0], array(
    'type' => 'image',
    'settings' => array(
      'image_style' => 'thumbnail',
      ),
  ));
  $brand = $node->title;
  $item_name = field_get_items('node', $node, 'field_item_name');
  $item_id = $node->nid;
  $image_uri      = $image_rendered['#item']['uri'];
  $style          = 'steal_burn_home_image';
  $derivative_uri = image_style_path($style, $image_uri);
  $new_image_url  = file_create_url($derivative_uri);

  switch ($i) {
    case 1:
      $submit_button = 'steal_burn_first';
      break;
    case 2:
      $submit_button = 'steal_burn_second';
      break;
    case 3:
      $submit_button = 'steal_burn_third';
      break;
  }

  // Block output in HTML with div wrapper
  $form['steal_or_burn_form'][]['image'] = array(
      '#prefix' => "<div class='steal_burn_image_block_$i'>",
      '#type' => 'markup',
      '#markup' => "<img src='$new_image_url'>",
    );
  $form['steal_or_burn_form'][]['brand'] = array(
      '#prefix' => '<div class="steal-or-burn-field-title">',
      '#type' => 'markup',
      '#markup' => $brand,
      '#suffix' => '</div>',
    );
  $form['steal_or_burn_form'][]['item_name'] = array(
      '#prefix' => '<div class="steal-or-burn-field-item-name">',
      '#type' => 'markup',
      '#markup' => $item_name[0]['value'],
      '#suffix' => '</div>',
    );
  $form['steal_or_burn_form'][]['product_id'] = array(
      '#type' => 'hidden',
      '#value' => $item_id,
    );
  $form['steal_or_burn_form'][]['submit'] = array(
      '#type' => 'submit',
      '#id' => $submit_button,
      '#name' => $node->nid,
      '#value' => t('Vote'),
      /*'#submit' => array('steal_or_burn_submission_callback'),*/
  );

  $i++;
} // end block image loop

return $form['steal_or_burn_form'];

}

```

# Answer
You would need to have an AJAX callback.

You would need to wrap your submit buttons --- (or your whole form, doesn't matter). Set the 'wrapper' with the ID of that HTML element ; and then set the name of your ajax callback function in 'callback'. Your ajax callback returns the form element (in case you're just wrapping the submit buttons) or the whole form. You shouldn't do any change in the form or its state as mentioned in the documentation. You do the changes in your form builder function. In this case, that will be `steal_or_burn_form`. But, you can change a form *element* and then return that.

Read the documentation for more info. Also, this one's a good example of a submit-driven ajax:

Form Builder

Ajax Callback of the form above
> 0 votes

# Answer
After a few more days work tweaking the form, I was able to get it to work by modifying this form and adding a js file for some of the jQuery functionality I just couldn't figure out how to accomplish directly in the form or through helper functions. Here is my updated version of the form:

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

  get_cookie('stealorburn');

  // Get the previous Steal or Burn NodeId as an offset
  $prev_sob_offset = get_sob_cookie_offset(COOKIE_NAME);

  // Load the NodeId's of the remaining Steal or Burn images in the database
  $unviewed_nids = load_sob_node_ids('stealorburn');

  // Find the index of the last viewed NodeId against the full database
  // return an array of the next 3
  if($prev_sob_offset) {
    // There was an offset saved in the cookie
    if($prev_sob_offset <= (count($unviewed_nids) - 3)) {
      $stealorburn = array_slice($unviewed_nids, ($prev_sob_offset), 3);
      $sob_offset = $prev_sob_offset + 3;
    } else {
      $stealorburn = array_slice($unviewed_nids, 0, 3);
      $sob_offset = 3;
    }
  } else {
      $stealorburn = array_slice($unviewed_nids, 0, 3);
      $sob_offset = 3;
  }

  //set hidden field for the sob_offset so it may be saved during form-submit
  $form['cookie_offset'] = array(
    '#type' => 'hidden',
    '#default_value' => $sob_offset,
  );

  $i = 1;
  foreach($stealorburn as $value) {

    $node = node_load($value, NULL, TRUE);

    $image = field_get_items('node', $node, 'field_brand_image');
    $image_rendered = field_view_value('node', $node, 'field_brand_image', $image[0], array(
      'type' => 'image',
      'settings' => array(
        'image_style' => 'thumbnail',
        ),
    ));
    $brand = $node->title;
    $item_name = field_get_items('node', $node, 'field_item_name');
    $item_id = $node->nid;

    $image_uri      = $image_rendered['#item']['uri'];
    $style          = 'steal_burn_home_image';
    $derivative_uri = image_style_path($style, $image_uri);
    $success        = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
    $new_image_url  = file_create_url($derivative_uri);

    switch ($i) {
      case 1:
        $submit_button = 'steal_burn_first';
        break;
      case 2:
        $submit_button = 'steal_burn_second';
        break;
      case 3:
        $submit_button = 'steal_burn_third';
        break;
    }

    // Block output in HTML with div wrapper
    $form['image'.$item_id] = array(
      '#prefix' => "<div class='steal_burn_image_block_$i'>",
      '#type' => 'markup',
      '#markup' => "<img src='$new_image_url'>",
    );
    $form['brand'.$item_id] = array(
      '#prefix' => '<div class="steal-or-burn-field-title">',
      '#type' => 'markup',
      '#markup' => $brand,
      '#suffix' => '</div>',
    );
    $form['item_name'.$item_id] = array(
      '#prefix' => '<div class="steal-or-burn-field-item-name">',
      '#type' => 'markup',
      '#markup' => $item_name[0]['value'],
      '#suffix' => '</div>',
    );
    $form['product_id' . $item_id] = array(
      '#type' => 'hidden',
      '#default_value' => $item_id,
      '#value' => $item_id,
    );

    $form['submit_'.$item_id] = array(
      '#type' => 'submit',
      '#id' => $submit_button,
      '#name' => $item_id,
      '#value' => t('Vote'),
      '#prefix' => '<div id="vote_btn_'.$item_id.'" class="steal-or-burn-vote">',
      '#suffix' => '</div></div>',
      '#ajax' => array(
        'callback' => 'steal_or_burn_ajax_callback',
        'event' => 'click',
        'progress' => array('type' => 'none'),
      ),
    );

    $i++;
  } // end block image loop

  $form['#attached']['js'] = array
  (
    array
    (
      'type'  => 'file',
      'data' => drupal_get_path('module', 'steal_or_burn') . '/steal_or_burn.js',
    ),
  );

  return $form;
}

function steal_or_burn_ajax_callback($form, &$form_state) {
  //function steal_or_burn_submit($form, &$form_state) {

  while (list($key, $value) = each($form_state['values'])) {
    if(substr_count($key, 'product_id') == 1) {
      if(!is_null($value) ) {
        $raw_values[] = $value;
      }
    }
    if($value == 'Vote') {
      $voted = $key;
    }
  }

  for($i = 0, $size = count($raw_values); $i < $size; ++$i) {
    if($raw_values[$i] != $voted) {
      $not_voted[] = $raw_values[$i];
      $votes[$raw_values[$i]]['entity_type'] = 'stealorburn';
      $votes[$raw_values[$i]]['entity_id'] = $raw_values[$i];
      $votes[$raw_values[$i]]['value_type'] = 'points';
      $votes[$raw_values[$i]]['value'] = 0;
    } else {
      $votes[$voted]['entity_type'] = 'stealorburn';
      $votes[$voted]['entity_id'] = $voted;
      $votes[$voted]['value_type'] = 'points';
      $votes[$voted]['value'] = 100;
    }
  }

  // Need to set criteria to be an empty array, otherwise it would reset votes.
  $criteria = array();
  // Add vote data to the database for these 3 images
  $current_vote = votingapi_set_votes($votes, $criteria);

  $submitted_image_nids = array_values($raw_values);

  for($i = 0, $size = count($submitted_image_nids); $i < $size; ++$i) {
    $image_nid = $submitted_image_nids[$i];
    $votes_this_round[] = $current_vote['stealorburn'][$image_nid][2]['value'];
  }

  $total_votes = array_sum($votes_this_round);

  for($i = 0, $size = count($votes_this_round); $i < $size; ++$i) {
    $points[$i] = intval(($votes_this_round[$i] / $total_votes) * 100);
  }
    //Using the $plug variable to make sure the sum of results = 100%
    $plug = 100 - array_sum($points);
    if($plug > 0) {
      $lowest_value = min($points);
    }

    foreach($points as $key => $value)
    {
      if($value == $lowest_value) {
        $points[$key] = $value + $plug;
      }
    }

  $tracking_votes = array_combine($submitted_image_nids, $points);

    $commands = array();
    foreach($tracking_votes as $key => $value) {
      $replace_id = "#vote_btn_$key";
      $commands[] = ajax_command_replace($replace_id, drupal_render($form[$replace_id]));
      $vote_percentages[] = $value . "%";
    }

  // Include a custom function that will be called in the JavaScript file:
  $commands[] = array
  (
    // The command will be used in the JavaScript file
    'command' => 'stealorburnCallback',
    // Pass the form values of each element to the JS function:
    'votePercentages' => $vote_percentages,
  );

  //delete the cookie before writing the new one
  steal_or_burn_cookie_delete('stealorburn');

  $new_sob_offset = $form_state['values']['cookie_offset'];

  //write the cookie with updated index
  $steal_or_burn_to_cookie = $new_sob_offset;
  steal_or_burn_cookie_save('stealorburn', $steal_or_burn_to_cookie);

  // And finally, we will return all of our commands to the system to be executed:
  return array('#type' => 'ajax', '#commands' => $commands);
  }

```

The contents of the JS file are primitive. Right now the page is getting reloaded after 2 seconds of displaying the results. My next challenge is to make a function or alter the form in a way that I can reload it after the 2-second delay without having to reload the whole page.

\**myjsfile.js

```
(function($, Drupal)
{
    // Our function name is prototyped as part of the Drupal.ajax namespace, adding to the commands:
    Drupal.ajax.prototype.commands.stealorburnCallback = function(ajax, response, status)
    {
        $('.steal-or-burn-field-title').each(function(index, obj){
            if(index == 0) {
                $("<div class='steal-or-burn-percentage'>"+response.votePercentages[0]+"</div>").insertBefore(this);
            } else if (index == 1) {
                $("<div class='steal-or-burn-percentage'>"+response.votePercentages[1]+"</div>").insertBefore(this);
            } else if (index == 2) {
                $("<div class='steal-or-burn-percentage'>"+response.votePercentages[2]+"</div>").insertBefore(this);
            }
        });

        setTimeout(function() {
            location.reload(true);
        }, 2000);

        return false;

    };
}(jQuery, Drupal));

```
> 0 votes

---
Tags: 7, redirection, forms, nodes
---


# Question
Title: Why does the zen theme load javascript in the head element?
Most tutorials for jQuery recommend loading javascript before the closing body tag so that the rest of the page can load first. However the Zen theme (im not sure about others) doenst do this. Why is this the case?

# Answer
Some contrib modules only work correctly if jQuery and other scripts are in `<head>`.

Check out the Magic module or the AdvAgg module, which gives you greater control over how CSS and JS files are handled in your theme.
> 0 votes

---
Tags: javascript, theming
---


title: Just list one product variation

text:
# Question
Title: Just list one product variation
I'm developing a videogame store with Commerce (I'm n00b in Drupal), so for example I'm adding a new game "GTA V", GTA has versions to XBOX360 and PS3, so I'm trying to create the product and add two variations for PS and XBOX with different prices and some stuff, but I don't need a product page where the user selects PS or XBOX version, because I'm splitting my site by consoles, so if the user is in XBOX section, I need to list only the XBOX variation and not the PS variation.

I'm trying to achieve this because I don't wanna repeat myself with description, videos, etc of video games, so in the "GTA V" example I will write just one description and not two (for PS and XBOX) that will be the same.

# Answer
You can just use views to filter on the catalog pages for product variations if they are set. You should take a look at http://www.drupalcommerce.org/user-guide/products the guide will help you create product variations, you can then create a view for the catalog, you can then create a exposed filter (lets the users change the filter value) for product variation so they user can select PS3 or XBOX and get only those products on the filter. But if you went to that page, you would still need to select "PS3" or "XBOX" to place a order.
> 2 votes

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


# Question
Title: customize destination for user_login with modal_forms link?
I am using the Login Destination module to form rules for login customization. But they seem to be failing when modal\_form is opened for the user login. Can any one suggest something ?

# Answer
> 0 votes
You can checkout the following for ctools modal\_form issues https://drupal.org/node/1329040 there is some code there that should allow you to set the redirect url using PHP to where you need it to go.

You should also double check that your modules are both up to date, there did not seem to be any open issues about computability between the two modules.

---
Tags: users
---


# Question
Title: Is there a way to add managed_file field to theme-settings.php?
Anytime I add a managed\_file field to theme-settings.php, the field works, however, it gets saved with a status of 0 in the database.

When I add a submit handler to the theme settings form, I get a " Call to undefined function" error.

Of course, when I remove the managaed\_file field, the undefined function error goes away and the submit handler fires as normal.

Has anyone tried doing this? Is there another way around this problem?

thanks! david

# Answer
> 3 votes
The theme-settings.php is included from system\_theme\_settings(), which executes the following code.

```
// Call engine-specific settings.
$function = $themes[$key]->prefix . '_engine_settings';
if (function_exists($function)) {
  $form['engine_specific'] = array(
    '#type' => 'fieldset',
    '#title' => t('Theme-engine-specific settings'),
    '#description' => t('These settings only exist for the themes based on the %engine theme engine.', array('%engine' => $themes[$key]->prefix)),
  );
  $function($form, $form_state);
}

```

```
foreach ($theme_keys as $theme) {
  // Include the theme-settings.php file.
  $filename = DRUPAL_ROOT . '/' . str_replace("/$theme.info", '', $themes[$theme]->filename) . '/theme-settings.php';
  if (file_exists($filename)) {
    require_once $filename;
  }

  // Call theme-specific settings.
  $function = $theme . '_form_system_theme_settings_alter';
  if (function_exists($function)) {
    $function($form, $form_state);
  }
}

```

Unfortunately, the file is not loaded from Drupal before any validation/submission handlers for that form are invoked.

When form\_cache\_get() is called, the following code is executed.

```
    foreach ($form_state['build_info']['files'] as $file) {
      if (is_array($file)) {
        $file += array('type' => 'inc', 'name' => $file['module']);
        module_load_include($file['type'], $file['module'], $file['name']);
      }
      elseif (file_exists($file)) {
        require_once DRUPAL_ROOT . '/' . $file;
      }
    }

```

As `form_get_cache()` seems called before a form is validated/submitted, you could use the following code. (Replace mytheme with the short name of your theme.)

```
function mytheme_form_system_theme_settings_alter(&$form, &$form_state) {
  $theme = $GLOBALS['theme_key'];
  $themes = list_themes();

  $form_state['build_info']['files'][] = str_replace("/$theme.info", '', $themes[$theme]->filename) . '/theme-settings.php';
}

```

# Answer
> 0 votes
Another potential solution (the previous one did not work for me) would be to add some code in the theme-settings.php file that checks to see if the uploaded image is saved and if not saves it. This is not really the proper place to do something like this, but it is simple and it works. Here is the code I used.

```
// Defining the managed_file form element:
$form['header']['mytheme_header_image_custom'] = array(
    '#title'        => t('Custom Header Image File'),
    '#type'         => 'managed_file',
    '#description'  => t('Upload a custom header image for your site. Dimensions to display properly must be: 968 x 300'),
    '#default_value' => theme_get_setting('mytheme_header_image_custom'),
    '#upload_location' => 'public://theme_header_images/',
    '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
    ),
);

// Setting the status to saved permanently if needed.
$image_custom_index = theme_get_setting('mytheme_header_image_custom');
if (isset($image_custom_index)) {
    $fid = theme_get_setting('mytheme_header_image_custom');
    $file = file_load($fid);
    if ($file->status == 0) {
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
        // Sets a Drupal message just for clarity.
        drupal_set_message(t('Header image saved.'), 'status');
    }
}

```

---
Tags: 7, forms
---


# Question
Title: How to change the field name in the url when using views exposed sort?
I've read a few posts on this and there does not seem to be an answer to that, is that right?

My exposed filters allow the user to change the sorting, but the url is kinda bad:

`?sort_by=field_rating` instead of just `?sort_by=rating`, for instance. Can this be achieved somehow? Is it advisable to try out better exposed filters module when you have already kind of customized your exposed filters? /:

# Answer
For `order_by` filter you can just set the filter identifier:

Although there is no option to set the identifier for `sort_by` filter, you can achieve your goal by altering the form.

**Example**

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

  if ($form['#id'] == 'YOUR-FORM-ID') {

    // fields which you want to rename
    $form_state['my_custom_names'] = array(
      'field_rating_value' => 'rating'
    );

    // rename option values
    foreach ($form_state['my_custom_names'] as $name => $new_name) {

      $form['sort_by']['#options'][$new_name] = $form['sort_by']['#options'][$name];
      unset($form['sort_by']['#options'][$name]);

      if ($form_state['input']['sort_by'] == $name) {
        $form_state['input']['sort_by'] = $new_name;
      }
    }

    // the custom submit handler need to be fired before the original one
    array_unshift($form['#submit'], 'my_custom_exposed_form_submit');
  }
}

/**
 * An additional submit handler for exposed filters.
 */
function my_custom_exposed_form_submit(&$form, &$form_state) {

  // set the form state values to their original names.
  foreach ($form_state['my_custom_names'] as $name => $new_name) {
    if ($form_state['values']['sort_by'] == $new_name) {
      $form_state['values']['sort_by'] = $name;
    }
  }
}

```

*Make sure to replace `YOURMODULE` and `YOUR-FORM-ID` with proper names.*
> 6 votes

# Answer
That's how views are built, the only way to fix that would be to change how you filter, you can try using views contextual filters and see if that works for you. But exposed views filters equate to query strings with field names, otherwise how would views know that "rating" actually means "field\_rating" without adding additional overhead to the database.
> 0 votes

---
Tags: views, uri
---


# Question
Title: Disallow purchase if coupon code is not entered?
I have a product that is part of a Groupon-like promotion. The customer purchases a promo code at the Groupon-like website and those coupon codes are entered into my Ubercart system as 100%-off discounts. I want to only allow this particular product to be purchased when one of those specific codes has been entered into the cart. In other words, the credit card entry panel would not appear until they have entered a valid code for that product's promotion.

Is that possible? If so, how might I accomplish that? Rules/Conditional Actions?

Thanks!

# Answer
There is no easy way to do this sadly, your best bet would be to try and play around with `hook_form_validate` or `hook_form_submit` on the ubercart form submit and see if you can find the field values in one of the submitted panes.

If that doesn't work then your best bet would be to try and code your own "pre review order" coupon box, that hooks into the cart view page. So what I am thinking is

* Users goes to /cart
* Has the listing of the items in the cart
* Has the "coupon stuff" at the buttom, but part of the "Checkout" form (use `form_alter` for example)
* And use the `hook_form_validate` hook to verify it has data, and the coupon is good, then proceed
> 0 votes

---
Tags: 6, ubercart
---