# Question
Title: Why cannot edit views because "The requested page could not be found."
I am having a sudden error on a drupal site I inherited in that I cannot edit views anymore, any of them. One moment I am able to open a view for editing by clicking the edit link on the all views list and the next moment the edit link results in

> The requested page could not be found.

for all views.

The *only* change I made was to change the display on a field from do not display to display for a specific view. I then updated the view and saved it. At first the save did not work, but then I clicked again and it saved. The field I wanted displayed but now I cannot reach the edit screen for any of the views.

The log only references the 404 error, but nothing as to why, my apache log is equally unhelpful in determining why this has become the case suddenly.

The rest of the site, so far as I can tell, is running as usual and I can still list the views and see the actual views when going to their paths.

**Update** (*problem solved but question remains*): I `drush cc all` (cleared the cache) and the view edit pages are reachable again. Though for future reference, what might be the reason that this happened? I feel like this isn't the first time I've found Drupal acting unpredictable and that clear the cache sets it straight.

# Answer
> 2 votes
The update to your original question suggests that the problem wasn't with Views itself.

When you do a `drush cc all`, it essentially calls `drupal_flush_all_caches()`, which

* clears the JS cached files
* clears the CSS cached files
* rebuild2 the list of themes
* rebuilds the theme registry
* **rebuilds the menus**
* rebuilds the list of content types
* deletes all temporary items from the cache bins, and all items that had TTLs set which have expired

What I suspect, is that something happened to the menu tables and the cached entries were not fully rebuilt (I have seen this before). Typically, it happens when you do a cache clear from the **Performance** page, and the process barfs, normally from running out of memory or timeouts because of load (I have seen the later on some servers).

When you did this from the command line, the menu tables got fully rebuilt that time, and your pages are available.

You should keep an eye on the amount of memory your site is using for page requests from a stale cache, and compare with the PHP `memory_limit` on your site. If the two are close, you may have periodic overages which will cause sporadic problems. Also make sure your Apache and MySQL are well tuned, as poor tuning can cause process stacking during cache clears, which can avalanche into a mess.

---
Tags: views, 6
---


# Question
Title: What should be the path to the file while using #attached in a custom_module_block_view()?
I have created a custom module and was trying to add javascript file to a block using #attached method which was described here. I am confused with the Path/to/file as I have tried to give a full path which is `"/var/www/html/sites/all/modules/custom_module/js/file.js"`. and shorter path `"js/file.js"`

but it doesn't load.

It just say `file_get_contents("/var/www/html/sites/all/modules/custom_module/js/file.js"): unable to load, no such file or folder present /var/www/html/common.inc .....`

Why I am getting the file\_get\_contents error when I am not using this method?

# Answer
> 1 votes
You should use `drupal_get_path()` function to construct the path of your asset file (in your case the JS file).

To include the `YOUR_MODULE.js` file which sits in a subfolder `js`, part of your custom module

```
$block = array
(
    'subject' => t('My block title'),
    'content' => array(
        '#markup' => '<p>' . t('This is some text that will go in the block.') . '</p>',
        '#attached' => array(
            'js' => array(drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/YOUR_MODULE.js'),
        ),
    ),
);

```

---
Tags: javascript, blocks
---


# Question
Title: How do I make a custom entity update or create automatically update the solr index?
I have implemented a custom entity type which is essentially identical to what the Model module does, with a few additional fields.

I have followed the Apachesolr User module to understand how to index my custom entities in the solr index. But when I add, or update and existing, entity the solr index is not automatically picking up the changes.

```
/**
 * Implements hook_apacheolr_entity_info_alter().
 */
function my_entity_apachesolr_entity_info_alter(&$entity_info) {
  $entity_info['my_entity']['indexable'] = TRUE;
  $entity_info['my_entity']['status callback'][] = 'my_entity_status_callback';
  $entity_info['my_entity']['document callback'][] = 'my_entity_solr_document';
  $entity_info['my_entity']['reindex callback'] = 'my_entity_solr_reindex';
  $entity_info['my_entity']['index_table'] = 'apachesolr_index_entities_my_entity';

  $entity_info['my_entity']['result callback'] = 'my_entity_result';
}

```

This is the hook I had to implement to index my content, the various callbacks are irrelevant. It is worth noting the index table needs to be implemented in hook\_schema() as well. This can be easily seen in Apachesolr User

# Answer
Originally I thought I had to implement my own hooks but after seeing that apachesolr took care of deletes I wondered why it hadn't taken care of my updates and inserts.

There is actually a apachesolr\_entity\_update/insert() which calls apachesolr\_entity\_should\_index(). That checks whether your entity info (returned by entity\_get\_info($entity\_type)) has the following key set:

```
$info['bundles'][$bundle]['apachesolr']['index']

```

Where $bundle is the $entity bundle. This made it pretty easy for me to figure out that I just had to add some stuff to my hook\_entity\_info\_alter():

```
function my_entity_entity_info_alter(&$entity_info) {
  foreach (my_entity_get_types() as $type => $info) {
    $entity_info['my_entity']['bundles'][$type] = array(
      'apachesolr' => array('index' => TRUE),
    );
  }
}

```

After adding that and clearing cache I no longer needed my entity update/insert hooks.

**Note: Don't get this confused with hook\_apachesolr\_entity\_info\_alter like I did!**

***Original Answer***

I found the function apachesolr\_index\_get\_entities\_to\_index() which checks the indexer table for your entity\_type for a changed timestamp that's greater than what it's last seen (I have yet to find out where it sets that). Essentially we just need to automate the updating of that table. This can be done with 2 hooks:

hook\_entity\_insert() hook\_entity\_update()

```
/**
 * Implements hook_entity_insert().
 */
function my_entity_entity_insert($entity, $type) {
  // Update our indexer table
  if ($type != 'my_entity') {
    return;
  }
  $indexer_table = apachesolr_get_indexer_table($type);

 // Insert the new entity into a fictional table of all entities.
  $info = entity_get_info($type);
  list($id) = entity_extract_ids($type, $entity);
  db_insert($indexer_table)->fields(array(
    'entity_type' => $type,
    'bundle' => $entity->type,
    'entity_id' => $id,
    'changed' => REQUEST_TIME,
  ))->execute();
}

/**
 * Implements hook_entity_update().
 */
function my_entity_entity_update($entity, $type) {
  // Update our indexer table
  if ($type != 'my_entity') {
    return;
  }
  $indexer_table = apachesolr_get_indexer_table($type);

  db_update($indexer_table)
    ->fields(array(
      'changed' => REQUEST_TIME,
    ))
  ->condition('entity_id', $entity->entity_id)
  ->execute();
}

```

You may have to add this line into the insert statement in hook\_entity\_insert() if you have a status coming from $entity (mine is always 1 so the db table defaults it to that).

```
'status' => $entity->status,

```

**Edit:** You may be wondering "What about delete??", this seems to be taken care of by apachesolr\_entity\_delete, I'm going to see why apachesolr\_entity\_update and apachesolr\_entity\_insert didn't take care of my entities. However this answer is still valid.
> 4 votes

# Answer
I develop a custom module to create a new entity "my\_entity" on drupal 7. I use:

* my\_entity\_entity\_info() ==\> Declare my new entity.
* my\_entity\_schema() ==\> create the database table.

Then, I'd like to make this entity available for apache solr indexing.

Do I have to create only the hook "my\_entity\_entity\_info\_alter" into my custom module as you described above? Do I need to implement the hook "my\_entity\_apachesolr\_entity\_info\_alter" too?

I'm very confused with these two hooks "my\_entity\_entity\_info\_alter" and "my\_entity\_apachesolr\_entity\_info\_alter".

```
 function my_entity_entity_info_alter(&$entity_info) {
     foreach (my_entity_get_types() as $type => $info) {
          $entity_info['my_entity']['bundles'][$type] = array(
          'apachesolr' => array('index' => TRUE),
          );
     }
 }

```

Thanks a lot
> 0 votes

# Answer
Thank you so much for your help. It was very confusing at the beginning but I figured out how Apache solr handles an entity.

This is the process I implemented:

1 - my\_entity\_entity\_info() ==\> Declare my new entity into a custom module.

2 - my\_entity\_schema() ==\> create the entity database table for this new entity

3 - my\_entity\_entity\_info\_alter() ==\> to mark this entity indexable by Apache solr

```
function my_entity_entity_info_alter(&$entity_info) {
     $entity_info['my_entity']['apachesolr']['indexable'] = TRUE;
}

```

4 - my\_entity\_apachesolr\_entity\_info\_alter() ==\> to tell Apache solr to index your entities "my\_entity" through the callbacks defined.

```
function my_entity_apachesolr_entity_info_alter(&$entity_info) {
  $entity_info['my_entity']['indexable'] = TRUE;
  $entity_info['my_entity']['status callback'] = 'my_entity_status_callback';
  $entity_info['my_entity']['document callback'][] = 'my_entity_document';
  $entity_info['my_entity']['reindex callback'] = 'my_entity_solr_reindex';
  $entity_info['my_entity']['index_table'] = 'my_entity_index_entities_my_entity';
}

```

For information:

* \['status callback'\] = 'my\_entity\_status\_callback'; ==\> Is this entity ready to be indexed?
* \['document callback'\]\[\] = 'my\_entity\_document'; ==\> Which data to send to Apache Solr?
* \['reindex callback'\] = 'my\_entity\_solr\_reindex'; ==\> to refresh the entity index database table where Apache solr takes a look to know what to send
* \['index\_table'\] = 'my\_entity\_index\_entities\_my\_entity'; ==\> the entity index database table name -- that is different than the table defined in the hook my\_entity\_schema() -- DON'T GET CONFUSED!! Apache solr has is own database table for entity information.

Correct me if I wrong. Thanks

I hope that could help some other folks as myself after hours surfing on forums and banging my head against the wall.
> 0 votes

---
Tags: 7, search, entities
---


title: Close Fieldset when another is opened

text:
# Question
Title: Close Fieldset when another is opened
I have a form at http://turtle.umbrellamedia.net/build

What I would like is to be able to open each field set group, and close the others. For instance, if I click on "Front Color" the "Type of Phone" field set would close.

Any help would be appreciated.

Edit: I am using the forms API for this and have a custom module built that made these form items.

# Answer
Sounds like a case for a jquery.ui accordion fieldgroup setup instead.

e.g: If you install https://drupal.org/project/field\_group

I believe you can also use those group styles in custom FAPI forms. At least, I've done that for vertical tab, but maybe that's core now...

You could also add the javascript manually with

```
drupal_add_library('system', 'ui.accordion');

```

and use it as per: http://jqueryui.com/accordion/
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to handle free and paid orders with post processing?
I'm going around in circles trying to use Drupal Commerce to make an ecommerce site where some orders cost money and some don't (because some users have coupons that make products free).

I've set up the Checkout process as seen in the screenshot below and have created a rule as such

* Rules Event: Process checkout pane
* Rules Conditions: Price comparison (commerce order = $0)
* Rules Actions:
    + Change pane properties (disable billing information, off-site payment redirect, Payment)
    + Update the order state to (pending/complete)

With this setup when the user goes through without a coupon it all works fine. When the user uses a coupon to get the price to zero on the Checkout page the user presses the `Continue to next step` button and goes to an empty Review page (the panes have been set to disabled so there is nothing to see) and they can't progress any further.

Pressing the `Continue` button on that page just bounces them back to the same page. If they press `Cancel` and go back to the shopping cart, then on through checkout and press "Continue to next step" again (the coupon has been remembered and the total is still $0) then get sent to the Checkout Complete page and `hook_commerce_checkout_complete($order)` is called.

I've tried adding extra actions to the rule, to complete the checkout or change the order status, but they have strange side effects like going to the Review page anyway, or calling that hook twice.

Can anyone help me set up the checkout and rules so that a free order goes straight to complete from the checkout page, whilst still maintaining the normal path for orders that require payments?

# Answer
> 0 votes
You would be better to implement a custom payment method that can be active when the order has a 0 balance.

If the order has payment required, use the standard payment method. If the order has no payment required, complete checkout.

e.g: https://drupal.org/project/commerce\_no\_payment

---
Tags: 7, commerce
---


# Question
Title: View nodes in a listing only, not on their own?
I have created two node-types: 'match' and 'set'. When a 'match' node is viewed it displays a listing of several 'set' nodes. I've acheived this by calling `node_load_multiple` in `hook_node_view`. That's all 'set' nodes do: they are listed by a match node. 'Set' nodes can be created, edited and deleted, but I only want the user to be able to view them in listings.

So, I want to deny access to viewing 'set' nodes on their own page at node/1 or whatever. I've denied access to 'set' nodes using the node access mechanism, but then they don't appear in my listing either.

How can I set these nodes so that they can only be viewed in my listing?

The only thing I can think of is not to call `node_load_multiple` but to write by own `db_select` query to retrieve all the necessary 'set' nodes to list in a match 'node': a bit messy.

Hope this makes sense. I open to any suggestions. Thanks.

# Answer
> 0 votes
I believe you could use the node\_view hook. In that hook you can check for the node type (set) and view mode (full) and add your logic. If you're using a reference field to relate the set to the match then you could probably redirect the user back to the match.

When you're listing sets on the match page you could also not render them as links a user doesn't try to view the set directly.

---
Tags: nodes
---


# Question
Title: Admin Module frontpage has gone - How do I get it back?
I took the liberty to upgrade to v7.25 today; four hours later (after trying to get back to where I was 8 hours before) I had to used Backup and Migrate to restore my previous v7.24. I've tried numerous update.php attempts but my Admin Module page just will not show via /admin/modules path. I can get admin/uninstall but any attempt to get back to /admin/modules gives me a black white screen so I cannot manage any modules.

Can anyone suggest a solution. I'm aware of Drush and have it to hand, but not too aufait at present (I'm on an Ubuntu desktop with localhost).

I do get a PDO error starting as: PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'has\_children' in 'field list':......

if that has any influence.

Thanks.

# Answer
Try using phpMyAdmin. Backup again, then show the system table. Change the status of the problem module from 1 to 0 from phpMyAdmin. Then refresh Drupal pages to see if it resolves it. Other modules might be the issue so try process of eleimaination, toggling 1 to 0. If the 0 works, try and uninstall then reinstall if practical.
> 0 votes

---
Tags: 7
---


title: Create a file programmatically

text:
# Question
Title: Create a file programmatically
I am working on a cron job that is creating a backup file. I want to move the file to the private file directory but I am having trouble figuring out how to do this. The cron job creates a file in a folder called /temp in the root of my site. I've been trying to use `file_save_upload` to move the file, but this isn't working

```
$gzip_file = $_SERVER['DOCUMENT_ROOT'] . '/temp/myfile.gz';
$private_file = 'private://myfolder/myfile.gz';
$drupal_file = file_save_upload($gzip_file,array(),$private_file,FILE_EXISTS_REPLACE);

```

I am not getting an error and $drupal\_file equals false. The private folder exists and I can write to it with PHP. Is file\_save\_upload the wrong function? What do I need to do instead?

# Answer
> 3 votes
If it's an 'unmanaged' file, i.e one that doesn't have a database entry, you can use either

1. `file_unmanaged_move` or
2. `file_unmanaged_save_data`

---
Tags: files
---


# Question
Title: Using AJAX to access the content of a view
I have a simple view with one exposed filter that displays a table view of contents.(for example nodes are some addresses with the exposed filter of the city). And I made a map for cities;I want that whenever user clicks on a city in the map, the selected city become exposed filter of view and view become refreshed without refreshing the whole page.is it possible? I thought that I can use something like:

```
$.get(
'/myviewpage',
{myfield=14},
function(data){  $('#SomeOtherDiv').html(data) }
);

```

I tried that but I got unauthorized error. if it's correct; how can I make a page view-able for everyone? thanks

# Answer
The way I would do it (and it works):

Instead of directly calling the page with JQuery $.get, you should use the Drupal ajax framework and call a custom path you created with hook\_menu with a callback function which calls the view and return it using ajax\_deliver. Then you create your own js function for the response.

There is some nice documentatione/example about this, particularly this one.
> 1 votes

# Answer
First, enable Ajax on the view. On window load, bind the click event to a custom function, let's call it `getInfo(arg)` and pass the arguments you need (*nid*, *tid*, or whatever you need)

Then, on `getInfo()` add the following code.

```
function getInfo(args) {
  $.ajax({
    url: '/views/ajax',
    type: 'post',
    data: {
      view_name: 'your_view_name',
      view_display_id: 'block_1', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
      if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#myDiv').html(viewHtml);
        Drupal.attachBehaviors(); //check if you need this.
      }
    }
  });
}

```

You pass the arguments in the data array, and you get the #myDiv replaced with the view content.
> 3 votes

# Answer
You can not use hook\_menu. Exposed filter of view send request to /views/ajax, you can add param for this request view\_name=\[view\_name\]&view\_display\_id=\[view\_display\_id\], so you only get the content that you want. If you want to use JSON, install views\_datasource
> 1 votes

---
Tags: views, ajax, javascript
---


# Question
Title: Why does default .gitignore suggest ignoring config directory?
In Drupal 8, perhaps the most anticipated feature is separation of configuration from content. It achieves this by storing configuration changes in a sites/default/config\_\* folder.

Why then does the default .gitignore file suggest ignoring this directory?
If I make changes to the site, I want those changes to be tracked to push them to the live site, or merged with another developer's changes.

# Answer
> 3 votes
You are supposed to put that in a separate repository, I suppose. Note that the best practice workflow is to export the configuration and git the staging directory. You are not supposed to edit the active directory to the best of my understanding.

Edit: since writing this answer the default storage is now in the database and there's no more active directory.

---
Tags: 8, version-control
---


# Question
Title: Better Exposed Filter Module(bef) doesn't work with hierarchical taxonomy
I'm using better exposed filter module, and trying to build a filter based on a hierarchical taxonomy. But I can't work it out. Whatever how many terms in the taxonomy, the filter only show two radios: `-any-` and \`\`(empty). Like this:

Do I miss something?

You can follow my steps: on a new drupal site, the default content type 'article' has a field named `Tags`, using the default taxonomy `tags`. So I build a simple hierarchy like this:

Then I create a new page view for content type 'article', add the `Tags` field to `FILTER CRITERIA` and set `Dropdown` with `Show hierarchy in dropdown`.

And set the display to `Nested Checkboxes/Radios Buttons` in `BEF settings`.

Visit the view page, only 2 radios are shown: `-Any-` and \`\`(empty).

I have try other display setting in `BEF settings`:

* Default Select List: will show all 6 options in a dropdown with `-` prefix, it's ok
* Checkboxes/Radios Buttons: will show 2 radios, `-All-` and \`\`(empty).
* Links: will show all 6 links with `-` prefix, , it's ok

# Answer
It's very strange that the default option shows the correct info (dropdown with dash-prefixed options) but the BEF nested option doesn't work correctly. I just tried this using a clean build and a similar taxonomy and it was displaying correctly:

Since this is my dev machine, I'm using the latest -dev releases of CTools (7.x-1.x), Views (7.x-3.x) and BEF (7.x-3.x). Can you try your site with the latest BEF to start with and possibly Views/CTools, if that doesn't fix thing?

Finally, if all else fails, feel free to open an issue in the BEF issue queue (which I'm hoping to give some attention to this month -- New Year's resolutions and all...). Be sure to include an export of the view and content type(s) needed to reproduce the problem.

Hope that helps.
> 0 votes

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


title: Display blank date in hook_form

text:
# Question
Title: Display blank date in hook_form
I am creating a custom page with hook\_form and using the datatype '#type' =\> 'date,

I would like to make that field required.

AND, I want it to initially display blank.

Without #default\_value specified, the default is today. How do I, in effect, make the default\_value NULL?

# Answer
> 4 votes
You can use a `#pre_render` function on that field to unset the values and add an empty option on the 3 select boxes.

```
$form['start_date'] = array(
    '#type' => 'date',
    '#title' => t('Date'),
    '#description' => t('Your field description ...'),
    '#required' => true,
    '#pre_render' => array('_YOUR_MODULE_form_pre_render_date'),
);

```

```
function _YOUR_MODULE_form_pre_render_date(&$element)
{
    // Don't put empty values if a date has already been set
    if (date('Ynj') !== implode('', array_values($element['#default_value']))) {
        return $element;
    }

    // Loop through each field, add empty option and unset value
    foreach (array('year', 'month', 'day') as $field) {
        if (!isset($element[$field])) {
            continue;
        }

        unset($element[$field]['#value']);
        $element[$field]['#default_value'] = '0';
        $element[$field]['#options'] = array(
            '0' => '',
        ) + $element[$field]['#options'];
    }

    return $element;
}

```

# Answer
> 1 votes
As I was having date validation problems using Mike Vranckx answer above, I needed to implement a custom validation method to get around the `The specified date is invalid.` error.

First add a custom #element\_validate function to the form element:

```
  $form['dob'] = array(
    '#type' => 'date',
    '#title' => t('Date Of Birth'),
    '#weight' => 9,
    '#pre_render' => array(
      '_form_date_empty',
    ),
    '#element_validate' => array('_form_date_empty_validate'),
  );

```

However it seems that setting this value will prevent the default `date_validate()` function from running, which still has some value, we just want to make sure it doesn't prevent blank dates:

```
function _form_date_empty_validate($element, &$form_state, $form) {
  $date = $element['#value'];
  if (($date['year'] || $date['month'] || $date['day'])) {
    date_validate($element, $form_state, $form);
  }
}

```

---
Tags: forms
---


# Question
Title: modifying option text in ubercart attributes
I am made an attribute with mulitple options on my Ubercart Product. I made an adjustment to the price of some of the options ie: -38 (its 38 less dollars) but now on the dropdown, it has the option name followed by ', -$38.00). How can I get rid of this text?

# Answer
> 1 votes
1. Go to this URL in your Drupal site:

*admin/store/settings/products*
2. You will find a list of menu in that click `Attribute settings`
3. You will option for price format in that select the first radio button `do not display`

---
Tags: ubercart
---


title: Views & Multi-dimensional table

text:
# Question
Title: Views & Multi-dimensional table
I have the following configuration with my drupal website:

* **Taxonomy vocabulary:** Procedure
* **Users Role:** Doctor
* **Node Type:** Surgical Operation

When I create a "Surgical Operation" node, I can select a procedure (abdominoplasty, breast augmentation, etc...) and a doctor (users with doctor role) via entities.

What I would like to do now is create a View that displays what operations have been performed, how many times, and by what doctors in a table:

So far I have tried the following modules without success:

* Views Aggregator Plus;
* Views Calc;
* Views Table Group;

How should I proceed? Should I create a module myself to display these informations?

Thank you for your help.

# Answer
I had a very similar problem and I could solve it using Views Matrix module. It has only a dev version for Drupal 7, but it did the job perfectly.

Look at this question, it's almost the same except that I didn't need to count the items: Matrix view with content as columns and taxonomy terms as rows

There is also another answer to that question which I tested and it works as well.
> 2 votes

---
Tags: views, theming
---


title: Custom User Login validation

text:
# Question
Title: Custom User Login validation
I am developing a Mobile App for my drupal website, where user need to login with existing user account in drupal. How to validate password? I have tried MD5, and also concatinated it with $S$. Any suggestions..

# Answer
> 3 votes
use `user_hash_password()` to validate the password for existing users.

---
Tags: users
---


title: Theme views pager

text:
# Question
Title: Theme views pager
I need to theme views pager, but I can't find the way to do it. For example - Instead of printing 'last page' I need print the last page number. I tried to use Drupal's `theme_pager` with the pager array from the 'view' object, but it returns an empty string.

Thanks!

# Answer
> 2 votes
Solved :) - Following Change views pager programmatically .

**Example code:** (In `hook_views__pre_render`)

```
if( !empty($view->query->pager->options) ) {
  $last_page = ceil($view->query->pager->total_items / $view->query->pager->options['items_per_page']);
  $view->query->pager->options['tags']['last'] = $last_page;
}

```

---
Tags: views, theming, paging
---


# Question
Title: Is there a module or way to edit all my product's categories from one admin menu?
Currently I have to go to admin\>store\>products and then go to each product individually to change their category. This is tedious when you have hundreds of products and need to change many of their categories. For just changing the title/name of a category/term I can just edit the taxonomy term but Ive also added many new terms. So is there a module or a setting to allow this? I am using ubercart.

# Answer
Here are a couple of possibilities:

1. Perhaps try Views Bulk Operations \- this might have an operation for changing taxonomy term in content in a batch.
2. If you are changing the same taxonomy term (old) to another term (new) on many products, I wonder if deleting the new term and then renaming the old term to what that new term was would do the job? The end result is that you now have products all using the new term. This idea would only be suitable if there isn't other content using that new term which is not part of the change.
> 1 votes

---
Tags: taxonomy-terms, ubercart
---


title: Token access from module

text:
# Question
Title: Token access from module
Hi I'm trying to replace a Webform email with a token which works from the tpl file like this:

```
$company_email = token_replace('[node:field-charter-company:field-company-email]', array('node' => $node));
echo $company_email;

```

This works fine but when I try to do it from a module it just outputs "\[node:field-charter-company:field-company-email\]" instead of the contents of the token.

```
function webform_node_token_form_alter(&$form, $form_state, $form_id, $node) {

        if ($form_id == 'webform_client_form_126') {
            $company_email = token_replace('[node:field-charter-company:field-company-email]', array('node' => $node));
            $form['submitted']['company_email']['#value'] = $company_email;
  }
}

```

I know I'm doing something wrong but kind of lost. Can anyone give me a pointer?

# Answer
> 1 votes
Extra arguments passed to the initial form function will not be passed to the alter - so the 4th parameter of `$node` in your form alter function isn't available. If you check your logs you'll probably find a related notice.

For any node form (including webform), you should be able to get the node object directly from the form:

```
$node = $form['#node'];

```

---
Tags: 7, webforms, tokens
---


# Question
Title: Add image file programmatically in drupal 6
i want to upload an image on my site. I have a custom form in a module with

```
  $form['picture'] = array(
  '#type'   => 'file',
  '#title'  => t('Avatar'),
  '#prefix' => '<img src="' . $user->picture . '">'
  );

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

```

and in my validate fucntion :

```
$validators = array('file_validate_extensions' => array('jpg png'),
                    'file_validate_image_resolution' => array('500x500'));

$file = file_save_upload('picture', $validators);
dsm($file);

```

The problem is that i do not get the picture returned by the form, i only get "0" which is an error. So, did i do something wrong, or another method is better to get and save a picture returned by a custom form?

Thanks.

# Answer
> 1 votes
I found a sample for implement it in drupal 6

maybe your problem occur because of 2 thing,

* permission of directory
* $form\['#attributes'\] = array('enctype' =\> "multipart/form-data");

made this example for you...explain how to working with cvs

```
   /**
    * Form function
    */
     function _form_cvs_import($form_state) {
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['container'] = array(
        '#type' => 'fieldset',
        '#title' => t('CVS UPLOAD') ,
      );
      $form['container']['cvs_file'] = array(
        '#type' => 'file' ,
        '#title' => t('CVS FILE') ,
        '#description' => t('insert your cvs file here') ,
      ) ;
      $form['container']['submit'] = array(
        '#type' => 'submit' ,
        '#value' => t('SEND') ,
      ) ;

       return $form ;
    }

/**
* form validate
*/
function _form_cvs_import_validate($form, $form_state) {
 $validators = array(
  'file_validate_extensions' => array('cvs'),
 );
 if(!file_save_upload('cvs_file', $validators)) { // the file is not submitted
    form_set_error('cvs_file', 'Please select the cvs file') ;
 }else{ // the file is submitted another validation for extension
   $file = file_save_upload('cvs_file', $validators, file_directory_path()) ;
   if($file->filemime != 'application/octet-stream' ) {
     form_set_error('cvs_file', 'Extensions Allowed : cvs') ;
   }
 }
}

/**
*  form submit
*/
function _form_cvs_import_submit($form, $form_state) {
    $file = file_save_upload('cvs_file', $validators, file_directory_path()) ;  // this is the cvs file in the tmp directory
    $file_handler = fopen($file->filepath, 'r') ; // open this cvs file
    $line_num = 0 ;
    $fields = array() ;
    while(!feof($file_handler)) {
        $line_num++ ;
        $line = fgets($file_handler) ; // this is the line/row
        $line_array = explode(",", $line);  //  array of row fields
        $field_num = 0 ;
        foreach($line_array as $field) {
            $field_num++ ;
            $fields[$line_num][$field_num] = str_replace('"', '', $field );  // E.g you can access second row and third field by $fields[2][3]
        }
    }
    fclose($file_handler);
    unlink($file->filepath);

```

}

# Answer
> 2 votes
This is not good job save file in validation phase and really where you get file from posted data ? file exist in `$form_state['value']['picture]`

mybe below code help you

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

    $file = $form_state['values']['picture'];

    $validators = array();
    $file = file_save_upload('file', $validators, 'public://');
....

```

---
Tags: 6, forms, media, files
---


# Question
Title: Migrating XML source twice, according to language
I am writing a scheduled import using the Migrate module, where I have an XML feed which gives me a number of reports. These reports have most of their fields in common, but have two fields ("location/name" and "desc") which are supplied twice, each specific to a language.

My question is how I could import this into two nodes, one for each language? My first thought went out to using stubs, but thinking on that I can't figure out how.

Ofcourse, the "location/name" and the "desc" elements should only import the one relevant to the language being imported.

Altering XML structure is not possible, data in the fields has been altered for privacy reasons.

Example XML and current code: https://gist.github.com/Tagini/8319661

P.S.: Any help on migrating the location (using Location module) is welcome.

# Answer
> 0 votes
Turns out I didn't look at SimpleXML enough.

Using XPath, I can very easily select one of the languages through the lang attribute, and as such have one language imported.

If i then make a second migration for the other language, my problem is solved.

For reference, the selector for the description now looks like this:

```
$this->addFieldMapping('body', 'desc')
  ->xpath('desc[@lang="nl"]');

```

---
Tags: 7, location, migrations
---


# Question
Title: Views Data Export Module not including the custom added rows in a view
I have created a view for commerce orders where format is tabular and they are grouped by email of order owner. So basically each group of record shows how many orders are placed by a given email id.I need to have a extra row in each grouped results which is basically summary of order(showing cumulative order total) so I used views\_summarize module and got it done. Now I need to have export views as csv or xls functionality so I put views\_data\_export module but it seems the row added by views\_summarize is not included by csv or xls generated by views\_data\_export.

I also tried including the row using hook\_views\_pre\_render(), and I am seeing the row is getting added in the views page under preview but when I export the views in csv again the row does not appear.

Here is code

```
function mymodulename_views_pre_render(&$view) // don't forget to replace my_module with your modules name
{
  if($view->name == "paid_partner") {
    if($view->current_display = "paid_partner_csv" || $view->current_display = "paid_partner_xls") {
      foreach($view->result as $submission) {
        $order_total_summary += $submission->field_data_commerce_order_total_commerce_order_total_amount;
        $quantity_total_summary += $submission->commerce_line_item_field_data_commerce_line_items_quantity;
        $currency = $submission->commerce_order_total_amount_currency_code;
      }
    $price_display = commerce_currency_format($order_total_summary, $currency);
    // insert a 'total' row
    $row = new stdClass();
    $row->order_id = "Order Summary";
    $row->users_commerce_order_mail = "Order Total Summary";
    $row->commerce_line_item_field_data_commerce_line_items_quantity = $quantity_total_summary;
    $row->field_commerce_order_total[0]['rendered'] = array(
      '#markup' => $price_display,
      '#access' => TRUE,
    );
    $view->result[] = $row;
    }
  }
}

```

What can I do to include the summary row with each grouped record in exported csv or xls.

# Answer
Views Data Export does not render your results in a traditional way, so `render` hooks are not executed. But you should be able to alter results using `hook_views_post_execute`:

> This hook is called right after the execute process. The query has been executed, but the pre\_render() phase has not yet happened for handlers.
>
> Adding output to the view can be accomplished by placing text on $view-\>attachment\_before and $view-\>attachment\_after. **Altering the content can be achieved by editing the items of $view-\>result.**

Emphasis mine - that's what you should to to alter content not only for display purposes, but in generic, usage-independent way.
> 3 votes

---
Tags: views, importing-exporting
---


# Question
Title: Retrieving users from Database on to forms
I have a webform with a select option type field. I need an authenticated user to view other available users in the website in this list. So, it needs to be dynamic by communicating with the database. What is the best way to do this?

Thanks in advance!

# Answer
You have to use `hook_webform_select_options_info()` in your custom module.

I made my first module with that hook because i needed to achieve a similar thing but with people who were linked thanks to module `relation`. I show you what i did (i change the query to retrieve all users from the site, i'm not an expert in query). It was my first code, so it's not very optimize but it's work.

```
function my_module_webform_select_options_info() {
  $items['membres'] = array(
  'title' => t('Membres'),
  'options callback' => 'webform_membres_options',
  );
return $items;
}

function webform_membres_options($node)  {
  global $user;
  $store = array();

  $result = db_query("SELECT users.name AS users_name, users.uid AS uid, users.mail AS  users_mail
                      FROM {users} users
                      WHERE (( (users.status <> '0') ))");

 //Store mail|username in an array (good format for select options)
 foreach ($result as $row) {
   $store[$row -> users_mail] = $row -> users_name;
 }
 //All users don't have relationship so we have to check the length of array
 if (count($store > 0)) {
   return $store;
 }
     else {
   return false;
 }
 }

```

You'll see your list in **Load a pre-built option list** when you'll build your webform (after selecting "select options") Don't forget to put a default value for the select list. After you'll see your list in the webform :
> 1 votes

# Answer
Here is another aproach. I just used this on a project i am working on.

```
/**
 * Same as example above
 */
function YOUR-MODULE_webform_select_options_info() {
  $items = array();
  $items['users'] = array(
    'title' => t('Users'),
    'options callback' => '_YOUR-MODULE',
  );

  return $items;
}

/**
 * Get a list of all uids except uid 1
 * This is easier to read.
 */
function _YOUR-MODULE($component, $flat, $filter, $arguments) {

  $all_users = entity_load('user');
  foreach($all_users as $value) {
    $user_list = (array)$value;
    if($user_list['uid'] > 1) {
      $user_names[$user_list['uid']] = $user_list['name'];
    }
  }

  return $user_names;
}

/**
 * Set the default value of the select list to the current user
 */
function YOUR-MODULE_form_alter( &$form, &$form_state,$form_id ){
  global $user;
  $uid = $user->uid;

  //
  if ($form_id == 'webform_client_form_YOUR-WEBFORM-ID' && $uid > 1) {
    // manipulate component values like this:
    $form['submitted']['YOUR-WEBFORM-FIELDNAME']['#default_value'] = $uid;
  }
}

```

Edit: I added some more comments and a solution for setting the default value of the select list to the current ID.
> 1 votes

---
Tags: webforms, database
---


# Question
Title: Visiting admin pages return 404 (page not found error) after transfer website
I have transferred my website from another hosting . Front showing fine but if we click on link it will page not found error ..admin also not showing so how i control my website..i checked `.Htacces` as following

`# RewriteRule ^ index.php [L]`

`RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]`

And added this code in `setting.php`
`$conf = array( 'clean_url' => 0,);`

My website URL is like this :

http://tailoredsuitonline.com.previewdns.com/oceanwis/

Please share your help here. Thanks...

# Answer
> 2 votes
So there is a problem with Clean URLs, as this works: http://tailoredsuitonline.com.previewdns.com/oceanwis/?q=album

But this doesn't: http://tailoredsuitonline.com.previewdns.com/oceanwis/album

You can log in with your admin account here: http://tailoredsuitonline.com.previewdns.com/oceanwis/?q=user

Then go there and disable clean URLs: http://tailoredsuitonline.com.previewdns.com/oceanwis/?q=admin/config/search/clean-urls

# Answer
> 1 votes
I think the old `.htaccess` file not uploaded ,please upload it again and make sure the old one uploaded .put some comment in it then upload check it upload correctly. sometimes the .htaccess file not upload.
another reason is maybe you clean url not active, this link maybe help you about clean url https://drupal.org/node/256410.

and third reason maybe occur of dedicate servers,in dedicate server sometimes local configuration not applied

---
Tags: .htaccess, configuration
---


# Question
Title: Linking to #targets when promoting to homepage
On a Drupal 6 site, I want my article to start with a bullet list of section headings, linked to in-page targets; and I want to include this list in the teaser text which is promoted to the homepage.

But the links don't work from the homepage, because Drupal doesn't work out that the on-page target in an article is an off-page target or the teaser, so it doesn't include the node reference.

Is there some way for content authors to achieve this easily? Maybe there's a module which handles it?

# Answer
> 1 votes
Use URL's relative to the site root. Suppose your node lives at http://example.com/node/123 and your named anchor is called "target", write your link like this:

```
<a href="/node/123#target">Target</a>

```

This should work on the home page and the node page itself.

---
Tags: navigation
---


# Question
Title: Drupal 7: What's the schema of the 'data' column in the 'users' table?
I'm trying to bulk-add some users, all columns of the `users` table are clear less the last, the `data` which has some serialised data like this:

```
a:2:{s:13:"form_build_id";s:32:"form-153847821e107639110c0cae645b3d88";s:4:"contact";i:0;s:11:"newsletters";a:2:{i:67;i:42;}}

```

I'm looking for a syntax/reference for this field, so I know what I'm getting into.

thanks

# Answer
There isn't a 'schema' as such, the values can be absolutely anything (that's why a serialised array is used rather than having statically defined fields).

From the `user_schema()` docs:

> A serialized array of name value pairs that are related to the user. Any form values posted during user edit are stored and are loaded into the $user object during user\_load(). Use of this field is discouraged and it will likely disappear in a future version of Drupal.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Remove jQuery, and jQuery UI and add migrate plugin with Updated jQuery and UI
I am trying to use `drupal_add_html_head` to add script elements to the head tag, however, this is important that these script tags are not self-closing because that is not the correct way to add them.

How do I do this:

```
$html5jquerymigrate = array(
    '#tag' => 'script',
    '#attributes' => array(
        'src' => libraries_get_path('jquery.migrate', true) . '/jquery-migrate-1.2.1.min.js',
    ),
    '#prefix' => '',
    '#suffix' => '',
);

drupal_add_html_head($html5jquerymigrate, 'html5jquerymigrate');

```

But instead of getting it printed out like this: `<script src="/sites/all/libraries/jquery.migrate/jquery-migrate-1.2.1.min.js" />`

How do I have it print out in the head like the following instead?

`<script src="/sites/all/libraries/jquery.migrate/jquery-migrate-1.2.1.min.js"></script>`

# Answer
Ok, there was no 1 step solution to this problem. So here's what I did in case anyone else wants to know.

This is a 3 STEP solution to adding jQuery 1.9 and jQuery UI 1.10 functionality to Drupal 7. Not sure about other versions of Drupal.

**1** \- Needed to remove Drupals old jQuery library of version 1.4 and replace with version 1.9, so in my theme, I added the following function:

In `template.php`

```
function MYTHEME_js_alter(&$js) {

    $js['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';

    // Adding this ensures that the UI functionality gets added at all times!  Even when logged out of the site, since we have functionality on the site that requires this when logged out!
    if (!isset($js['misc/ui/jquery.ui.core.min.js']))
    {
        drupal_add_js('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js');
    }
    else
        $js['misc/ui/jquery.ui.core.min.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js';
}

```

**2** \- Now that this is done, before we can really take advantage of Drupal with any other jquery library that is greater than 1.8 (which sucks), we need to add in the `migrate` plugin found here: http://blog.jquery.com/2013/05/08/jquery-migrate-1-2-1-released/

I have the Libraries Module installed, so I just put the JS in my Libraries folder called: `jquery.migrate`

**3** \- Than I added this to `template.php` file for my theme:

```
function MYTHEME_page_alter($page) {
    drupal_add_js(libraries_get_path('jquery.migrate') . '/jquery-migrate-1.2.1.min.js');
}

```

Now I can use all of the greatest and newest technologies in jQuery 1.9 and beyond while still being able to have Drupal 7 not crash on me! AMEN! HALLELUJAH!!!!
> 4 votes

# Answer
You can use `drupal_add_js` function instead. Read the API Documentation here: drupal\_add\_js
A Simple Example:

```
// This may do the work for you.
drupal_add_js('/sites/all/libraries/jquery.migrate/jquery-migrate-1.2.1.min.js');
// Using a CDN
drupal_add_js('http://code.jquery.com/jquery-latest.min.js', 'external');

```
> 2 votes

---
Tags: javascript
---


# Question
Title: Organic Group visible only by authenticated user
I want to make the list of OG visible only to authenticated user so they can request membership. I have created a view but it only display group the user is already member of.

When I change the group visibility from * Private - accessible only to group members\* to *Public - accessible to all site users* this make the group visible to anonymous user too.

# Answer
> 1 votes
I used the Content Access module to deny access to anonymous user.

In your Organic Group content type admin interface (admin/structure/types/manage/committee) a new `ACCESS CONTROL` tab appears. Unckeck `anonymous user` for the view `View any committee content`.

If `authenticated user` is check it will over-right Organic Group settings (ie. the Private / Public will have no effect and the content will be accessible to all authenticated user).

source

---
Tags: 7, organic-groups
---


# Question
Title: Display content not updated from specific date
I can generate a views with provides a list of content has been updated from an specific date (by adding field "Content: Updated date" in Filter criteria). However, I cannot find the opposite option, I mean built a list from a specific date which has not been moderated or updated. How can I get it?

Thanks a lot!

# Answer
> 0 votes
When you create your filter criteria you have an `Operator` drop down list that will offer the option like `Is not equal to` or `is empty (NULL)`

Then you can expose this filter and set the date manually or use an offset from the current date.

---
Tags: views, datetime
---


# Question
Title: How do I set up an action to email all users with a certain role?
I'm using Rules 7.x-2.6 and the way it works has changed a bit since I last saw.

I have a rule as follows:

```
EVENT
A node has been flagged, under "Report content"

CONDITIONS
None

ACTIONS
Send mail to [site:mail]

```

However, I'd like to, instead of sending directly to \[site:mail\], send an email to all users flagged with an "admin" role.

Now I know that I'll need to provide a loop do so, but my sticking point is generating the list of users to pass to the loop. So far, I have attempted to add a new action:

```
"Fetch entity by property"
Entity type: User
Property: User roles
Value: admin

```

But this doesn't seem to give me what I want in data selection, when passing it to the loop. Can someone recommend what they would set here?

# Answer
I have "Send mail to all users of a role" available when I add an action.

* edit rule
* click add action
* Under system section select "Send mail to all users of a role"
* Select role and save
> 5 votes

---
Tags: 7, rules
---


# Question
Title: Services module: what is the syntax of node.index parameters?
I'm trying to get the list of certain type nodes using xmlrpc and POST method. I'm constructing xml like this:

```
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
<methodName>node.index</methodName>
<params>
   <param>
      <value>
         <string>0</string>
      </value>
   </param>
   <param>
      <value>
         <string>*</string>
      </value>
   </param>
   <param>
      <value>
         <string>type=forum</string>
      </value>
   </param>
</params>
</methodCall>

```

yet in return I get nodes of various types. I guess that type=forum is bad. What is correct syntax of this parameter?

# Answer
I usually call node.index this way

```
$nodes = xmlrpc($this->server_endpoint, Array('node.index' => Array(0,'nid,uuid,vid', array('type' => $contentType), PHP_INT_MAX)), $this->headers);

```

the parameters being:

1. Page number (usually I set it to zero and set the number of nodes per page to PHP\_INT\_MAX. This because I found page support buggy in a previous version, I haven't retested it recently)
2. Array with fields to retrieve (only that you find in the node DB table are available. Careful with it, less fields means better request speed)
3. Array with content type(s) to retrieve
4. Number of nodes in the index list per page

I dont'know how exacly goes in XML, but I think that it should be easy enough to adapt to that syntax, if necessary.
> 0 votes

---
Tags: services
---


# Question
Title: Content Type "Article" is not showing when trying to add, but it is showing in Structure-> Content Type. Please help me
I don't know how i lost Article content type when adding a content. It is not visible for me.

Please find the two screen shots attached.

# Answer
> 0 votes
Try re-enabling the content types in the navigation menu.

Go to administration-\>structure-\>menus-\>navigation and you should see your article content type disabled in the menu. Just re-enable them and it should all work fine

---
Tags: nodes
---


# Question
Title: Assigning a role based on signup url on a Drupal 7 site?
I need to give out a URL that will grant people who sign up at that URL a specific role. If possible I would like to also have the user fill out profile fields as part of user registration.

I think the Profile 2 module does something like this, but this is already set up with normal Drupal fields, is there any way to make this work?

# Answer
> 2 votes
You can do it with Auto Assign Role module, It provide paths that will trigger a specific role when an account is created.

> The Auto Assign Role serves three primary purposes. The first is to provide an automatic assignment of roles when a new account is created. The second is to allow the end user the option of choosing their own role or roles when they create their account. The third is to provide paths that will trigger a specific role when an account is created. The administrator has full control over these functions and can have them working together or independently of each other. Auto Assign Role is integrated with the Content Profile module so that you can have content types serving as registration pages. You can even replace the default user/register page with a customized version of your own design.

# Answer
> 2 votes
I know the auto assign roles will work but often you want different customer fields or required fields as well. I have found that Profile 2 registration path will give custom fields per role and path registration.

---
Tags: users
---


# Question
Title: How to validate the headers of a csv uploaded with cck filefield?
I need my users to upload a csv, using a cck filefield. I then wish to confirm they have the correct order of columns.

My research led me to believe that writing a custom validator for the filefield, was the best option. I have used this as a resource: https://drupal.org/node/546146 for writing it...

I then used this for an example of how to open a csv and read it: http://oliverhuynh.wordpress.com/2011/06/21/drupal-batch-csv-importing-template/ ...

I'm very new to this and lack the insights to spot what i'm doing wrong... Here's my code:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'stocklist_node_form') {

    $form['field_stocklist'][0]['#upload_validators']['stocklist_validation'] = array();
    return $form;
  }

}

/**
 * The validation for the file.
 *
 */

function stocklist_validation($field) {
  // variable for error messages
  $errors = array();

  // do some processing on the field / file
  $filepath = $field->filepath;
  global $base_url;
  $fileurl = $base_url . '/' . $file_path;
 // Open the file
      if ( $handle = fopen($fileurl, 'r') ) {
        $line_count = 1 ;
        $first = TRUE ;
        if ( $line = fgetcsv($handle, 4096) ) {

        // Validate the headers

         if ( $line[0] !== 'manufacturer' ) {
            $errors[] = t('Unable to verify uploaded file !filepath. Please ensure the file has the correct file type, column names and information.', array('!filepath' => $field->filename));
         }
        }
        fclose($handle);
      }

// in case of error, add error message

          return $errors;
}

```

I would really appreciate any help or pointers... I feel I'm one step away from finishing it but running out of google searches... It doesn't matter whether I upload a valid or invalid file, it just throws the defined error message... Why is it doing that?

edit:

Here is a screenshot using devel whilst viewing a 'stocklist' type node. Thought it may help...

# Answer
Just got this too work:

```
/**
 * The validation for the stocklist.
 *
 */

function stocklist_validation($field) {
  // variable for error messages
  $errors = array();

  // do some processing on the field / file
  $filepath = $field->filepath;

 // Open the file

      if ( $handle = fopen($filepath, 'r') ) {
        $line_count = 1 ;
        $first = TRUE ;
        if ( $line = fgetcsv($handle, 4096) ) {

        // Validate the headers
         if ( $line[0] !== 'something' ) {
            $errors[] = t('Please ensure the files 1st column has the something in it. Including something as the heading.');
         }

    if ( $line[1] !== 'somethingelse' ) {
            $errors[] = t('Please ensure the files 2nd column has the somethingelse in it. Including somethingelse as the heading.');
         }

        fclose($handle);
      }

           else {
        $errors[] = t('Unable to open uploaded file !filepath.', array('!filepath' => $filepath));
       }
      }
// in case of errors, return error messages

          return $errors;
}

```

The first function didn't need changing...

In the second function, it was the fopen() that needed changing. Secondly, like an idiot I just realised that the "valid" file was actually tab delimited... Doh! Would be nice to be able to accept those files too. As some software saves csv files in that format, such as the one I clearly used, OpenOffice.
> 0 votes

---
Tags: 6, entities, files, importing-exporting
---


# Question
Title: update hook to delete and bulk update pathauto aliases
I have put all of my SEO settings into a feature, in order to migrate the settings from a dev site to a live site. Is there a way to write an update hook that will delete all of my existing content aliases and then bulk update them automatically?

# Answer
I do it with the following method:

```
function MYMODULE_update_7100(&$sandbox) {
  module_load_include('inc', 'pathauto');
  module_load_include('inc', 'pathauto.pathauto');

  // Delete the existing node aliases.
  db_delete('url_alias')
    ->condition('source', 'node/%', 'LIKE')
    ->execute();

  // Regenerate the node aliases.
  $nids = db_query("SELECT nid FROM {node}")->fetchCol();
  pathauto_node_update_alias_multiple($nids, 'bulkupdate');

  // Delete the topics taxonomy aliases.
  db_delete('url_alias')
    ->condition('source', 'taxonomy/term/%', 'LIKE')
    ->execute();

  // Regenerate the taxonomy aliases.
  $tids = db_query("SELECT tid FROM {taxonomy_term_data}")->fetchCol();
  pathauto_taxonomy_term_update_alias_multiple($tids, 'bulkupdate');
}

```
> 1 votes

---
Tags: features, updating, path-aliases
---


# Question
Title: How to add template suggestions for entities?
I need to add a template suggestion for entities in a custom module, similar to how you can add one for nodes. I've seen the ones implemented in the Entity API module, but how do I hook into entity preprocessing so I can add my own?

# Answer
I found a solution. The Entity API module defines template\_preprocess\_entity() such that you can add template suggestions during your own preprocessing in a custom module, like for example:

```
function mymodule_preprocess_entity(&$variables) {
    if($variables['elements']['#entity_type'] = "myentity") {
        $variables['theme_hook_suggestions'][] = "myentity";
    }
}

```

This runs preprocessing for custom entities built off the Entity API, but not for not nodes or entities built into Drupal core. In order to add template suggestions for Drupal core entities, you need to add it while using the various entity-specific preprocessing hooks provided in Drupal core. For example:

```
// Preprocessing for taxonomy terms
function mymodule_preprocess_taxonomy_term(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for user profiles
function mymodule_preprocess_user_profile(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for comments
function mymodule_preprocess_comment(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for nodes
function mymodule_preprocess_node(&$variables) {
  // Add template suggestion code here.
}

```
> 5 votes

---
Tags: 7, theming, hooks, entities
---


# Question
Title: "b.handleError is not a function" on image remove/upload
I was not able to upload/remove CCK field images from the UI; when I looked at the console in Firebug, it said, "b.handleError is not a function." When I look for this error on Internet, I keep getting redirected to http://drupal.org/node/1064890, but this has a patch for Drupal 7.

Has anyone faced something similar?
More importantly, was this fixed?

I am using Drupal 6, and the following modules:

* jQuery UI 1.7.3
* jQuery Update 1.5.2

# Answer
You can update the jquery.form.js as found in this comment:

https://drupal.org/comment/7520175#comment-7520175

I tried on my system which also makes use of a newer version of jQuery and it works like a charm.
> 0 votes

---
Tags: javascript, 6
---


# Question
Title: Turn off cron and hook_cron for every module in Drupal
How can I turn off cron and disable implement of hook\_crons in every modules in Drupal my site is Drupal 6 Thanks

# Answer
It is a good practice to run cron on your site. You might decide upon the frequency, keep it a high value but it is necessary to run cron to keep your site in healthy state.

If you are worried about loosing the caches when cron is run, you can install Cache Lifetime Options module and set Minimum Cache Lifetime to a very high value. This will make sure that your caches are not cleared on cron runs. Then you can Expire module for your cache invalidation strategy.

If you do not want to run all the hook\_cron implementations but only a selected ones then you should consider using Elysia Cron module. It lets you run cron for selected modules at selective frequences.
> 1 votes

---
Tags: caching, performance, cron
---


# Question
Title: Is it possible to update Drupal page cache right after it is cleared?
I am trying to improve Drupal performance and I have all the tuning usual suspects setup:

* Varnish
* Memcache
* APC
* Drupal core cache

From what I understand when you clear the Drupal cache it does not replenish page caches until an anonymous end user makes a request for the page. Drupal then builds the cache and the following page requests are snappy. The problem with this is the non cached call can take 2- 4 seconds to finish. We would like all page requests to be as snappy as a cached request. So we are looking into either a way auto replenish or set up a cron that would hopefully make the non cached page request before an end user.

If my assumptions are correct is there a module or way to automatically replenish all page caches? I am assuming that since this does not automatically happen that it is potentially a resource issue to cache the entire site at once. But if we set Drupals cache to live for 1 or 2 days and cleared cache on a cron in the middle of the night it might be ok to automatically replenish. Has anyone ever tried to solution this?

# Answer
> 0 votes
Cache Warmer Module is the one you are looking for.

> cache\_warmer is a drush command that hits a set of URIs of a drupal site based on the freshness of the content.

It is a drush integration for warming the caches using httprl, which means calls can be made parallely as well.

Since it is a drush extension you can tie it up easily with your cron as well.

---
Tags: 7, caching
---


# Question
Title: Why am I missing 'notification' features on my entityforms?
A coworker installed entityforms on a staging site and it delivers email notifications nicely. I am trying to replicate the process on the production site, but I am missing all the features/UI related to email notifications.

Below you can see I'm missing access/submission/validation options. I am also missing the 'Notifications' tab that should show up on the entityform 'edit' page.

**Staging server**

**Production server**

* I have the rules module and other dependencies (auto-installed with drush)
* I have Entityforms Notifications enabled
* I have Rules UI enabled

What am I missing?

# Answer
Because... I have different versions of Entityforms on staging and production. In the more recent version (7.x-2.0-beta2), they just moved things around.

You can get to the notification rules now by going to `Structure > Entityform Types > [form]` and clicking the `Rules` tab.
> 1 votes

---
Tags: 7, emails, entities
---


title: Cache is not cleared

text:
# Question
Title: Cache is not cleared
I have a weird problem that the cache won't be cleared. It all began since I added a template file "field--custom-field-name.tpl.php". The field is attached on user entity type.

I put `var_dump(get_defined_vars())` to output the available variables that I could use. I modified the file to begin using some of the variables, and cleared the cache. I found that the page is still showing var\_dump output.

I tried:

* Clearing the cache under performance tab
* Disabling/Enabling themes
* Emptying the cache\* tables in database
* Renaming the field template file
* Deleting the field template file

I don't have Drush, though.

The page just doesn't go back to normal; it just keeps showing the `var_dump()` output.

How can I fix this?

-Update- admin/reports/dblog has nothing useful, clearing cache has no error output. To me it's like it doesn't remove the var\_dump call from cache when I remove/update that field template, and it sticks to somewhere permanently.

I've also checked every file in the same folder, not var\_dump or output statements found.

Could it be a bug of drupal cache?

# Answer
The conents of the template files are not cached. So your concern is misplaced.

I am assuming that it is views. Edit the view goto `Advanced->Others->Theme Information` you can find out which template file is being used. Goto to the file and make the necessary changes or else copy the default file from the views module to the location.

Even if the above is not solving your problem, the var\_dump is coming from the database and not code.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Entity Reference - am I using it correctly?
I need a bit of help with entity references. I have Customer Profiles entity and Credit Card entity. I'd like to be able to create "credit cards" and attach them to customer profiles so that if I click hte customer profile, I'd see any credit cards attached to them. I'm not sure how to do this. I've created the credit card content type, added a reference field to it that references the customer, but I'm not sure how to display the filtered credit card entries on the customer profile. I've tried adding an entity reference field to the customer profile back to the credit cards but don't know how to filter the results.

My brain hurts a bit at this point.

# Answer
One way to do it is with Views and a module called Eva (Entity Views Attachment). Eva allows a view to be attached to a host entity, and understands how to filter the view based using the host entity's id to display only related information.

Since you already have the entity reference field on the credit cart type, the steps would look like this:

1. Install Eva and Views as needed
2. Create a View for the credit card content type
3. In the view, add an "EVA" display
4. Configure the view to be attached to the customer (under Entity content settings)
5. Add a Contextual filter using the field that links back to Customer. This will filter credit cards using the customer profile entity
> 1 votes

# Answer
I managed to do this with entity reference - views. I created a view with an entity reference display that displays the credit card fields. I then added a contextual filter based on the customer profile ID.

I added an entity reference field to the customer profile pointing to this view and used a token to grab the customer profile ID to filter the view. I had to patch entity reference to allow for token use but it works.

Hope this helps someone else.
> 0 votes

---
Tags: entities
---


title: Contextual view that limits results?

text:
# Question
Title: Contextual view that limits results?
This is a hard one to explain, so thanks for taking a look. I've created a menu in views of all the nodes associated with a particular taxonomy term. The problem is that some of these nodes have children associated with them that I do not want to show in the views menu. BUT, they should still display the menu.

> Node 1
> Node 2
> \- (child) Node 2a
> \- (child) Node 2b
> Node 3

In that example, the menu would show up on all 5 pages, but would only have 3 items in the menu.

I am able to make a menu of all the items associated with a term, but can't figure out how to add depth. Any ideas? -JB

# Answer
> 0 votes
A better understanding of contextual filters led me to a solution. I used a contextual filter to limit which pages showed the menu, then used a filter to control the items.

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


# Question
Title: Why does drupal_session_start() fail after a user clears the cache and logs back in?
I'm writing a document management module which has come pretty far and is almost ready for a final review and release, but I've found a really strange authentication issue that is requiring a gross work around.

Several actions in my module are handled via AJAX. I need to authenticate my user when I run the AJAX protocol. I also need to get the Drupal core functionality so I'm using the following code.

```
// Bootstrap Drupal.
define('DRUPAL_ROOT', dirname(dirname(dirname(dirname(dirname(__FILE__))))));
require_once( DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Validate the user.
_drupal_session_read($_POST['sid']);
drupal_session_start();
if (!user_access('manage documents')) {
  die('Access denied');
}

```

`$_POST['sid']` contains the value from `session_id()` or from `$user->sid`. They should be the same thing, but if I clear my cache, log back in, go to the page, and run any AJAX action, I get a 403 error on the first request, every time. My ugly work-around is to send a "checkin" action that just triggers the 403 error, since that is returned only once.

Can anyone explain to me why this code would behave this way?

# Answer
> 0 votes
> Upon closer inspection, I've found that the AJAX call is actually creating a new session. This means that I wind up with two session cookies for the site. How can I make Drupal recover the existing session instead?

If you have two sessions, you apparently have two cookies. They may hold the same session ID (and return the same data for `$_SESSION`). The difference between the cookies is the cookie name.

The name of the cookie is generated from some rather tricky code. (In Drupal 7, it's in `drupal_settings_initialize()`). it relies on `$base_url` and `$cookie_domain`, which are globals. it does some magic and then calls `hash('sha256', $session_name)` to create the session name, which is the cookie name.

If you get different values for `$base_url` or `$cookie_domain` in your AJAX calls, you may end up with two different cookies. For example, one of the AJAX callbacks might be called on ajax.yourdomain.com, while the domain for the site is website.yourdomain.com. It shouldn't be a problem either; the cookie value is what matters. If the cookies have the same value, you don't have a new session.

---
Tags: ajax, caching
---


# Question
Title: Set default title by content type in Panelizer
Is there a way to set a default title per content type using Panelizer? I see that you can use substitutions and change the title after you've created the content, but I would like it to use a specific substitution by default.

I know that I could use the autonode titles module, but I'd rather not add on more modules. Any ideas? -JB

EDIT: Just to clarify, I want to use a substitution for the title (a field from the content type), and the reason I want to set the default is so my admins don't need to change it themselves.

# Answer
> 1 votes
If you're using a custom module already and you want to 'set' the title prior to saving the node then you can use hook\_node\_presave().

To avoid contributor confusion when creating the node you can also do a form\_alter and set the #access of the title field to false. This will hide the field from the contributor.

---
Tags: panels
---


title: Does Ubercart have an external API?

text:
# Question
Title: Does Ubercart have an external API?
Does Ubercart have an external API that a 3rd party site could query? Specifically from a fulfillment point of view? We need to be able to query the system for items to ship, then update the order's status and set a tracking number after the item shipped. All this is done on a completely different server/company, so needs to be done via a publicly exposed API (like a REST or SOAP service). Does Ubercart do something like this?

# Answer
> 0 votes
Ubercart does have an API (see http://www.ubercart.org/docs/api and http://api.ubercart.me/ ), but I don't see general REST or SOAP support related to fulfillment.

Some options may include miniRESTapi or as noted UCServices and Bee Colony for Drupal 6. There are some vendor-specific SOAP implementations for CyberSource, but I do not know how well-supported they are.

---
Tags: ubercart
---


# Question
Title: How can Display Suite be used with Book module links?
After settings some node types to use Display Suite I have noticed those which are in Books don't show the book links at the bottom of the page.

Is there a work around for this?

# Answer
> 0 votes
you've to activate the full display to show the book navigation field on Display Suite display settings.

There is only a problem: the book navigation links are always rendered after the comment form. I know it was a known bug some months ago but I don't know if it has been fixed recently.

---
Tags: navigation, display-suite, nodes
---


# Question
Title: Associate multiple Profile2 profiles with vocabulary and expose the vocabulary's terms in a views' filter
I have 2 profiles that have two different taxonomy term fields that point to the same vocabulary (the reason that I created 2 different fields instead of one is that I want the users that handle the two profiles to be able to select different amount of vocabulary terms). If I try to create an exposed filter (select list) in views 3 I can only create 2 different exposed filters: one for profileA and one for profileB. I want to be able to merge them into one.

The "Global Combine Fields" option does not work since I want to expose a select list and not an input field. All the relationships that I tried to create are specific to one field or another (and not to the targeting vocabulary for example).

My question is: can I create an exposed filter based on the vocabulary (instead of the fields) that will filter the profiles based on whether the specific term(s) that were selected are in either the profileA's field and profileB's field?

I would like to know whether this is possible directly in views 3 with a method that I'm missing or if I could create a custom exposed filter programmatically. If the answer is the latter, I would really appreciate if you could point me to an article that shows how you can create such an exposed filter (or a similar) since I do not have any experience at all in the specific field.

# Answer
> 1 votes
This probably doesn't answer your specific question, but this poses an alternate solution.

If you created two fields to allow the user to select a different number of terms, you could potentially do this with one field and a form\_alter hook or validation.

The idea is that the form alter would change the number of allowed values based on some custom logic. Ideally this would make downstream functionality like views simpler because you're dealing with a single field.

The answer on this question may help give you ideas. How do I set the fixed amount of values to 11?

# Answer
> 1 votes
A similar question has been posted on https://drupal.org/node/357082 .

The author of the issue asked to combine an argument and pass to multiple filters: instead of filtering directly from arguments, the argument can be used as input value for regular filters. Moreover the filters can be set with the AND or OR operators. This solution is currently under discussion where you can find many ideas and different approaches.

---
Tags: 7, views, users
---


# Question
Title: Redirect if nothing is select in the View's jump menu
In D7, I have a view that produces a jump menu. As a default label for the jump menu I display "Please select category".

At the moment if I click submit while "Please select category" is selected, it just reloads the page. I want to be able to redirect to another page instead (only if nothing has been select in the drop down). How do I do it?

Thank you

# Answer
> 0 votes
Using `hook_form_alter` you override the default `$options` value used in `ctools_jump_menu` for the array key `_none` to whatever site url you want to redirect to.

---
Tags: routes, 7
---


# Question
Title: Download, Install and Configure New Drupal Instance within drush script
I am writing script to download, install and configure new Drupal site. The download and install steps are working, however. In the third step - configuration, i would like drush to bootstrap from the new installed directory, so the Drupal API is available for functions such as variable\_set(),drupal\_parse\_info\_file(). Here is the script so far:

```
#!/usr/bin/env drush
<?php

$default_dest = 'test-core';
$default_make = '../builds/build-drupal-core.make';
$make_file = ($build_src = drush_get_option('build-src', FALSE)) ? $build_src : $default_make;
$dest = ($build_dest = drush_get_option('build-dest', FALSE)) ? $build_dest : $default_dest;
$status = _process_make_file($make_file, $dest);
drush_print('Make Download '.(($status) ? "SUCCESS" : "FAILURE" ));

# Site
##########################################################
$siteName="Test Site";
$siteSlogan="Some test site";
$siteLocale="en";
##########################################################

# Database
##########################################################
$dbHost="localhost";
$dbName="drupal_test_db";
$dbUser="test_user";
$dbPassword="xxxxxx";
$dbPort ="3306";
##########################################################

# Admin
##########################################################
$AdminUsername="admin";
$AdminPassword="password";
$adminEmail="admin@example.com";
##########################################################

# Install core
##########################################################
// go to installed dir
drush_op('chdir', $dest);

$status = drush_invoke_process('@self', 'site-install', array('standard'), array(
                                                              'account-mail'=> $adminEmail,
                                                              'account-name' => $AdminUsername,
                                                              'account-pass' => $AdminPassword,
                                                              'site-name' => $siteName,
                                                              'locale' => $siteLocale,
                                                              'db-url' => 'mysql://'.$dbUser.':'.$dbPassword.'@'.$dbHost.':' . $dbPort . '/'.$dbName,
                                                        )
                              );
drush_print('Site Install - ' . (($status) ? 'SUCCESS' : 'FAILURE'));

//check if we can bootstrap
$self = drush_sitealias_get_record('@self');
if (empty($self)) {
    drush_die("I can't bootstrap from the current location.", 0);
}

# Enable modules
##########################################################
//@ToDo read from make file and enable modules
$build_file_parsed = drupal_parse_info_file($build_src);
print_r($build_file_parsed);

# Pre configure settings
##########################################################
//variable_set();

```

I tried different things as described in drush-isnt-bootstrapping-drush-script. I also tried something like creating dynamic alias:

```
$cur_dir = getcwd();
$site = array(
        'root' => $cur_dir,
        'uri' => 'http://default',
        '#name' => 'self',
        'path-aliases' => array(
            '%root' => $cur_dir
        ),
);

drush_bootstrap_max_to_sitealias($site);

```

All of the attempts have failed. How would one bootstrap from currently installed Drupal dir via drush script, so the Drupal API is available? Thank you

EDIT:

So, with a little bit more of understanding of Aliases, Phases and Bootstraping, i have

```
$site2 = drush_sitealias_get_record($cur_dir.'#default');
$boot_status = drush_bootstrap_max_to_sitealias($site2, DRUSH_BOOTSTRAP_DRUPAL_FULL);
drush_print('Attempting Bootstrap ' . (($boot_status) ? 'Yes' : 'No'));
drush_print('Current bootstap phase: ' . drush_get_context('DRUSH_BOOTSTRAP_PHASE'));

//perhaps it takes time to bootstrap
while(!drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL)){
    sleep(2);
    drush_print('waiting...current phase '.drush_get_context('DRUSH_BOOTSTRAP_PHASE'));
}

```

This showed that the phase is staying the same '0' even thou the variable 'boot\_status' confirming the attempt to bootstrap. Then i looked at the error:

($errors = drush\_get\_context('DRUSH\_BOOTSTRAP\_ERRORS')) ? print\_r($errors) : drush\_print('no errors') ;

This was printing the following error:

```
[DRUSH_NO_DRUPAL_ROOT] => A Drupal installation directory could not be found

```

I am confused because we are in the new install root directory. In addition, the alias is specifying the root as following(printed $site2):

```
[uri] => default
[root] => /Users/latvian/Sites/drupal/test/test-core
[path-aliases] => Array
    (
        [%root] => /Users/latvian/Sites/drupal/test/test-core
    )

[#name] => .Users.latvian.Sites.drupal.test.test-core#default

```

Why would drush not see the new install root directory? Thank you

# Answer
> 1 votes
i wasn't able to figure out how to bootstrap the new Drupal instance in the installation directory as i would like, but what worked was creating a separate drush script only for configuring the instance and call it from the installation script as following:

```
drush_shell_exec('drush ../config/drush-scripts/configure-site.php --debug --build-src=the-make-file-installing-the-site.make');

```

And the configuration script:

```
#!/usr/bin/env drush
<?php

// check if we can bootstrap
$self = drush_sitealias_get_record('@self');
if (empty($self)) {
    drush_die("I can't bootstrap from the current location.", 0);
}

//go to the install dir
drush_op('chdir', $self['root']);

# Enable modules
##########################################################
$build_file_parsed = drupal_parse_info_file($make_file);
$modules_to_enable = array_diff($build_file_parsed['projects'],array('drupal'));
$modules_enabled = drush_invoke_process("@self", "pm-enable", $modules_to_enable);
drush_print('Modules ' . (($modules_enabled) ? 'WAS' : 'WAS NOT' ). '  Enabled');

# Pre configure settings
##########################################################
# disable user pictures
variable_set('user_pictures',0);

# allow only admins to register users
variable_set('user_register',0);

# set site slogan
variable_set('site_slogan',$siteSlogan);

# Configure JQuery update
variable_set('jquery_update_compression_type', "min");
variable_set('jquery_update_jquery_cdn',"google");
variable_set('jquery_update_jquery_version',"1.7");

```

I hope one day it will become apparent why i wasn't able to do all - download, install and configure in one drush script or if you know, please, share

---
Tags: drush
---


# Question
Title: Node gallery: display image count in a template file
I use the Node Gallery API module (part of the node\_gallery project) to create galleries of nodes. Now I need to theme node--gallery.tpl.php to display the count of images in a gallery.

I tried to use the Node Gallery API function called node\_gallery\_api\_get\_item\_count, but it doesn't work. So I tried to look at the database and indeed the node\_gallery\_galleries table contains zero values on the item\_count and pub\_item\_count columns (even if I call the function with reset=TRUE).

So how to calculate the value directly from the database?

# Answer
> 1 votes
One answer:

```
<?php
  $results = db_select('field_data_node_gallery_ref_1')
  ->fields(NULL, array('entity_id'))
  ->condition('node_gallery_ref_1_target_id', $node->nid)
  ->execute()->fetchAll();

  $pcount = count($results);
?>

```

Explanation:

The `field_data_node_gallery_ref_1` table contains one row for each picture in the gallery. I filter it by the nid of the gallery (`node_gallery_ref_1_target_id`) in order to get only pictures in that gallery, then count how many pictures exist on the gallery by counting the results of the query array.

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


# Question
Title: Programmatically insert an image with caption
I'm trying to attach programmatically an Image with caption to my node. I'm using image\_field\_caption module.

```
    $node = node_load($nid);

    $path = "images/gallery_articolo/".$value['foto'];
    $filetitle = $value['desc'];
    $filename = $value['foto'];

    $file_temp = file_get_contents($path);
    $file_temp = file_save_data($file_temp, 'public://' . $filename, FILE_EXISTS_RENAME);

    $node->field_steps['und'][($value['order'] - 1)] = array(
        'image_field_caption' => array( 'value' => $value['desc'], 'format' => 'full_html'),
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => 1,
        'uri' => $file_temp->uri,
        'status' => 1
    );

    node_save($node);

```

I followed the stucture seen in devel, but I have a lot of issues..

This is the recent log entry:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'caption' cannot be null:
INSERT INTO {field_image_field_caption_revision} (field_name, entity_type, entity_id, revision_id, bundle, delta, language, caption, caption_format)
VALUES (
:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8), (:db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13, :db_insert_placeholder_14, :db_insert_placeholder_15, :db_insert_placeholder_16, :db_insert_placeholder_17);
Array ( [:db_insert_placeholder_0] => field_steps [:db_insert_placeholder_1] => node [:db_insert_placeholder_2] => 455 [:db_insert_placeholder_3] => 863 [:db_insert_placeholder_4] => article [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => und [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => [:db_insert_placeholder_9] => field_steps [:db_insert_placeholder_10] => node [:db_insert_placeholder_11] => 455 [:db_insert_placeholder_12] => 863 [:db_insert_placeholder_13] => article [:db_insert_placeholder_14] => 2 [:db_insert_placeholder_15] => und
[:db_insert_placeholder_16] => Wild Roses: fiori che sembrano appena sbocciati, che sottolineano ancora una volta la sua grande cifra stilistica, composizioni perfette per ogni dolce e speciale occasione.
[:db_insert_placeholder_17] => full_html ) in image_field_caption_field_attach_update() (line 234 of /sites/all/modules/image_field_caption/image_field_caption.module).

```

But, as you can see, the :db\_insert\_placeholder\_16 is valorized. Can someone locate where the error is? I can't find it..

Thank you ^^

# Answer
in the log entry it shows that `[:db_insert_placeholder_7]` and `[:db_insert_placeholder_8]` elements of the Array were empty - that might be the reason why **Insert** statement failed for the `caption` field:

```
Array
(
[:db_insert_placeholder_0] => field_steps
[:db_insert_placeholder_1] => node
[:db_insert_placeholder_2] => 455
[:db_insert_placeholder_3] => 863
[:db_insert_placeholder_4] => article
[:db_insert_placeholder_5] => 0
[:db_insert_placeholder_6] => und
[:db_insert_placeholder_7] =>
[:db_insert_placeholder_8] =>
[:db_insert_placeholder_9] => field_steps
[:db_insert_placeholder_10] => node
[:db_insert_placeholder_11] => 455
[:db_insert_placeholder_12] => 863
[:db_insert_placeholder_13] => article
[:db_insert_placeholder_14] => 2
[:db_insert_placeholder_15] => und
[:db_insert_placeholder_16] => Wild Roses: fiori che sembrano appena sbocciati, che sottolineano ancora una volta la sua grande cifra stilistica, composizioni perfette per ogni dolce e speciale occasione.
[:db_insert_placeholder_17] => full_html
)
in image_field_caption_field_attach_update() (line 234 of /sites/all/modules/image_field_caption/image_field_caption.module).

```

also, \[:db\_insert\_placeholder\_16\] - contains a string with 173 characters - is the `caption` field big enough?

hope this helps
> 1 votes

# Answer
In Drupal 7, you can use **system\_retrieve\_file**

> **system\_retrieve\_file** \- It will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file\_managed table if you want it to be managed.

```

  $node_info = node_load($nid);//load created node
  if(empty($node_info->field_image)){//assign only if the image field is empty
    $field_language = field_language('node', $node_info, 'field_image');//get image field language
    $url = 'https://ssl.gstatic.com/gb/images/k1_a31af7ac.png';//image URL to save. If image already saved in the drupal system then get the file ID(fid)
    //I have used picture folder to store images using image field settings
    $file_info = system_retrieve_file($url, 'public://pictures/', TRUE);//storing image inside picture folder
    if($file_info->fid){//if fid exist then image is saved from URL.
        $node_info->field_image[$field_language]['0']['fid'] = $file_info->fid;//assign fid
        $node_info->field_image[$field_language]['0']['image_field_caption']['value'] = 'test caption';//assign caption
        $node_info->field_image[$field_language]['0']['image_field_caption']['format'] = 'full_html';//assign format
    }
    node_save($node_info);//update node
  }

```

Note:

* Change your image field name.
* If the image is already stored in the drupal system then get the file ID(fid) and assign it to the image field directly.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Add css file to the Admin Theme of the Commerce Kickstart distribution?
I'm trying to add a css file to the Admin Theme (for Backend) of the Commerce Kickstart distribution.

I tried this in a custom module, but not working, the css file is not loaded at all.

```
drupal_add_css(drupal_get_path('theme', 'commerce_kickstart_admin') . 'css/overrides.css', array('group' => CSS_THEME, 'type' => 'file'));

```

I created the css file at:

```
profiles/commerce_kickstart/themes/commerce_kickstart_admin/css/overrides.css

```

Also, is there any way to put the css file in other location? like:

> site/all/themes/mytheme/css/overrides.css

# Answer
I would strongly suggest to create a subtheme for additional CSS. That's what subthemes are for, after all, and it's less work than to make a module. Simply use info file and it's `stylesheets[all][]` entry.

If you have time, you can investigate how AdaptiveTheme allows GUI editing of CSS, and implement this in your custom theme. AT is open-source after all, so it would be legal to copy-paste this functionality. It will make your life easier for future:
> 0 votes

---
Tags: commerce
---


title: OG + Exposed Filters + Views

text:
# Question
Title: OG + Exposed Filters + Views
What would be the smartest way to approach filtering content by the groups that it is posted in?

I will almost certainly need custom code to do this (I think a Handler, but I need someone to point me in the right direction), especially because I want to be able to filter by content posted in "All" groups, posted in a set of groups (i.e. a user's "core groups," determined by a taxonomy term reference on all users and groups -- if they are equal, that group is a user's "Core Group"), and also by each individual group that the user belongs to (but I don't want groups that the user isn't a member of showing up in the filter).

The docs for Views aren't very good, and I just know that there's an elegant, Drupal way to do this, and I need someone to point me in the correct direction (i.e what hooks, etc.)

Thanks in advance for help!

# Answer
> -1 votes
I think you can do what you want using OG and Views with nothing custom. This is a good place to get started: https://modulesunraveled.com/organic-groups-7x-2x.

---
Tags: views
---


title: How to add and condition in Query

text:
# Question
Title: How to add and condition in Query
I have to fetch nodes where it doesn't have both roles(6,7) in it,at the same time exactly.

I don't want to show role 7 nodes, but it some times have role 6 attached to it also ,at that time i want to omit those nodes.

This is the query which i wrote for that

```
$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition('ur.rid', 7, '<>');
$nids_result = $nids_result->execute()->fetchAll();

```

But this is fetching me all nodes including role 7 also,because role 6 is also some times available in the nodes.

How do I write and condition where it checks for both 6 and 7 roles are available and omit those nodes.Thanks in advance.

# Answer
> 1 votes
By default it is and condition

```
$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition('ur.rid', 7, '<>');
$nids_result->condition('ur.rid', 6, '<>');

// if you have devel installed check this.
dpq($nids_result);
$nids_result = $nids_result->execute()->fetchAll();

```

debugging the query with dpq will tell yuo the exact query that you can run on phpmyadmin and can see what you are missing.

**Updated:**

if you need query like

```
SELECT n.nid AS nid
FROM
{node} n
INNER JOIN {users} u ON n.uid = u.uid
INNER JOIN {users_roles} ur ON u.uid = ur.uid
WHERE ( (ur.rid <> :db_condition_placeholder_0) OR( (ur.rid <> :db_condition_placeholder_1) AND (ur.rid <> :db_condition_placeholder_2) ))

```

Code will be :

```
   $nids_result = db_select('node', 'n');
   $nids_result->join('users','u','n.uid = u.uid');
   $nids_result->join('users_roles','ur','u.uid = ur.uid');
   $nids_result->fields('n', array('nid'));
   $db_or = db_or();
   $db_or->condition('ur.rid', 7, '<>');
   $db_or->condition(db_and()->condition('ur.rid', 7, '<>')->condition('ur.rid', 6, '<>'));
   $nids_result->condition($db_or);
   $src = $nids_result->__toString();
   dpm($src);

```

# Answer
> 1 votes
I got through it using sub query and it is successful.

```
$query = "SELECT n.nid AS nid FROM node n INNER JOIN users u ON n.uid = u.uid INNER JOIN users_roles ur ON u.uid = ur.uid where u.uid NOT IN (SELECT u.uid FROM node n INNER JOIN users u ON n.uid = u.uid INNER JOIN users_roles ur ON u.uid = ur.uid where(ur.rid = 7))";

$nids_result_set = db_query($query)->fetchAll();

$nids_result = array();
foreach($nids_result_set as  $nids)
{
   $nids_result[] = $nids;
}

```

This returns all except role 7 nodes.

Where as the issue with below code is that

```
$nids_result->condition(
              db_and()
                ->condition('ur.rid', 7, '<>')
                ->condition('ur.rid', 6, '<>')
);

```

it has seperate entries for each role , so its not escaping for nodes which has both roles 6 and 7. So i have used sub query to get it through.

If any one can find much simple solution will be nice.Thanks all.

# Answer
> -1 votes
Another approach is to use db\_and(). Example:

```
$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition(
              db_and()
                ->condition('ur.rid', 7, '<>')
                ->condition('ur.rid', 6, '<>')
);
$nids_result = $nids_result->execute()->fetchAll();

```

---
Tags: 7, database
---


title: Custom form template without any region

text:
# Question
Title: Custom form template without any region
I made a custom log in, register and forget password templates, to hide the theme region and wrote a css code.

the issue here when open the page using colorbox module the regions appear for few second before they hide by css code, what i need to disable the theme region in those custom pages.

any advices? Thanks.

# Answer
> 1 votes
All you need to do is search your `page.tpl.php` for parts like:

```
print render($page['region_name']);

```

and then wrap them in appropriate `if` construct, not rendering them at all on pages you don't want to see them rendered.

Alternatively, you can create files named page--user.tpl.php, page--user--login.tpl.php and so on. See this answer for details. Simply copy default page.tpl.php and remove unneeded regions from a copy.

---
Tags: 7, theming
---


# Question
Title: Can i add a Slide show to my website in a block. Is it possible for my Theme
I would like to add slide show to my website. How can i do that. And i would like to add it as a block in all the pages. What is the easy way to do that.

Please suggest.

# Answer
> 0 votes
The easiest way is Views sldieshow module , create a views just in block . the screen cast is this and a lot more
and another help to choose a good slideshow module is this page

# Answer
> 0 votes
You could do this with the Fields slideshow module https://drupal.org/project/field\_slideshow and optionally the Colorbox module.

Create a content type with an image field. Configure it so that you can load infinite images. Set the formatter of the image field as "slideshow". Then create a block with views and display the block in your sidebar.

Here is a good screencast to set it up: http://vimeo.com/26411524

---
Tags: javascript
---