# Question
Title: shopping cart is empty when I programmically create order
I create a order with below code

```
      global $user;
     $product_id = 860;
     $price=intval($form_state['values']['field_suggest_your_price']['und'][0]['value']);
     dsm($price);
     dsm($form_state['values']);
// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
       $order = commerce_order_new($user->uid, 'checkout_checkout');

// Save the order to get its ID.
        commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
        $product = commerce_product_load($product_id);
        $product->commerce_price["und"][0]["amount"]=$price;

        $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
//// Save the line item to get its ID.
        commerce_line_item_save($line_item);
//// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
//// Save the order again to update its line item reference field.
commerce_order_save($order);
dsm($order);

//// Redirect to the order's checkout form. Obviously, if this were a
//// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);

```

but in `checkout/orderid` shopping cart is empty, any body know where is my fault? **appreciate any urgency help**

# Answer
> 2 votes
Here's an example on how to programmatically create an order and add a product to it, then redirect to checkout.

```
/**
 * Create new commerce_order with product
 * based on $_GET['pid'] from URL
 */
function MODULE_commerce_order_new(){

  global $user;

  // Sanitize just in case
  $product_id = filter_xss($_GET['pid']);

  // Load product
  $product = commerce_product_load((int)$product_id);

  if((empty($product->product_id)) || (!$product->status)){
    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }

  // Attempt to load existing order for user from session
  $order = commerce_cart_order_load();
  if(!$order){
    $order = commerce_cart_order_new($user->uid);
  }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;

  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  // Save new line item to get line item id
  commerce_line_item_save($line_item);
  // Add line item to order wrapper
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

  if(!empty($order->order_id)){
    drupal_set_message(t('Thank you, your %product is ready for checkout.',
                         array('%product' => $product->title)));
    drupal_goto('checkout/'.$order->order_id);
  }else{
    drupal_set_message(t('Sorry, there was a problem building your order. Please try again later.'), 'error');
    drupal_goto(); // frontpage
  }

}

```

# Answer
> 0 votes
Here is another example how to create commerce order programatically (it works with drush as well, e.g. `drush -vd -u "$1" scr order_code-7.php`). Please note that `commerce_payment_example` module is required.

```
<?php

  if (!function_exists('drush_print')) {
    function drush_print ($text) {
      print $text . "\n";
    }
  }

  $is_cli = php_sapi_name() === 'cli';

  global $user;

  // Add the product to the cart
  $product_id = 5;
  $quantity = 1;

  if ($is_cli) {
    drush_print('Creating new order for ' . $quantity . ' item(s) of product ' . $product_id . '...');
  }

  // Create the new order in checkout; you might also check first to
  // see if your user already has an order to use instead of a new one.
  $order = commerce_order_new($user->uid, 'checkout_checkout');

  // Save the order to get its ID.
  commerce_order_save($order);

  if ($is_cli) {
    drush_print('Order created. Commerce order id is now ' . $order->order_id);
    drush_print('Searching product ' . $product_id . ' in a Commerce system...');
  }

  // Load whatever product represents the item the customer will be
  // paying for and create a line item for it.
  $product = commerce_product_load((int)$product_id);

  if((empty($product->product_id)) || (!$product->status)){
    if ($is_cli) {
      drush_print('  Cannot match given product id with a Commerce product id.');
    }

    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }

  if ($is_cli) {
    drush_print('  Found a Commerce product ' . $product->product_id . '.');
  }

  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

  if ($is_cli) {
    drush_print('  Added product to the cart.');
  }

  // Save the line item to get its ID.
  commerce_line_item_save($line_item);

  // Add the line item to the order using fago's rockin' wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  if ($is_cli) {
    drush_print('Saving order...');
  }

  // Save the order again to update its line item reference field.
  commerce_order_save($order);

  // Redirect to the order's checkout form. Obviously, if this were a
  // form submit handler, you'd just set $form_state['redirect'].

  if ($is_cli) {
    drush_print('Checking out the order...');
  }

  commerce_checkout_complete($order);

  if ($is_cli) {
    drush_print('Marking order as fully paid...');
  }

  $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

  if (!$payment_method) {
    if ($is_cli) {
      drush_print("  No example payment method found, we can't mark order as fully paid. Please enable commerce_payment_example module to use this feature.");
    }
  }
  else {
    if ($is_cli) {
      drush_print("  Creating example transaction...");
    }

    // Creating new transaction via commerce_payment_example module.
    $charge      = $order->commerce_order_total['und'][0];

    $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
    $transaction->instance_id = $payment_method['instance_id'];
    $transaction->amount = $charge['amount'];
    $transaction->currency_code = $charge['currency_code'];
    $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    $transaction->message = 'Name: @name';
    $transaction->message_variables = array('@name' => 'Example payment');

    if ($is_cli) {
      drush_print("  Notifying Commerce about new transaction...");
    }

    commerce_payment_transaction_save($transaction);

    commerce_payment_commerce_payment_transaction_insert($transaction);
  }

  if ($is_cli) {
    drush_print("Marking order as completed...");
  }

  commerce_order_status_update($order, 'completed');

  if ($is_cli) {
    drush_print("\nDone.");
  }

```

---
Tags: 7, commerce
---


# Question
Title: How do I hide the display of a field if another field is set?
I have a content type with a date field. The date is mandatory, but I want the option to not show the date in all displays if the option is selected. This date field is not published date.

The content type has several display modes, so I want to disable this in all of them. What would be the best way?

My thought is to add an additional boolean field, "Hide date", but then I'm not sure what is a nice clean way to hide the date field everywhere if "Hide date" is selected.

# Answer
> 2 votes
Use the #states property. Here is a tutorial.

Alternatively just use the Conditional Fields module which provides a nice easy to use UI making it easy to set up multiple rules.

---
Tags: 7, entities
---


# Question
Title: How to set multi-value hidden field from javascript?
I have a multi-value text field, the values should be set from javascript on the browser.

For a single value text field, I can just set the value of the hidden field. But for multi-value text field, drupal **will only take the first value** and omit following values even the browser post more than one value.

I insert some `input` tag with same name (nearly, see below) under the form using jquery:

```
<input type="hidden" name="field_subscription_id[und][0][value]" value="52e1c1d99c29ec6fd84698b6" />
<input type="hidden" name="field_subscription_id[und][1][value]" value="52e1c1d99c29ec6fd84698b6" />
...

```

data is POST like this (inspect using dev tool of chrome):

```
field_subscription_id[und][0][value]=52e1c1d99c29ec6fd84698b6
field_subscription_id[und][1][value]=52e3de349c29ec6fd84698d4
...

```

After node created, the field `field_subscription_id` will only have the first value.

So, any idea to make this work? ~thx

## EDIT

I define the form from UI, just a normal content type and a text field. I make a ajax request to external site from page, let user select something (from the ajax response), then fill a field of add-node form with the selected ids.

Using the AJAX response, I build a list of `<li>`, each `<li>` has a checkbox, the `form` attribute (HTML5) of the checkbox has been set to the value of form-id of drupal add-node form on this page.

# Answer
Fields will only appear in the $field\_state array if they were there when the form was built. (If you inspect the $\_POST array directly you should see your values there.)

The solution: When creating the form add enough fields so you don't need to add any more with js.

If you didn't create the form yourself then use hook\_form\_alter to add more fields.

If you need to be able to add more fields on the fly then you will have to look into the #ajax property. The examples module has some good examples on that.

Also make sure to use the #default\_value, not #value property if you need to set a default value for any of the hidden fields as using #value will lock the value to that and stop the client from being able to make any changes.
> 1 votes

---
Tags: forms, javascript
---


title: Set node field value in separate form

text:
# Question
Title: Set node field value in separate form
I have a File field attached to my content type. Using Drupal, when we are creating new node, we use node form to set all field values for particular node. But is it possible to create more forms for editing one node? In particular, I need to setting File field values in separate page separated from node form.

For now, I do it with Form API, and hook\_form\_alter. For file field I can use form type "managed\_file". But is it possible with some existing module, using GUI? Could I create separate form, where I can set just one (or few) fields of node (or entity, in general)?

EDIT: to explain it shortly. I would like to split node form to more forms. I would be able to set, which node fields would be set in which form.

# Answer
> 0 votes
Not sure i follow your narrative up there but you might be interested in entity metadata wrapper to help you deal with the objects and their states individually with custom forms.

https://drupal.org/node/1021556

The project page: https://drupal.org/project/entity

---
Tags: 7, nodes, forms, files
---


title: Changing language in drupal

text:
# Question
Title: Changing language in drupal
So my problem is i dont know how to make my custom menu item change language in drupal. I know there is a language switcher in drupal, but i want to make a new custom menu in drupal, theme it, and i want the links to trigger changing the language, like the link "french" changes the site to french. How can this custom trigger of events be created in drupal and how do i know which functions to call/variables to change to allow me to achieve this?

I really appreciate any help!

# Answer
> -1 votes
May be you are looking for language\_negotiation\_get\_switch\_links

> Return the language switch links for the given language.

```
$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$links = language_negotiation_get_switch_links($type, $path);

```

# Answer
> -1 votes
If you have localized content, say an "About Us" page with and English version and a version of that page translated into French, then you're looking for Entity Translation.

You don't need to create a custom menu item as the Locale module, which ET depends on, provides this block for you. It should be called "Language switcher".

---
Tags: hooks
---


# Question
Title: How to distinguish radio and checkbox type in drupal
I have a content type which consists four types of fields. checkbox, radio, select, select multiple

I'm using `field_info_instances('node','bundle_name')` in my custom module to get filed info for my content type. I need this info to use somewhere.

My question is, how can I distinguish the checkbox type and radio type.same problem for select and multi select also.

Here is the output

# Answer
> 0 votes
I got the solution, I've used **field\_info\_field** function, In the return array I found the difference in cardinality.

The cardinality for checkbox is **-1** and for radio button is **1**. Similarly for select is 1 and multi select is -1

I found it myself, is there any better solution than this?

# Answer
> 0 votes
A field has a cardinality property (meaning how many values it can have) and a type property (meaning what *general* sort of form element to use).

I say *general* because the field object itself does not dictate the exact widget. That is controlled by `options_field_widget_form()` (docs here) which takes the field object and works out whether to use checkboxes or radio buttons based on the cardinality.

So yes you are right - examining the field object won't tell you which type of form element will be used, but you can assume it from the cardinality (so long as no-one has overridden `options_field_widget_form()`).

Multiple cardinality gets checkboxes; single cardinality means you are only allowed one choice, hence a set of radio buttons. By the way 1 and -1 are not the only possible cardinalities. -1 means unlimited. A cardinality of, say, 3 will also get a set of checkboxes.

---
Tags: 7, nodes, entities
---


# Question
Title: How to use default taxonomy with a mixture of terms and content?
My site has a structure like this, which seems a natural way to use taxonomy:

Food (term)
\- Fruit (term)
-- Apple (content)
-- Pear (content)
\- Bread (content)
\- Cheese (content)

The problem arose when I wanted an top-level overview page of Food. Logically (to me) that would mean showing Fruit, Bread and Cheese since these are the direct descendants of Food. But the default taxonomy term page for Food only shows Bread and Cheese, because it only shows content. It doesn't seem like you can show taxonomy terms in views, so overriding the view was not enough and I ended up doing some jiggery-pokery. As a fan of clean logical simple sites I would rather stick close to the defaults. What am I doing wrong?

# Answer
You probably want to replace the taxonomy/term/## page with a page view of content in that term and "attach" another view to the header that lists the child "taxonomy terms".

That way you them alongside your content as a browsable tree or as a list of "folders" above the content in that folder.
> 0 votes

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


# Question
Title: Adding custom meta tags to nodes, dependent on author name?
I would like to add the meta tag

```
`<meta name="robots" content="follow,noindex">`

```

to all nodes (content type is article) written by specific authors, not only for their new articles but for the few hundred that already exist.

I've installed metatag and metatags-quick, neither seem to offer the functionality I'm after. This is a drupal 7 installation.

I'd rather not have to edit the php, as I'm unfamiliar with that, but I will if I have to.

Does anyone know a way to do this?

# Answer
I don't know of a metatag module which gives you that level of granularity; you might have to do it in code.

Fortunately, it's pretty easy. You'll need a custom module, in which you should implement `hook_node_view()`, and use `drupal_add_html_head()` to add the meta tag based on custom logic.

Very brief example:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'foo' && $view_mode == 'full') {
    if ($node->name == 'admin') {
      $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'name' => 'robots',
          'content' => 'follow,noindex',
        ),
      );
      drupal_add_html_head($tag, 'MYMODULE:robots:noindex');
    }
  }
}

```
> 1 votes

---
Tags: meta-tags
---


# Question
Title: Drush install fails within Vagrant Puppet
I originally posted this on SO but thought I'd probably get more traction on the Drush side of things from you guys.

I've just gotten a new MacBook running Mavericks.

Unfortunately, I can't get our current project running on it.

We're using Vagrant and Puppet and during the `vagrant up` phase, I get a message telling me `err: /Stage[main]/Drush::Git::Drush/Exec[first drush run]: Failed to call refresh: /usr/bin/drush status returned 255 instead of one of [0] at /tmp/vagrant-puppet-1/modules-0/drush/manifests/git/drush.pp:32`

I can successfully `vagrant ssh` into into the instance but it's clear that Drush doesn't exist.

The only difference between the 2 systems is the operating system. All other files are from the same git repo and same branch.

Any insight would be welcome as this is a total ball-ache.

Thanks,

Steven

# Answer
> 4 votes
The drush.pp you are using is out of date. I have used that one successfully in the past, but just a few days ago, Drush switched to using Composer to install, so running drush status will no longer download the console table. Instead, you must run `composer install` after pulling Drush, or just install Drush via composer. See the Drush project page for details.

The Drush Puppet module you mention will need to be updated to adjust for this change in procedure.

*Note:* The drush.pp you are using would probably work if you told it to check out one of the Drush 6.x tags instead of using master (the default). Haven't tried that, though.

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


title: Drush from GitHub stopped working

text:
# Question
Title: Drush from GitHub stopped working
I have a Github clone of drush that has been working since it moved there. I did a `git pull` this morning, and am now getting errors:

> $ drush
>
> Warning: require(/home/mpd/drush/vendor/autoload.php): failed to open stream: No such file or directory in /home/mpd/drush/includes/bootstrap.inc on line 1007
>
> Fatal error: require(): Failed opening required '/home/mpd/drush/vendor/autoload.php' (include\_path='.:') in /home/mpd/drush/includes/bootstrap.inc on line 1007

How can I fix this?

# Answer
> 10 votes
Drush now uses composer for managing external libraries. You can read about this in the GitHub issue.

If you don't have composer installed, you can follow the instructions on its project page. Under Linux or OSX, you can do

```
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer

```

which will install it globally.

Once you have done this, you can

```
$ cd /path/to/your/git/clone/of/drush
$ composer install

```

This will download all of the external depencencies, and drush should start working.

See the drush project page for details.

---
Tags: drush
---


# Question
Title: Taking over a url and getting variables from url
I have a (non drupal bound) table, that I need to display within my site.

It has information about "runs":

userID (drupal) - runID - name - distance - ... etc

I want to go to site/run/runID and display the data of that particular run.

I don't know if there is an easy way of doing it without having to create a custom module for it? I basically just need to $get the variables and display them from the database. My first concern is calling my php code when the file is loaded.

And if I need to create a module for it. How would I go about it?

Or perhaps I can use panels to put my custom code on a page and get the url variables? Or some other module I am not thinking about...

--Update

To get started I created this little module. Now just reading the url parameter runID that is behind it...

```
function epicrun_menu(){
 $items['epicrun'] = array(
 'page callback' => 'epicrun_my_page',
 'title' => 'Callback',
   'type' => MENU_CALLBACK,
 'access arguments' => array('access content'),
 );
 return $items;
}

* this code (noted in the callback above) creates the
 * contents of the "epicrun" page */

function epicrun_my_page(){
 return "<p>This is my epicrun demo page.</p>";
}

```

# Answer
> 0 votes
Ok, creating a new module for that seems very easy:

```
function epicrun_menu(){
 $menuitems['run'] = array(
  'title' => 'Run data',
  'page callback' => 'epicrun_mymenu_page_callback',
  'page arguments' => array(0),
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
  );
 return $menuitems;
}

/**

* Implementation of hook_menu().

*/
function epicrun_mymenu_page_callback($firstparameter = '',) {

  $result = 'This page will display the run data of the run with ID '.$firstparameter;/*
   $result.='<br> The first parameter passed to the url is :<b>'.$firstparameter.'</b>';
   $result.='<br> The second parameter passed to the url is :<b>'.$secondparameter.'</b>';*/

  return $result;

}

```

# Answer
> 0 votes
I would suggest looking into the Data module. I does pretty much everything (and more) what you're describing in your request.

---
Tags: 7, uri
---


# Question
Title: Displaying and selecting data from a database in a module
I have a database table (gpx\_api) with the following fields:

```
runID   userID  score   distance    pace    speed   gpx_path    missionID   startTime   duration

```

I want to display all of these fields from within a module.

I have searched a lot on stack and I got until here:

```
   $query = db_select('gpx_api', 'run')
     ->fields('run')
     ->condition('runID', $firstparameter, '=')
     ->execute()
     ->fetchAssoc();

```

Do I only select the row where runID = $firstparameter like this?

This should only return one result. Now how can I display the fields one by one?

```
$query->distance

```

will not work.

I also tried

```
foreach($query as $result2){
 $result .="DISTANCE";
$result .= $result2->distance;
  }

```

This strangely enough gave a lot of results and errors.

I am sure there is a very simple way, but I am not familiar with the drupal API.

--Update

a var\_dump of query gives me:

```
array(10) { ["runID"]=> string(1) "2" ["userID"]=> string(1) "1" ["score"]=> string(2) "10" ["distance"]=> string(3) "200" ["pace"]=> string(1) "7" ["speed"]=> string(1) "8" ["gpx_path"]=> string(0) "" ["missionID"]=> NULL ["startTime"]=> NULL ["duration"]=> NULL }

```

so it is just about displaying the array. Shouldn't $query-\>distance work then? Yet if I try it, I get this error:

```
Notice: Trying to get property of non-object in epicrun_mymenu_page_callback() (line 62 of /home/suneesto/public_html/addons/epicrunapp.com/sites/all/modules/epicrun/epicrun.module).

```

# Answer
> 1 votes
Basic php error, it's $query\['distance'\]

---
Tags: 7, database
---


# Question
Title: How to import Custom Post Types of wordpress into Drupal?
I've a wordpress site with around 500+ posts of a Custom Post Type with some custom fields attached to them.

I want to migrate them to Drupal. I've tried using `wordpress_migrate`. But it doesn't seem to work! This module didn't even seem to recognize the Custom Post Types. How can I import them?

# Answer
> 2 votes
This isn't currently available in `wordpress_migrate` however there is a feature request open here. https://drupal.org/node/1580412

Your best option would be to write a custom migration using Drupal's migrate module. You would need to write a custom source to load your data from WordPress and you'd be able to look at `wordpress_migrate` for help as needed.

---
Tags: 7, migrations
---


title: Ignore Users Content with Flags>

text:
# Question
Title: Ignore Users Content with Flags>
I am developing a network of websites for our nonprofit organization.

As with any membership site, we have some members who simply do not get along and often, their back and forth "drama" will detract from the other member's positive, supportive experiences.

Rather than simply banning members who can't get along with each other, we'd like to set up a way for members to flag a member and "mute" them, so that instead of seeing their content, they will see a message like "You have muted this member and cannot view their post. To unmute the member, visit your profile page." or something to that effect.

There was a module for 6 that is ported to 7 called Ignore User, but it doesn't seem to be in a stable release for 7.

It seems to me that there has to be some way to do this with flags, rules, and views -- but I admit it is a bit above my knowledge level.

Has anyone ever done something like this on a Drupal 7 site? Can you help me make this work? I really do feel it will make a big difference for our chapters and minimize some of the "drama" we have to deal with on a regular basis.

Thanks Heather

# Answer
> 0 votes
There is Ignore User, but for D7 there is only a dev version that hasn't seen any progress in over 2 years. Might be worth a look though, maybe you can start with that and even contribute back any improvements.

Everything else would require a considerable amount of configuration concerning the flags themselves, any views listings and node displays. Probably you will even need to do some custom coding.

---
Tags: views, users, rules, flags
---


# Question
Title: Trying to create a widget that submits a form and takes you to another search page
The original example `http://www.trellon.com/content/blog/apachesolr-and-facetapi` uses an auto submitter, which I don't want. I'm trying to modify it to use checkboxes and submit with a submit button, however that doesn't appear to be working. I can select different boxes and submit, but it doesn't take me to another search page.

```
class ResourceLibraryWidget extends FacetapiWidget {
   /**
   * Renders the form.
   */
  public function execute() {
    $elements = &$this->build[$this->facet['field alias']];
    $elements = drupal_get_form('resource_library_facetapi_select', $elements);
  }
}

function resource_library_facetapi_select($form, &$form_state, $elements) {
  // Build options from facet elements.
  //$options = array('' => t('- Select -'));
  foreach ($elements as $element) {
    if ($element['#active']) {
      continue;
    }
    $options[serialize($element['#query'])] = $element['#markup']; //. '(' . $element['#count'] . ')';
  }

  $form['select'] = array(
    '#type' => 'checkboxes',
    '#options' => $options,
    //'#attributes' => array('class' => array('ctools-auto-submit')),
    'default_value' => '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Find Resources'),
    //'#attributes' => array('class' => array('ctools-use-ajax', 'ctools-auto-submit-click')),
  );

  // Lets add autosubmit js functionality from ctools.
  $form['#attached']['js'][] = drupal_get_path('module', 'ctools') . '/js/auto-submit.js';
  // Add javascript that hides Filter button.
  //$form['#attached']['js'][] = drupal_get_path('module', 'example') . '/js/example-hide-submit.js';

  $form['#attributes']['class'][] = 'resource-library-checkbox-facet';

  return $form;
}

```

Why isn't it working the way I intend? I'm trying to change different values on the submit button, but that doesn't seem to do anything.

# Answer
It's not clear from your question, so I will assume that you are missing the following:

```
/**
 * Submit handler for facet form.
 */
function resource_library_facetapi_select_submit($form, &$form_state) {
  $form_state['redirect'] = array(
    $_GET['q'],
    array('query' => unserialize($form_state['values']['select'])),
  );
}

```
> 0 votes

---
Tags: entities
---


title: How can I override images on migration?

text:
# Question
Title: How can I override images on migration?
I'm migrating images from URLs and I'm mapping the image field with this code:

```
$this->addFieldMapping('field_image', 'titlePhotos')
     ->xpath('/photo/@URL');
$this->addFieldMapping('field_image:source_dir')
     ->defaultValue(DRUPAL_ROOT . '/sites/default/files/images');
$this->addFieldMapping('field_image:file_class')
     ->defaultValue('MigrateFileUri');

```

I want to overwrite files if they already exit when running the migration for the first time and on update.

I'm using Drupal 7.

# Answer
The MigrateFileUri destination has a class property which indicates what to do when collisions are encountered.

```
  /**
   * How to handle destination filename collisions.
   *
   * @var int
   */
  protected $fileReplace = FILE_EXISTS_RENAME;

```

What you want to do is, extend MigrateFileUri override `$fileReplace` to be `FILE_EXISTS_REPLACE` and then use that as your destination.

example:

```
class MigrateFileUriReplace extends MigrateFileUri {
  protected $fileReplace = FILE_EXISTS_REPLACE;
}

```

Don't forget to update your migration code.

```
$this->addFieldMapping('field_image:file_class')
     ->defaultValue('MigrateFileUriReplace');

```
> 0 votes

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


title: Unsupported operand types

text:
# Question
Title: Unsupported operand types
hi suddenly i started to get Fatal error: Unsupported operand types in E:\localhost\htdocs\drupal\modules\field\field.info.class.inc on line 479

any page i visit just display this error

how to fix this ?

# Answer
The problem here is that in the given file, the line

```
$field['settings'] += field_info_field_settings($field['type']);

```

fails (i.e line 479), because `field_info_field_settings()` doesn't return an array. This shouldn't happen and it is probably caused by a custom or contrib module or by faulty data in your database.

You can try to trace the error down. Open `field.info.class.inc` in a text editor and put the following code directly above the line 479:

```
$field_settings = field_info_field_settings($field['type']);
if (!is_array($field_settings)) {
  print_r($field);
  die();
}

```

Then load a page where you would normally get that error and look at the printed details (I hope there are any). Then ask yourself the following questions:

* For which field are the settings requested?
* Does this field still exists?
* Is it a field declared by a module that you have disabled?

This should help you to trace down the problem.

Remember to remove the debug code!
> 4 votes

---
Tags: entities
---


title: What does General Cache Wipe mean

text:
# Question
Title: What does General Cache Wipe mean
The definition of CACHE\_TEMPORARY used in cache\_set reads as follows.

> CACHE\_TEMPORARY: Indicates that the item should be removed at the next general cache wipe.

I am just curious as to what `General Cache Wipe` means and what constitutes to `General Cache Wipe` other than obvious cron.

# Answer
> 5 votes
Any action that makes a call to either `cache_clear_all(NULL, $table);` on all core cache tables or a call to `cache_clear_all();` can be termed as `General Cache Wipe`

I could list down following based on a quick grep search for these functios.

1. Cron : Very obvious.
2. When a vote is submitted on a poll.
3. Any operation performed on `admin/content` page like
* Node Multiple Delete. (Handled as a special case with confirmation form)
    * Any other operation like
4. When node access is rebuilt. (Like change of permissions)
5. When menu cache is cleared. (Node module clears all the caches \[node\_menu()\])
6. Node Form Submission. \[Creation or Updation\]
7. Node Deletion
8. Comment Form Submission
9. Any operation performed on `admin/content/comment` page
10. Block administration. Any action performed on `admin/structure/block`
11. Create, Delete/Update any custom block.
12. Any forum form submit.
13. Any System Theme settings are changed.
14. When aggregator parses a feed.
15. Profile fields are edited/updated/deleted or their weights and categories are changed.
16. When a user account is cancelled.
17. When taxonomy term/vocabulary is added/deleted/updated.

---
Tags: caching, performance
---


title: Making menu wrapped in nav tag

text:
# Question
Title: Making menu wrapped in nav tag
I've got problem with making main-menu wrapped in element. I've tried:

1. Using hooks in template.php like:

```
function koko_menu_link_main_menu($variables) { /* For block override */
$output = '<nav>';
      foreach ($variables['links'] as $link) {
        $output .= l($link['title'], $link['href'], $link);
  }
  $output .= '</nav>';
  return $output;
}

function koko_links__system_main_menu($variables) {
  $output = '<nav>';
foreach ($variables['links'] as $link) {
  $output .= l($link['title'], $link['href'], $link);
}
  $output .= '</nav>';
    return $output;
}

```

Using preprocesss/block.preprocess.inc:

```
  switch ($variables['block']->module) {
    case 'system':
      switch ($variables['block']->delta) {
        case 'help':
        case 'powered-by':
          break;

      case 'main':
          // Use a template with no wrapper for the page's main content.
          $variables['theme_hook_suggestions'][] = 'block__minimal';
          break;

      default:
          // Any other "system" block is a menu block and should use
          // block--nav.tpl.php
          $variables['theme_hook_suggestions'][] = 'block__nav';
          break;
      }
      break;

      case 'menu':
      case 'menu_block':
      // Use block--nav.tpl.php template.
      $variables['theme_hook_suggestions'][] = 'block__nav';
      break;
  }

case 'main':
  // Use a template with no wrapper for the page's main content.
  $variables['theme_hook_suggestions'][] = 'block__minimal';
  break;

default:
  // Any other "system" block is a menu block and should use
  // block--nav.tpl.php
  $variables['theme_hook_suggestions'][] = 'block__nav';
  break;
 }
 break;

case 'menu':
case 'menu_block':
    // Use block--nav.tpl.php template.
     $variables['theme_hook_suggestions'][] = 'block__nav';
     break;
   }

```

That contains. block--nav.tpl.php

```
    <nav<?php print $attributes; ?>>
      <?php print render($title_prefix); ?>
      <?php print render($title_suffix); ?>
      <?php print $content; ?>
    </nav>

```

Still nothing happends. Main-menu is not wrapped in anything different than: `<div class="content">`.

# Answer
> 0 votes
Did you read this and this posts? I thinks it's not so difficult to achieve this:

```
function MYTHEME_links__system_main_menu($variables) {
  $html = "<div>\n";
  $html .= "  <nav>\n";
  foreach ($variables['links'] as $link) {
    $html .= "<li>".l($link['title'], $link['path'], $link)."</li>";
  }
  $html .= "  </nav>\n";
  $html .= "</div>\n";
  return $html;
}

```

---
Tags: blocks, hooks, navigation
---


# Question
Title: how to highlighted clicked taxonomy term
I am using below code :

```
 echo "<h1>".Volume."</h1>";
$tid=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
INNER JOIN taxonomy_term_data td ON th.tid=td.tid
INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
WHERE td.vid = '6' AND th.parent = '0'  AND book.entity_id = $nid
")->FetchField();
print $tid->Name;

$child=taxonomy_get_children($tid);
 foreach($child as $t){

$url = "taxonomy/term/$t->name";
    print '<a href="'.$url.'">'.ucwords($t->name).'</a><br>';

    }

```

they show volume 1,volume 2,volume 3 and they have linked problem is that when i am click on volume 1 they highlighted and show no link but other volumes are show linked in normal form

# Answer
I can only advise to use the available API functions.

To build the link use the  function:

```
$link = l(ucwords($t->name), 'taxonomy/term/' . $t->tid);

```

You can also pass in an options array, so to add an active class to the link when the link url points to the current page, you could use something like this:

```
$options = array();
if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2) == $t->tid) {
    $options = array('attributes' => array('class' => 'active'));
}
$link = l(ucwords($t->name), 'taxonomy/term/' . $t->tid, $options);

```

Also, this kind of code shouldn't be mixed directly in a template, especially not the database query. Have a look at the answers to this question for more insight: Preprocess functions and template files
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Adding a tab to commons browsing widget with hook_commons_bw_group_widget()
I am trying to add a tab to the Commons Browsing Widget so I made a custom module and followed this guide https://drupal.org/node/1782922. I used the first PHP code with hook\_commons\_bw\_group\_widget() but it doesn't add the new tab to the widget. What could be wrong?

# Answer
> 0 votes
Don't know if this is your module, but this one accomplishes just that: https://drupal.org/project/commons\_bw\_ui

It was posted just 2 weeks after your post above.

---
Tags: 7
---


# Question
Title: How to delete events from Full Calendar?
I'm using FullCalendar module

I have added an event. Now I want to delete it. How can I remove/delete an event from the calendar?

# Answer
if you want to be able to delete nodes directly from the calendar, here is how:

make sure you have the tokens module installed/enabled.

1. in your fullcalendar view, add the Content:Nid field.
2. add a global:custom text field that is under the nid field you just added, and input the following as the text:

node/\[nid\]/delete
3. click on the fullcalendar settings (under the format heading) and click "customize fields" click the "use a custom redirect URL" checkbox, then in the dropdown, select your custom text field you created in step 2.
4. save the view.

now when you click on the event, it will ask you to confirm or cancel the deletion of the node.
> 1 votes

---
Tags: javascript
---


# Question
Title: How to change redirect after adding node of a particular content type
I am currently developing a D7 site. One content type is a "resource," which is a link to an external site, or uploaded pdf file. I have a page view to list out all resources (/resource-list/edit ) that allows an admin to see resources broken up by category, reorder them, edit, and delete.

The edit, and delete links were added via views. I have also added an "Add new resource" button to the header of the view, which properly opens the add resource form in the admin overlay. However, when the admin submits the new resource, they are redirected to the new node that was created. Instead, I would like them to be redirected back to /resource-list/edit. How would one go about changing the redirect only for this content type, and only when triggered from the /resource-list/edit view page?

# Answer
You can do this with http://drupal.org/project/rules.

Just import this declaration and adjust it to your needs:

```
{ "rules_redirect" : {
    "LABEL" : "redirect to view",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "page" : "page" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "path/to/your/view" } } ]
  }
}

```
> 1 votes

# Answer
To redirect using a custom module you can use the following code (Drupal 7):

```
function MY_MODULE_form_alter($form, &$form_state, $form_id) {

    // drupal_set_message("Form ID is : " . $form_id); // this can be useful to work out the form ID of the form you want to target

    switch($form_id) {

        case 'page_node_form': // here we are making sure that we only add our additional submit handler to the node type we want

            $form['actions']['submit']['#submit'][] = 'custom_submit_handler';

            // dpm($form); // dmp provided by the devel module can be useful for inspecting the $form array

            break;

    }

}
function custom_submit_handler($form, &$form_state) {
    // this will redirect to the front page
    $form_state['redirect'] = '';
}

```
> 0 votes

# Answer
If all you want to do is change where a user redirects to after they submit an add node form, there is a much easier way.

Just make your link look like this: /node/add/\[CONTENT-TYPE\]?destination=\[URL-REDIRECT\]

Here is an example that I got working: /node/add/ic-competencies-toolkit-codes?destination=admin/survey-codes
> -1 votes

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


# Question
Title: Redirecting after submitting content - why this code doesn't work?
```
function MYMODULE_form_alter($form, &$form_state, $form_id) {
    if($form_id == "zdjecie_do_projektu_node_form" ||
       $form_id == "zdjecie_ze_szkolenia_node_form" ||
       $form_id == "referencja_node_form" ||
       $form_id == "zajawka_na_stronie_glownej_node_form" ||
       $form_id == "webform_node_form") {

        $form['actions']['submit']['#submit'][] = 'MYMODULE_node_submit';
    }
}

/**
 * Custom submit function.
 *
 * Redirect user to the site frontpage after node creation.
 */
function MYMODULE_node_submit($form, &$form_state) {
    $form_state['redirect'] = variable_get('site_frontpage', 'node');
}

```

The source for this solution is here: http://dropbucket.org/node/245

MYMODULE is of course replaced with real module name. The problem is that both functions are reached, however redirection doesn't happen. Any ideas what am I missing here? Or what could interfere possibly with this code? I have no other custom modules and this is the only custom code. I tried with Overlay and without Overlay with no effect.

# Answer
If you put a die in your MYMODULE\_node\_submit does it stop there after the form has been submitted? If it doesn't then your submit handler is not being called and you need to debug why that isn't happening.

I just tried your code on one Drupal site I have with a good 40 or 50 modules and I could not get my additional submit handler to fire. Could not work out why.

I then put the same code on a testbed Drupal site I have with only the core modules installed and it worked straight away.

Once you've made sure that you additional submit handler is being called the you just need to put:

```
$form_state['redirect'] = '';

```

to redirect to the front page.
> 0 votes

# Answer
if you're just redirecting to the front page after saving a specific content type, you could use rules to do that instead of a custom module.

just set up a new rule with the event of "after saving new content of type your\_content\_type."

then add a condition of "content is of type" with the data selector as "node" and content types value of your\_content\_type.

then add an action of "page redirect" and using the direct input method, use the \[site:url\] replacement pattern as your value.

that should redirect them to the front page after saving the new content. you can also add an event of "after updating existing content" as well.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Module to suggest node revision to node author
Is there a module which facilitates functionality of allowing users to suggest node revision to author and author finally can publish the revised suggestion. Till the author is not accepting or rejecting the revision the existing node will be displayed.

# Answer
> 2 votes
check out revisioning. It seems more like it's set up for moderators to view revisions before approving content, but perhaps it can be used for what you need.

# Answer
> 1 votes
After trying some modules in the list of modules Molot suggested and links robotsguide suggested I found Workbench Moderation module to give closest to the required functionality.

---
Tags: nodes
---


title: Solr Search or Views Exposed Filters

text:
# Question
Title: Solr Search or Views Exposed Filters
I have a food recipes site and it has a search feature on home page.

My Questions are :

Once the user search for some thing, they "continue to narrow down the results" . Is it possible with views exposed filters ? or i should be looking into Solar search for Faceted navigation and Relevancy tuning .

**Another Search Interface .**

# Answer
Assuming that you use proper fields that keep the relevant information (either in nodes or custom entities), it is possible that this can be achieved with Views exposed filters (the slider will require some client-side programming). For more search features, you can also use the Search API without needing to get into the complications of Apache Solr.
> 1 votes

---
Tags: views, search
---


# Question
Title: "Site off-line due to technical problems" (no extra info in message). What causes this?
What causes the following message on a Drupal 6 site with no other information?

> Site off-line
>
> The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.
>
> If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider's database server is running. For more help, see the handbook, or contact your hosting provider.

I think it means that the database did not respond in time but can someone confirm that?

I can force almost the same message by stopping the db but then it has some extra info under it about not able to connect to the db. That makes me wonder what it means when there is no extra info at all.

It is definitely related to slowness. It happens sometimes when the site is very busy and therefore slow. There is no obvious reason recorded in either the Drupal or Apache logs

Thanks

# Answer
> 6 votes
I'd wager you're using Drupal 6. And yes, it means a fatal error in connecting to the database.

# Answer
> 0 votes
It should happened in missing db names kindly check db name/username/pwd in settings.php

---
Tags: performance
---


title: Services get users email address

text:
# Question
Title: Services get users email address
I am trying to do the following thing:

-\> Authenticate a user against Drupal. -\> Get all information about user (including email address!)

So far I have tried to use the Drupal module services for this. I created a new service 'system' and activated the resource 'login','index' and 'retrieve'. I create a new admin user 'servicesAdmin' and gave him all the permissions (on Drupal side) there are available for the 'Services' module.

I created this little standalone PHP script to test my new service. It basically does three things:

STEP1 Login of test user 'tom'. This returns everything about Tom, but NOT the email Address:

STEP2 Login of the user 'servicesAdmin'. This returns the necessary session name, session id etc.

STEP3 Retrieving all information about user 'tom'. And here is the problem: If user 'servicesAdmin' has full admin rights, STEP3 will return the email address, if not it will only return all the fields but NOT the email address?

What can I do get email address without making the user 'serviceAmdin' to be a full administrator?

Thanks, Uwe Here is the code

```
$curl_options_post = array
(
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HEADER         => false,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_ENCODING       => "gzip,deflate",
  CURLOPT_USERAGENT      => "login", // who am i
  CURLOPT_AUTOREFERER    => true,     // set referer on redirect
  CURLOPT_CONNECTTIMEOUT => 0,      // timeout on connect
  CURLOPT_TIMEOUT        => 80,      // timeout on response
  CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
  CURLOPT_POST            =>true
);
$curl_options_get = array
(
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HEADER         => false,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_USERAGENT      => "login"
  CURLOPT_AUTOREFERER    => true
  CURLOPT_CONNECTTIMEOUT => 0,
  CURLOPT_TIMEOUT        => 80,
  CURLOPT_MAXREDIRS      => 10,
  CURLOPT_POST     =>false
);
//STEP1: login - authenticating user against Drupal portal.
$data = array('username'=>'tom','password'=>'password');
$url = '/portal.localhost/services/system/user/login.json';

$ch = curl_init($url);
curl_setopt_array( $ch, $curl_options_post);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
curl_response = curl_exec($ch);
curl_close($ch);
$user_login= json_decode($curl_response);
$uid = $user_login->user->uid;

//STEP2: Login 'servicesAdmin'
$data = array('username'=>'servicesAdmin','password'=>'password2');
$url = 'http://portal.localhost/services/system/user/login.json';
$ch = curl_init($url);
curl_setopt_array( $ch, $curl_options_post);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($ch);
curl_close($ch);
$admin_login= json_decode($curl_response);

//STEP3: Retrieve all information about user with '$uid'

$url = 'http://portal.localhost/services/system/user/'.$uid.'.json?parameters[field]=mail,uid';
$ch = curl_init($url);

$header = array
(
  'Connection: keep-alive',
  'Keep-Alive: 10000',
  'Cookie:'.$admin_login->session_name . '=' . $admin_login->sessid
);
curl_setopt ( $ch, CURLOPT_HTTPHEADER,$header);
curl_setopt_array($ch, $curl_options_get);
$curl_response = curl_exec($ch);

print_r (json_decode($curl_response));

```

The url in STEP1 is the way it is only for 'stackexchange' as it would allow me to save this post otherwise

I am not allowed to answer my own question (yet). Anyway, here is the answer to my own question: The 'problem'? lies within the file services.module in line 751

```
function services_remove_user_data(&$account)
{
  // Remove the users password from the account object.
  unset($account->pass);
  if (!user_access('administer users'))
  {
    unset($account->mail);
    unset($account->init);
  }
  drupal_alter('services_account_object', $account);
}

```

This function gets called in user\_resource.inc after the user objects got put together. From the code you can clearly see that 'mail' gets 'unset' if the call is not authenticated as 'administers users'.

Why? I can not explain, it seems random to me.

# Answer
> 3 votes
Had the same issue and it's something that I was banging my head against the wall why an authenticated user can't see his own email!

Here's the solution:

```
/**
 * Implements hook_services_account_object_alter().
 */
function HOOK_services_account_object_alter(&$account) {
  $account->mail = db_query('SELECT mail FROM {users} WHERE uid = :uid', array(':uid' => $account->uid))->fetchField();;
}

```

---
Tags: services
---


# Question
Title: How can i remove required field validation on click submit button?
I have some radio buttons such as draft, need review, etc. I want to remove (omit) the required fields when draft is selected, and click on the submission button. I tried with below code but it is not working.

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
 if($form_id =='catalog_node_form')
 {
  $form['#validate'][] ='remove_required_field';
 }
}

function remove_required_field($element)
{
 foreach (element_children($element) as $name)
 {
  $element[$name]['#required'] = FALSE;
 }
 return $element;
}

```

# Answer
In the form\_alter function you can use the limit\_validation\_errors property.

```
'#limit_validation_errors' => array(),

```

The above code will not perform any field validations. You can then add the individual fields that you need to validate here using the below code.

```
$form['actions']['next']['#limit_validation_errors'][] = array($field_key);

```

Where next is the action that I am using.
> 1 votes

# Answer
Problem with your code is caused by the fact that #required is resolved before custom validation handlers. Thus, when `remove_required_field()` is called, it's already too late.

Instead, un your `mymodule_form_alter()` hook set:

```
$element[$name]['#required'] = FALSE;
$form['#validate'][] ='function_that_will_test_checkbox_only_if_its_needed';

```
> 1 votes

---
Tags: forms
---


# Question
Title: Logo size should not reduce after uploading - Drupal 7
I have had uploaded a logo in my site.

After uploading the image's size is reduced. Because of that, image quality is decreased and it doesn't look good.

What should I need to do **TO NOT REDUCE THE SIZE OF THE LOGO** after uploading.

I'm uploading via `admin/appearance/settings/theme_name` and using **"Upload logo image"** option

In admin/config/media/image-toolkit the JPEG quality is 75%. I made it 100%, still it doesn't work.

Any suggestions or advices will be helpful...

# Answer
> 0 votes
Don't use "Upload icon image", that's for favicon. Use "Logo image settings" -\> "Upload **logo** image".

I tested this theme and both logo and favicon work perfectly. Logo is not altered in any way and favicon works, no matter what size.

---
Tags: 7, theming
---


# Question
Title: How to show book information in search result page
I want to show some extra book information in the search result page like node id, book id, book name etc. I have added some code in search-result.tpl.php but its still not showing.

```
$node->book['bid']  //is added to show book id.
$node->node['nid'] //is added to show node id.

```

Let me know where i am doing wrong.

# Answer
Finally managed it using search-result.tpl.php file which copied in theme folder.

```
 $url = $variables['result']['fields']['url'];

```

this variable gives search result urls from which i extracted book name and based in book name i printed book id. @Anil, thanks for the help which guide me at right direction and got to know many more.
> 1 votes

# Answer
Please find the full documentation regarding search-result.tpl.php .

Above documentation explains full node information is stored in $result. You can able to pull information like Node Id, Book Id, Book Name using $result variable. Use below code to print out $result variable in tpl file which you can override in your custom theme.

```
print '<pre>';
print_r($result);
print '</pre>';

```
> 0 votes

---
Tags: nodes, search
---


# Question
Title: Set expiry time for fields on content type
Is there a module which allows to set expiry date on fields on content type. Needed when we want a particular field to be expired after a given interval of time, not the complete node as in case of node expire module.

# Answer
First feature of Node expire is:

> * Perform custom actions when the nodes expire

Just write a custom action that will change field's value instead of unpublishing node.
> 4 votes

# Answer
As far as I know there is no such module. But since Node Expire integrates with rules, I could imagine that you can configure the node to expire without unpublishing it and then react on the expiration by setting the field value of the field(s) in question to empty.
> 3 votes

---
Tags: entities
---


# Question
Title: Views Related Items Block when Taxonomy term is not on URL
I have a "Views Related Items Block" problem which I thought was simple but have stopped me dead in my tracks for the last 2 weeks. I have Googled lots and lots of "Drupal Views Related" to no avail and hope someone will be kind enough to help me out.

Here is a sample content node:

TITLE: ABC123 (simple text string)

SHAPE: Square (stored as a taxonomy vocabulary called "Shape" with possible terms of "Square / Circle / Triangle")

COLOR: Red (stored as a taxonomy vocabulary called "Color" with possible terms of "Red / Green / Blue")

I have successfully created a VIEW PAGE configured to display the details of a product item at the URL:

http://www.mysite.com/products/square/abc123

where "square" (as a taxonomy filter) is the shape of the node item and "abc123" is the title of the node.

I would like to create a related items block on this page that will display all items that have the same SHAPE AND COLOR as item "ABC123" (square and red in this case).

I've played with MANY different configurations of "Content: Has taxonomy term ID / Load default filter from node page, that's good for related taxonomy blocks". But it seems like I can only successfully filter for "shape" and not "color". I just don't seem to be able to extract "color" given the above URL path.

I am open to using PHP code filter or even pre\_execute() SQL modification, but I have zero experience in doing that in Drupal.

Any help will be most appreciated!

Thanks.

Andrew

# Answer
Okay, I spent another day working on this and finally kind of got it working.

The goal here is to create contextual taxonomy filters that will retrieve all products with the same shape AND color as item "ABC123" as displayed on the browser URL, where item ABC123 happens to have a shape of "square" and color of "red".

Getting "square" into the taxonomy filter is easy,

1. create a view block
2. add a contextual filter of type "Content: Has taxonomy term ID"
3. since this is a block with no path, we need to give it a default value, do that and select "Taxonomy ID from URL" and "Load default filter from node page, that's good for related taxonomy blocks"
4. select the vocabulary you want (in this case "shape")

Now comes the hard part, we need to filter for "color" of item ABC123, but it is not on the browser URL in any shape or form. We need to somehow get the node contents of item ABC123, look into its "color" field, and then scan for all products with that color.

1. create a 2nd contextual filter of type "Content: Has taxonomy term ID"
2. click "Provide default value" and select PHP code

$title = arg(2, drupal\_get\_path\_alias()); // arg #2 is title of item on URL
$query = new EntityFieldQuery();
$query-\>entityCondition('entity\_type', 'node')
-\>entityCondition('bundle', 'product'); // product is the machine name of my content type
-\>propertyCondition('status', 1)
-\>propertyCondition('title', $title);
// title is a node property, for other fields use -\>fieldCondition

$result = $query-\>execute();

if (isset($result\['node'\])) {
$items\_nids = array\_keys($result\['node'\]);
$items = entity\_load('node', $items\_nids);
}

reset($items);
$first\_item = key($items);

$item = node\_load($first\_item);

$color = field\_get\_items('node', $item, 'field\_color');
return ($color\[0\]\['tid'\]);

For "Views Related Items Block", we also need to filter out ABC123, but that is an exercise left for another day.

Please note that this is the very first time I dabble into Drupal API calls, and the code above is clobbered together from various places on line. The code above make some assumptions (e.g. title is unique), is not efficient, may or may not handle translations and may not be totally secure. Reference at your own risk!
> 1 votes

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


# Question
Title: Forbidden 403 http request using deployment module
When I use the deployment module on my local websites it works perfectly, I make a devlopment plan, add one or more endpoints, I select some nodes and then I deploy the plan and run Cron. This way nodes that I selected are copied to my other sites in the multisite set-up.

When I use the exact some set-up for my live websites I get this error when executing the Cron: Link to image: http://imageshack.com/a/img401/5973/bwju.png

This has to be something with the permissions when I look it up on the net but I cannot find a solution. Link to module: https://drupal.org/project/deploy

Is there anyone that has tested this module and had the same issue and fixed it? Or is there someone that can tell me what to fix to make it work?

Thanks in advance

# Answer
> 0 votes
The answer to my own question:

Add this to your .htaccess file (I have put it at the top):

```
#
# Apache/PHP/Drupal settings:
# Paste the code under this sentence
<Limit PUT>
    allow from all
</Limit>

```

---
Tags: 7, deployment
---


# Question
Title: How to check if result from cache_get() is expired?
`cache_get` always returns an object and I'm a bit confused by its values. There's probably a short generic function that can handle this for once and for all.

```
$cache = cache_get('key');
if ($cache) {
  // doesn't work, cache_get always returns an object
}

if (!$cache || ($cache->created < time() - $cache->expire)) {
  // cache is expired? I'm not sure
}

```

Just checking for the data member doesn't cut it.

I had seen the issue reported on d.o (in 2009) but that doesn't really help me fix it on any live site. So I'm looking for a function that will still make cache work for me without resorting to storing the cache myself in the database.

# Answer
> 3 votes
**TL;DR Don't, unless you have to.** Drupal has long history of optimization and even if it sometimes serves you outdated cache, it's not without a cause. It's to prevent overhead of constant cache wipes. If your application is time-critical for some reasons, read below.

---

As you can see in the code that does the actual work:

```
function getMultiple(&$cids) {
  try {
    // Garbage collection necessary when enforcing a minimum cache lifetime.
    $this->garbageCollection($this->bin);

    // When serving cached pages, the overhead of using db_select() was found
    // to add around 30% overhead to the request. Since $this->bin is a
    // variable, this means the call to db_query() here uses a concatenated
    // string. This is highly discouraged under any other circumstances, and
    // is used here only due to the performance overhead we would incur
    // otherwise. When serving an uncached page, the overhead of using
    // db_select() is a much smaller proportion of the request.
    $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
    $cache = array();
    foreach ($result as $item) {
      $item = $this->prepareItem($item);
      if ($item) {
        $cache[$item->cid] = $item;
      }
    }
    $cids = array_diff($cids, array_keys($cache));
    return $cache;
  }
  catch (Exception $e) {
    // If the database is never going to be available, cache requests should
    // return FALSE in order to allow exception handling to occur.
    return array();
  }
}

```

There is no test built in1, and no limit that makes Core return only unexpired nodes.

* The way I prefer if I can, is to delete/hide table rows on database level, for example by creating a proxy view that never returns outdated records in the first place, but usually this is inconvenient. Don't try unless you know what you're doing.
* The Drupal-only way would be to add comparison in PHP, like that:

```
if (isset($cache->data) and time() < $cache->expire) {

```
* If your cache is relatively long, you can, and for performance reasons probably should omit testing their expire date on each call and leave it to Drupal's core. It will allow minimum cache lifetime to work with your data, for example. **That's how core is doing it**.1

---

1 There are some tests in `prepareItem` method, but for performance reasons they do not *guarantee* that outdated cache items will not be returned - see actual code for details.

---
Tags: caching
---


# Question
Title: How to insert a custom search fields in a views page
I have a view page showing some books and I want to have an advanced search with search criterias at the top of this page. The search box should search inside the books page or books content type.

# Answer
On your view, all you simply need to do is add a filter criteria and expose it to the user. So you add a filter criteria of your content type, that you will not need to expose since thats the one you want to search on.

If you are searching on the title, you add a filter criteria, select content:title, it takes you to the next selection, select expose to visitors. You can also choose what operator to use and if need be, you can also expose the operator. See screenshot
> 2 votes

---
Tags: database, views
---


# Question
Title: Organic Groups Permissions and Site-wide Roles
I currently have a Drupal 6 site set up using Organic Groups and OG User Roles. This is important because we have mainly public groups, however some pages in the groups are restricted by a user's role, such as staff or student. In this way, a page can be private to its group members, and additionally visible by those users who have the staff or student role.

OG User Roles has not been upgraded to Drupal 7 and we are attempting to find a replacement. OG 7 does provide integrated roles for groups, BUT it does not include the ability to set viewership based on these roles. Public / Private is too black and white, we need much more granular settings for our editors.

I have looked at Content Access, but we have about 20 roles on our site, and our editors would be overwhelmed by the options. Additionally, Content Access does not provide a way to prevent an editor from assigning "edit" or "delete" permissions, which is an issue for us.

We only want editors to be able to say "For this group page, this site-wide role can see this page." Very similar to the existent OG audience selection, but including site-wide rules as OG User Roles does currently in D6.

Is there any solution for this in D7 with Organic Groups?

# Answer
> 0 votes
In order to solve this we had to use an additional content access module, and we picked Simple Access.

Using the OG user roles built into OG for D7 we got our editing permissions under control, but that did not allow us to control *viewership* permissions for the content at all.

By utilizing Simple Access in addition to OG, we have the solution that we needed.

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


title: Cache warming for logged in user roles

text:
# Question
Title: Cache warming for logged in user roles
I have 2 pages that are highly customized per user, and I happen to know exactly when certain users are going to log in (this site is used by students during classtime). I have APC and memcache helping, but they are basically worthless here since my users hit these pages once or twice right at the beginning of their session and don't often return, but may spend over 10 seconds waiting for the page to generate when 40 users all log in at once and try to get the different versions of the same page.

I plan on significantly redoing these pages to make them less resource intensive, but for the moment, I'd love to be able to schedule a cron job to do a cache warm 10 minutes before class starts so they have a better experience sooner. Is there any way to do a cache warm for pages that are custom per user when I don't have their password?

# Answer
You can use `drush user-login` together with `curl` (or `wget`) like this:

```
drush --uri=http://your-site.com/drupal-dir-if-any/ user-login --browser=0 username path/to/heavy/site | xargs curl -L

```

The `drush user-login` command prints a one-time login link of the following form:

```
http://your-site.com/drupal-dir-if-any/user/reset/1/1390809497/hzqAmTzHMdBIXDIrkbDsmLIyPQtcDnjAufz9Fd5OUJk/login?destination=path/to/heavy/site

```

Then `xargs` will pick it up from `stdin` and passes it as last command line argument to `curl`. Finally the `-L` flag instructs `curl` to follow redirects. You might want to also supply `-o /dev/null` in order to discard the output of `curl`.
> 2 votes

# Answer
First things first, you probably should start caching these pages. If you don't know, then you don't cache pages for logged-in users at all.

See Authcache module:

> The Authcache module offers page caching for both anonymous users and logged-in authenticated users. This allows Drupal/PHP to only spend 1-2 milliseconds serving pages, greatly reducing server resources.
>
> Please note that enabling authenticated user caching will require modifying how your user-customized content displays on your pages. You should be an experienced Drupal developer if you choose to implement the full functionality of this module.

When you will have it, warming mentioned in znerol's answer will be able to make a significant difference.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Why can't I set radios default value (when after build is done)
I'm putting a node add form on a custom page that is a menu local task tab for specific taxonomy terms, and trying to set default values for some of the elements.

I'm building the form like this:

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

    module_load_include('inc', 'node', 'node.pages');
    $form = node_add('mtr');

    $form['field_shift'][LANGUAGE_NONE]['#default_value'] = 'early';
    // also tried this but it doesn't work either
    //$form[LANGUAGE_NONE]['early']['#default_value'] = true;

}

```

When I inspect the form array I can see:

```
#options (Array, 3 elements)
    early (String, 13 characters ) 23:00 - 07:00
    lunch (String, 13 characters ) 07:00 - 15:00
    late (String, 13 characters ) 15:00 - 23:00
#default_value (String, 5 characters ) early
#after_build_done (Boolean) TRUE

```

This shows my default value matches the options array key, however also shows that #after\_build is done. I suspect that the default value gets set in the after build function, however if I set after build to false I seem to get caught in an endless loop and the browser crashes.

I tried adding my own custom after\_build function to the form and setting the default values there, but because after\_build has already been done it is never called.

How can I set default values when building a form like this? Or is there a better way to load the node add form?

EDIT: Here is a paste bin with the whole form item array

EDIT2: This is a radios field that is part of a field collection that is part of a node add form.

# Answer
The assignment of the default value doesn't seem correct. I think it should be like this:

```
$form['field_shift'][LANGUAGE_NONE][0]['value']['#default_value'] = 'early';

```

See the following questions and their answers for more information:
> 1 votes

---
Tags: forms
---


# Question
Title: Features are sweet but what about content?
I used features successfully to restore my VIEW and content type...but the data for the content type didn't make it? Did I miss the option or is this something you typically bring over manually?

# Answer
Features are useful to export (and import) configurations, but is not useful for "entities": users, nodes, files, terms, and so on.

A great module to export and import is Node Export
> -1 votes

---
Tags: nodes, features
---


# Question
Title: How can I get Search API to index flags from flag.module
As far as I can tell by this issue, the Flag module should be visible to the Search API module, so I should be able to add it for indexing somehow, but I can't figure out how.

It is not present in the list of fields when editing the Search API index, nor in the “Add related fields” dropdown below. Any pointers?

# Answer
It seemed to be a caching issue or something similar. After reinstalling, the Flag was available in the Search API interface.
> 0 votes

---
Tags: 7, flags, search
---


# Question
Title: How can I associate an advanced forum with an organic group?
I am trying to set up a site which has forums and organic groups.

I want to set it up so the specific forum for a group appears only on that groups page.

By keeping tight control on group creation I can ensure that when a group is created I also create a forum for that group with the exact same name - this allows me to show the forum for that group on the group page by parsing the URL and then filtering by the group name to check it matches a forum name - then displaying that forum in the view on that groups page.. so far so good..

I have also added a group reference field to the forum topic content type, so topics show in the recent group content etc..

When adding a new forum topic, I'd like to automatically populate this field so the topic is assigned to the correct group, rather than give the user a choice, which they could then change. Hopefully this shouldn't be too hard as if a topic is added in the 'football' forum it will be the 'football' organic group that it should be associated with.

How do I go about doing this?

(if there is an easier way of doing the whole thing I'm open to suggestion there too! ie if the group name and forum name will always be the same anyway, it should make things easier all round, no?..)

# Answer
> 1 votes
I have struggled with this problem myself for some time and finally decided to just create a separate content type for my group forum topics and "create" a forum in each group with those topics.

I created a new content type called "Group Forum Topic." In Advanced Forum settings, I added this content type to the "node types to style" so that it would make it look like the forum.

On the og\_content view, I added an additional block and named it "Group Forum topics" and I changed it to use the forum topic list format. Using the view from Advanced Forum (Topic list) as a template, I set up the view to display the "group forum topic" content like a forum.

This allowed me better control over the permissions -- I am using entityreference-prepopulate to prepopulate the group when they add the content and I have the group content set to private, so I know that the content will be kept private to the group.

I tried using other modules, but ran into issues with auto-selecting both the forum name and the group and didn't want to chance the user accidentally not selecting one of those things on their own. After a lot of testing and trying, this seemed to be the easiest solution to having a private group forum on the group page.

Keep in mind this does NOT create a listing for the forum on the forum index page. What I have done instead is add my group listings to my forum index page view, so that beneath my "regular" forums, I have a listing of "groups," which contain their private forums inside.

This is my first answer here and I know this question is old... but I ran across it when I was researching this issue myself and thought perhaps the next person looking for a resolution might find it and it might help them!

---
Tags: organic-groups, nodes
---


# Question
Title: How to properly alter the output for fields of type file?
I have a file upload field which's format is set to generic file. It prints the following markup:

```
<div class="content">
  <span class="file">
    <img class="file-icon" alt="" title="application/msword" src="project/modules/file/icons/x-office-document.png">
    <a href="urltofile.doc" type="application/msword; length=22016" title="file.doc">Lorem ipsum</a>
  </span>
  <span class="file">
    ...
  </span>
</div>

```

But I'd rather not show the img at all, alter url text, something similar like this:

```
<div class="content">

  <span class="file maybe-some-custom-classes">
    <a href="urltofile.doc">$filename</a>
    <span>$description text of this field</span>
  </span>

</div>

```

What hooks would I have to use for this? And why is this so hard to find on the docs?!

# Answer
I'm guessing a bit here as I can't see what you have installed/configured...

The file formatter function is `file_field_formatter_view()`, and the only formatter which has an image attached to it runs through `theme_file_link()`. I would assume that's where the markup you're referring to comes from.

You can override that in your theme:

```
function MYTHEME_file_link($vars) {
  ...
}

```

Or, if you can get away without having to reproduce the function, just preprocess is:

```
function MYTHEME_preprocess_file_link(&$vars){
  ...
}

```
> 3 votes

# Answer
If it is a file field, not an image field, then it shouldn't be necessary to alter the template, but instead change the display configuration. See the attached screenshots.

Or am I misunderstanding your question?

Which then renders like this:

**Update:** Sorry, misunderstood the question, you don't want the icon in front, didn't catch that.
> 0 votes

---
Tags: files, entities
---


title: CSS Over-ride sub-theme

text:
# Question
Title: CSS Over-ride sub-theme
So I have got a base theme that is being used across multiple sites, but am wanting to add subtle tweaks to certain sites and was wondering what would be the best way to go about it.

I have created a sub-theme, which works fine. But, in order for it to work I need to bring all the files over from the parent theme, although I'm only changing the CSS. I thought it would use the files in the sub-theme and any files not in that folder just use the parent themes files.

# Answer
> 2 votes
To create a new subtheme, briefly:

* Create a new sub-directory in sites/all/themes with the machine name of the new theme.
* Create a new file in the new subdirectory with the machine name and extention .info:

> name = The human name of the new subtheme
>
> description = ...
>
> core = 7.x
>
> base theme = the-machine-name-of-base-theme
>
> stylesheets\[all\]\[\] = css/subtheme-new-file-name.css

* Regions are **not** inherited and should explicitly declared again, so copy over from base file theme info file.
* Color module file colors.css needs to be copied and added too, if the base theme supports it, otherwise a nasty error occurs.
* Favicon is not inherited
* Settings are not inherited

All the rest stay at base theme.

More about sub-theming: Creating a sub-theme

# Answer
> 0 votes
That is the "Drupal way". Sub-theming is made exactly for that.

If you want to do it differently, and load only CSS, you could do it in any number of ways. Perhaps creating custom CSS files that match the domain name, loading the appropriate one for each domain.

---
Tags: theming
---


# Question
Title: how to index unpublished nodes to apache solr
I want to display unpublish nodes to some of the user roles.

The apachesolr by default index only publish nodes.

Is there a way of indexing unpublished nodes to the apache solr index?

# Answer
> 0 votes
By default, with the Search API, it indexes unpublished nodes unless you specify it not to. There is a patch to change the behaviour in the workflow tab of the search api: https://drupal.org/node/1507882

Can you please clarify your setup? Are you using the Search API?

---
Tags: 7, search
---


# Question
Title: How to add a function to web form submit button?
On a Drupal site, when a form submission is done. I need to **trigger a SMS**. I am unable to edit the form submit code. Please let me know how to add a function to webform submit button. So that on **SUBMIT** button click the **SMS function** get executed as well the form data goes to the database.

# Answer
> 1 votes
Your mileage will vary, but it's the same as adding submit handlers to any form:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['actions']['submit']['#submit'][] = 'MYMODULE_some_function';
  }
}

function MYMODULE_some_function($form, &$form_state) {
  // Do something...
}

```

See `hook_form_alter()` for full details.

---
Tags: webforms
---


# Question
Title: How do I add a dropdown field in the commerce form?
Does someone know how to add a dropdown field to the commerce form?

I need to add a field where people need to select one of the 3 options. Ex.: "How did you know us?" (options: Google, a friend, I don't know)

Can anyone help me?

Thanks

# Answer
> 0 votes
I think this is what you are looking for: /admin/commerce/config/line-items/product/fields

This is where you can add fields to the product line item type. Make sure you have the Line Item UI module enabled or you might not have access to that UI.

---
Tags: forms, commerce
---


# Question
Title: Overriding File Entity fields when attached to a Node
We have a challenging user requirement that I've been puzzling over and wanted to submit this to the community:

We're using the Media 2 + File Entity modules for managing our site's image library. The Image bundles are fielded with meta data fields e.g. Title, Caption, Source, etc.

So here's the thing-- we need to have a way to override these on a case by case basis but if at all possible without duplicating the File. For example, with stock photography images, we only want to have one image of the lady with a pregnant belly, but it will be used in different ways throughout the site, and we need to be able to give it a different caption in two different places.

We really don't want to have the same image in the library twice with two separate captions. This would drive our editors crazy.

Thanks for any ideas!

# Answer
> 5 votes
There's no easy way to do this for files or images, which are essentially reference fields. There's no native way to do this for any type of reference field in Drupal. For example, you can create a reference field to a node, but override what the node's title is in a certain article when you reference it.

Typically what people recommend is using a Field Collection or a Multifield that consists of an image field + whatever field you want to have as the 'use this value only when this image is used here' stuff.

For captions, I know we added a caption filter specifically in Drupal 8 core, but I cannot find if it got back-ported for Drupal 7. That would be handy to have and use now.

# Answer
> 0 votes
This may be overkill but this is the solution I use to override image fields (stored as file entities and using Media 1) when they are attached to a node.

I use Views to display the image and associated meta data. I have to use a View because I show either a video or an image, depending on which is available. The View will eventually be displayed as a block on a node so I add a Contextual Filter to determine the current page's NID. The View has a Relationship to the file entity and pulls in the meta data fields. The meta data fields are then set to be hidden from display.

The node also has a caption field. The View is configured so that, if there a caption in the node, use that, otherwise, the "No Results" option is set to use the Related file entity's meta data.

I tie this together with Display Suite to create a Block Field which pulls in the View and makes it available to the node's Manage Display tab. And it is critical to configure the View's caching options to avoid slowing down the site.

---
Tags: media, files
---


title: How do I insert a localized menu item?

text:
# Question
Title: How do I insert a localized menu item?
When writing a custom module, what is the proper way to insert a localized menu via `hook_menu` or `hook_menu_alter`? By localized I mean not only the translated label - that'd be done using the `t()` function on title - but also having localized path and page callback.

I tried something like this:

```
function hook_menu() {
  global $language;
  $items = array();

  switch($language->language){
  case 'en':
    $items[] = array(
      'title' => 'Contact Us',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/285'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  case 'pl':
    $items[] = array(
      'title' => 'Kontakt',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/286'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  }
  return $items;
}

```

but this is not behaving properly - once created, the menu item stick at the original language regardless of subsequent language negotiations. So what is the way to go?

---

**Edit after trying out the code provided in answers** OK, so I approached that topic afresh and tried out all of the three methods suggested below. The two programmatic methods have the culprit that the array key used to install the menu item (as in: `$items['corporate/contact-us']`) will display in the status bar on hover, regardless of the language chosen. This is cosmetic but I consider it a bad UX. The third - UI-based - method has a side-effect (which is not the point of the original question) but was tried out just for curiosity. The point of my question was - whether it was possible to install a localized menu item totally programatically, and get exact result as when done through UI. Looks like this is not quite possible, unless there's a piece of know-how that I'm missing.

# Answer
The array returned from `hook_menu()` is cached, and each implementation of `hook_menu()` is only invoked when the cache is cleared, which what happens, for example, when a module is disabled/enabled.

If the users are redirected to a different node depending on the currently set language, then the code should be similar to the following one.

```
function mymodule_menu() {
  $item['mymodule_path'] = array(
    'title' => 'Contact Us',
    'page callback' => 'mymodule_redirect',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_redirect() {
  global $language;

  switch ($language->language) {
    case 'en':
      $goto = 'node/285';
      break;

    case 'pl':
      $goto = 'node/286';
      break;

    // ...
  }

  if (isset($goto)) {
    drupal_goto($goto);
  }
}

```

The alternative would be:

* Create a link through the user interface (admin/structure/menu/manage/main-menu/add)
* Use the following code to alter where the link takes

```
function mymodule_menu_link_alter(&$item) {
  if ($item['module'] == 'menu' && $item['link_title'] == t('Contact us')) {
    $item['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$item, $map) {
  global $language;

  if ($item['module'] == 'menu' && $item['link_title'] == t('Contact us')) {
    switch ($language->language) {
      case 'pl':
        $item['link_path'] = 'node/286';
        break;

      // ...
    }
  }
}

```

The first hook is necessary, or hook\_translated\_menu\_link\_alter() is not invoked.

The module could also programmatically add the link to the main menu. In this case, the code I would implement is similar to the following one.

```
function mymodule_enable() {
  $item = array(
    'link_path' => 'node/285',
    'link_title' => t('Contact us'),
    'menu_name' => 'main-menu',
    'mlid' => 0,
    'plid' => 0,
    'module' => 'mymodule',
  );

  menu_link_save($item);
}

function mymodule_menu_link_alter(&$item) {
  if ($item['module'] == 'mymodule' && $item['link_title'] == t('Contact us')) {
    $item['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$item, $map) {
  global $language;

  if ($item['module'] == 'mymodule' && $item['link_title'] == t('Contact us')) {
    switch ($language->language) {
      case 'pl':
        $item['link_path'] = 'node/286';
        break;

      // ...
    }
  }
}

```
> 2 votes

# Answer
The key to have a translated URL for a menu item is to create a **language specific path alias** for it. This can be done in PHP - with path\_save() \- when your module gets installed, or manually in the URL aliases configuration (/admin/config/search/path/add)

Then you can translate the menu item using common tactics of the i18n module bundle to have translated names of the menu item show up in your navigation. But this is independent of the translated URL path...
> 0 votes

---
Tags: routes
---


# Question
Title: Convert link from node/nid to Pathauto url?
Im using Pathauto to make my URLs nice and I may want to change the paths in the future. On some pages Im manually lining to other nodes.

The issue is that if I code the nice URL then the link will be broken if I change the Pathauto settings in the future. If I link to node/(the node id) then the link will always work, but its bad for SEO to not have keywords in the anchor text.

Is there a way to code in the NID so it always works but on the page show the nice URL?

# Answer
> 8 votes
I would, as Splat mentioned, check out the Global Redirect module, which will help out with google not seeing node/FOO and pretty/path pointing to identical content. If, however you are wanting to make sure that when engines scan your page content and pretty/path shows up inside the HTML, you can either continue to hardcode the paths, or create a function that returns the aliased path based on the nid.

```
function make_my_path($nid) {
  $pretty_path=drupal_get_path_alias('node/' . $nid);
  return $pretty_path;
}

```

Then use that (or `drupal_get_path_alias()` directly) in your templates or preprocess functions, or just use `l()`. If it is passed 'node/FOO' as the path, it will return the aliased path if one is set. (Unless you explicitly tell it not to; see `url()`.)

So, for example, `print l('Hello World','node/23');` should return `<a href="/pretty/path/to/node/23">Hello World</a>`.

# Answer
> 3 votes
If you're using CKEditor, you should use the CKEditor Link module. It allows searching content by title to insert, and in Drupal it saves the link as /node/\[ID\]. Then a text filter (which you'll need to enable for each text format it's being used on) replaces that URL with the current path alias in the rendered page.

# Answer
> 2 votes
I think you're looking for the Global Redirect module. This will make sure whenever you link to node/*x* that anyone following the link is redirected to the clean URL for that node.

---
Tags: navigation, path-aliases
---


# Question
Title: Simplest way to have dynamic content (year) in field's default value?
I'm looking for the simplest way in Drupal 7 to set simple dynamic content in the default value of a text field.

Specifically, I have a "Copyright notice" field, and I want the default value to be like this: "© Copyright Our Organisation \[YEAR\]", where \[YEAR\] is the current year. When the user creates a node in 2012, the form field is pre-populated "© Copyright Our Organisation 2012", and will be saved as this and stay as 2012 unless editted. When the user creates a node in 2013, the form field is pre-populated "© Copyright Our Organisation 2013" but all the old nodes made in 2012 don't change. EDIT: The field should still be editable, so users can replace it where it's not appropriate (e.g. if one piece of content they're uploading is actually "© Copyright Some Other Organisation 1981"): but the default should reflect the current year.

There seem to be a few options, but none of them seem particularly clean:

* **Using tokens**. It seems that this requires either the token\_filter module or the token\_insert module. Then, the default value could include \[current-date:custom:Y\]. However, it's not so clean. For token\_filter, the token from the default won't be translated until the user manually changes the input filter to "token filter" and hits save - bad for the user. For Token Insert, I believe the input field type would need to change to long text, and I'm not even sure it would work in the context of setting the default value.
* **Custom module**. Something like, setting the default value to include some gibberish string like "**_*!YEAR!*_**", and then use something like `hook_form_alter();` to find and replace. Or, defining some custom field that does this. Both involve fixing this specific combination of field and content firmly into code, which seems undesirable.
* **D7 CCK module**. It exists (as a dev module) and apparently it has some feature to do with setting lists using PHP that didn't go into D7 core. Sounds not very applicable to this case however.
* **PHP filter**. While you can set the Default Value field to use the PHP filter, in testing I found it doesn't actually apply the filter to the content you enter into the *default value* field. For example, putting `© copyright Our Organisation <?php echo date('Y'); ?>` into a default value field with PHP Filter applied just dumps that exact string, `© copyright Our Organisation <?php echo date('Y'); ?>`, into the field on the edit/create form, giving a user without access to the PHP filter nothing but some escaped text resembling PHP code, and giving a user with PHP filter access PHP code in the content of the field which continually processes, rather than becoming static text.

Am I missing something? Is there another way, or a variant on the above that is simpler?

# Answer
you can write a module and implement hook\_node\_save(). If the node is new just set the value of the field (a simple text string to something like:

```
$node->field_copyright_notice[LANGUAGE_NONE][0]['value'] = "© Copyright Our Organisation ".date('Y');

```

So in your own module you could do:

```
function MYMODULE_node_presave(&$node) {
 // Only do this for new nodes, eg nodes without a NID.
 if (!isset($node->nid)) {
     // Set our copyright text string.
     $node->field_copyright_notice[LANGUAGE_NONE][0]['value'] = "© Copyright Our Organisation ".date("Y");
 }
}

// You can also hide the field for new nodes with hook_form_alter().
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_NODETYPE_add_form') {
    $form['field_copyright_notice']['#access'] = FALSE;
  }
}

```
> 2 votes

# Answer
Why not you use hook\_form\_alter and add a default value to the text field?

You have to check that the default value is only when someone is in node/add/content-type, not in node/nid/edit.

```
    // You can also hide the field for new nodes with hook_form_alter().
    function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
     if ($form_id == 'node_NODETYPE_add_form') {
       $form['field_copyright_notice']['#default_value'] = t('here go my text');
     }
    }

```
> 0 votes

# Answer
To alter a field implemented using the field API from another module, you need to implement hook\_field\_widget\_form\_alter().

```
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field to change' && empty($element['#default_value']) {
    $element['#default_value'] = 'default value';
  }
}

```

The code works only if the default value set from the module implementing the field doesn't set a default value for the field, or the default value is an empty string. This means that, when the field is created through the user interface, its default value needs to be an empty string.
> 0 votes

# Answer
Here is a similar question: https://drupal.stackexchange.com/questions/39748/set-a-token-as-the-default-value-of-a-new-field

And probably the easiest way: Field Default Token module

And yes, the solution has to apply to only the DEFAULT value, not the actual value of the field itself, or else the tokens will get updated whenever you re-render the page.
> 0 votes

---
Tags: 7, entities
---


title: Remove tagging on node view

text:
# Question
Title: Remove tagging on node view
I am building a social network with Drupal. I have the following requirement:

1. A person who adds a post can tag his friends when adding his posts.
2. His tagged friends can untag themself when viewing the post.

Requirement #1 was met by the amazingly efficient entity reference view widget (see my recent answer).

But how to achieve requirement #2 ?

What is the best way to implement such a feature?

1. Is there any inline editing tool (such as the edit module) for entity reference fields?
2. Does editablefields really works for Drupal 7?
3. Should I just implement it using the Rules Link module?
4. Any other approach?

Please advise.

# Answer
I tried to define a custom field formatter but it didn't find the hook.

In the end it was much easier to use the Entity Reference Views Formatter module, then theme the view field to add the desired behavior to the relevant link. I used the rules\_link module to define the untag link, then added the untag link into the field's theme. Next time I should probably use a tpl.php file as well.

```
File: views-view-field--with--block--field-with.tpl.php

<?php
  global $user;
  $my_uid = $user->uid;
  $node = node_load ($row->nid);
  $results = db_query(      // Load the field without loading the entire node.
    "SELECT field_with_target_id
       FROM field_data_field_with
      WHERE entity_id = :entity_id",
    array(':entity_id' =>$row->nid));

  $lines = "";
  foreach($results as $result) {
    $uid = $result->field_with_target_id;
    $account = user_load((int)$uid);
    $rendered = l(mymodule_get_realname($account), "user/$uid");
    $untag = "";
    if ($uid == $my_uid) {
      $rules_link = rules_link_load('un_tag_me');
      $untag = render(rules_link_render_link($rules_link,$row->nid));
      $untag = str_replace (
        array("<div ", 'title="x"'),
        array("<div title='Un-tag me'", 'title="Un-tag me"'),
        $untag);
    }
    $line = "<div class='field-item'>$rendered $untag</div>";
    $lines .= $line;
  }
  if (!empty($lines)) {
    $output = "<div class='field-items'>$lines</div>";
  }
  print $output;
 ?>

```
> 0 votes

---
Tags: 7, rules, entities
---


# Question
Title: "Organic groups: Group node" equivalent?
I have several Drupal 6 views that use the "Organic groups: Group node" relationship. Does anyone know what the equivalent relationship in Drupal 7 is? Trying to set this up in Drupal 7 and the wording is confusing as I don't know what.

# Answer
> 2 votes
The one I was looking for (after much trial and error) is "OG membership: Group Node from OG membership"

That relationship seems to be the same as "Organic groups: Group node" in Drupal 6

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


# Question
Title: Change download directory when installing new modules using "Install from a URL"
I like using the "Install from a URL" method of installing modules as it's really easy. The problem is that it, by default, downloads the module to "/sites/all/modules", but I like to have my directory structure like "/sites/all/modules/contrib" and "/sites/all/modules/custom", therefore I would like automatically downloaded contrib modules to be downloaded into the "/sites/all/modules/contrib" folder. Is there a way to tweak this setting somewhere or do I need to hack core?

# Answer
Unfortunately I believe there is no way to change this in settings because there is no setting in the update module to change the installation path. If you check the update module configuration (*admin/reports/updates/settings*) there are fields regarding updating, but nothing regardig the installation path.

Even if you read the documentation (https://drupal.org/documentation/install/modules-themes/modules-7#using-drupal-interface) its never mentioned there. You would simply have to hack the core.

On the other hand, I recommend using drush (https://github.com/drush-ops/drush) with simple command (`drush dl [module_name]`) which *does* respect your *contrib* directory out of the box.
> 3 votes

---
Tags: 7, files
---