# Question
Title: How to expire views cache in code or with rule?
I have a view with block display that shows a user's picture and profile info. The view is cached for 1 hour.

How can I expire that cache when the user updates the profile?

# Answer
> 3 votes
I ended up using Views Cache Actions. It allows to use rules to expire a specific view or views displays when a certain event occurs (like user profile save).

# Answer
> 1 votes
Give it a try Views Content Cache

> This module implements a views cache plugin that is aware of content and can provide caching for views, until the content in those views changes.

Since, profile content is saved as a node the above module should work as it tell. Try and let us know !

OR

If above module doesn't address the isue we are looking for then use hook\_profile2\_update to hook into profile update and use the logic in above module to clear cache of a respective views block.

---
Tags: 7, views, caching
---


# Question
Title: How to setup Drupal Performance Monitoring to Bypass Varnish?
I have lots of uptime problems with my Drupal hosting company this month. Most of the time my Pingdom monitor doesn't even alert of the problem because Varnish is still able to serve a cached homepage.

How can I bypass Varnish to check true health of the Drupal instance? They have a username/password option but I'm sure that's for the http username/password and not for a form based login. If I specify a fake session cookie I could bypass Varnish but then Drupal would just redirect me to the home page?

# Answer
I could bypass it by adding a "NO\_CACHE=1" cookie to the request. Using a POST instead of a GET request will bypass Varnish as well.
> 3 votes

# Answer
Varnish is just like a proxy, so you configured that to get data from something like 127.0.0.1:8080 I guess.

So you just have to configure your pingdom to check example.com:8080 if you allowed your webserver listen also public request.
> 0 votes

---
Tags: 7
---


# Question
Title: Clean field value handling inside views_handler_field subclass?
I am writing a few views\_handler\_field subclasses that render fields of my entity depending on other values of the entity. The examples I see use a very awkward way of accessing the other field data, eg.

```
function render($values) {
  if (isset($values->field_name[0])) {
    $my_stuff = $values->field_name[0]['raw']['value'];
  }
  ...
}

```

Is there a clean way of accessing other fields in the entity, like EntityMetadataWrapper? I would just load the entity and create a EMW instance but that seems expensive to do for each cell in a big table.

# Answer
field\_get\_items() and field\_view\_value() are as clean as it gets without Entity API.
> 0 votes

---
Tags: entities, views
---


# Question
Title: Create new page without using Views or Panels?
I'm now in process of reducing the numbers of module used in the website. I will disable Panels and several other modules, but still using Views.

(The website is not too complicated, but because many modules involved, it become quite slow.)

Instead of using Panels, I'm customizing the appearance through dozens of template files.

But I just wonder, is it possible to create new page without using Views or Panels?

# Answer
> 1 votes
Yes, You can write a small custom module to create pages with out using heavy panels module.

Please see the hook\_menu documentation.

```
function yourmodulename_menu() {
  $items['page_one'] = array(
    'title' => 'Title of Page',
    'page callback' => 'page_one_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['page_two'] = array(
    'title' => 'Title of Page',
    'page callback' => 'page_two_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

 function page_one_callback() {
   $content = "";
   return $content;
 }

 function page_two_callback() {
   $content = "";
   return $content;
 }

```

To make your life much more easy without any coding, just go to "node/add/page" and create a new page !

---
Tags: views, panels, 7
---


# Question
Title: Returning Values from Tableselect Form with AJAX
Objective:

To combine AJAX Autocomplete with my Tableselect Form to create a key for users to select imported products that don't match existing products within your Drupal site. This new billing module would make it possible to use a specific 3rd party billing service.

Issue:

I am unable to get the following code to return the values inserted via the AJAX row. The array continues to send back the array keys of the row as both keys and values. Here is what the original selection is:

And here is the returned values:

As you can see the rows selected have their array key listed as the value on return, where as the non selected row has the value 0.

Question: **How do you change the return value so that it is the value that was selected on my AJAX form field?**

```
function Test_product_form($form, &$form_state)
{
  $form_state['page_num'] = 2;

  $form['Markup'] = array(
    '#markup' => t('Please select and synchronize Test Subscription Offers with your Drupal Commerce Product SKUS below:') . '</br>' . '</br>'
  );

  foreach ($form_state['sub_offers'] as $key => $offer) {
    if ($offer['Status'] == 'Active') {
      $product = commerce_product_load_by_sku($offer['OfferCode']) ? commerce_product_load_by_sku($offer['OfferCode']) : FALSE;

      if ($product === FALSE) {
        $rows[] = array(
          'Test Subscription Offers' => array(
            'data' => $offer['OfferCode'],
            'id' => 'row' . $key . '-aso',
            'class' => 'col-aso'
          ),
          'Drupal Product SKUS' => array(
            'data' => array(
              // drupal_get_form('commerce_product_line_item_add_form'),
              '#type' => 'textfield',
              '#title' => t('Product SKU'),
              '#description' => t('Enter the SKU of the product to add to the order.'),
              '#autocomplete_path' => 'commerce_product/autocomplete/commerce_product/line_item_product_selector/product',
              '#size' => 60,
              '#maxlength' => 255,
              //In order for AJAX within the Rows of tableselect form you must declare the
              '#id' => $key . 'product_textfield'
            ),
            'id' => 'row' . $key . '-dps',
            'class' => 'col-dps'
          )
        );

      } else {
        $rows[] = array(
          'Test Subscription Offers' => array(
            'data' => $offer['OfferCode'],
            'id' => 'row' . $key . '-aso',
            'class' => 'col-aso'
          ),
          'Drupal Product SKUS' => array(
            'data' => array(
              '#type' => 'link',
              '#title' => $product->sku,
              '#href' => 'admin/commerce/products/' . $product->product_id
              // '#options' => $l_options,
              // '#suffix' => ' ' . theme('mark', array('type' => node_mark($node->nid, $node->changed))),
            ),
            'id' => 'row' . $key . '-dps',
            'class' => 'col-dps'
          )
        );
      }
    }
  }
  $hinput = array(
    'Test Subscription Offers' => 'aso',
    'Drupal Product SKUS' => 'dps'
  );

  foreach ($hinput as $hkey => $hvalue) {
    $header[$hkey] = array(
      'data' => $hkey,
      'id' => 'head-' . $hvalue,
      'class' => 'col-' . $hvalue
    );
  }

  $options = array();

  foreach ($rows as $key => $row) {
    $options[$key] = array(
      'Test Subscription Offers' => $row['Test Subscription Offers'],
      'Drupal Product SKUS' => $row['Drupal Product SKUS']
    );

  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    //'#js_select' => TRUE,
    '#multiple' => TRUE
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array(
      'Test_payment_submit_step_two'
    ),
    '#validate' => array(
      'Test_payment_validate_step_two'
    )
  );
  ddl_once($form);
  return ($form);

}

```

# Answer
> 6 votes
Short answer: you cannot use tableselect for submitting form elements.

Longer answer: the tableselect is for selecting one or multiple **rows** for further processing. You can check this through your submit handler only receiving one value for each **row**.

See http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#tableselect (it links to a full example on http://drupal.org/node/945102#drupal7).

If you really need a table form you could use dwillcox suggestion to use a theme function to render your form as described http://drupal.org/node/1587968

I'm not sure but have you thought about multiple forms on one page? That is each line from your tableselect attempt has it's own form. For this to work you need to implement a hook\_forms(). I've used this for annotate module.

Some arguments about tableselect versus theming a form:

* As table select **adds radio or checkboxes** it changes the complete form thus its meaning. The bad implementation of Drupal is it renders the form elements thus making the complete page looks like a form.
* Theming your form is ugly as the exercise from http://drupal.org/node/1587968 shows.

Some nitpicking one your code:

* mixed case function names : violation of the coding standards
* mixed case array keys: this is not expected by most coders.
* swapped the key and value for $hinput which makes it hard to maintain.

Let us know what solution you took.

---
Tags: ajax, commerce, forms
---


# Question
Title: How to alter node load system to make it possible for only one field is attached to a node?
I have created a special content type using the build-in field system, which allows users to create multiple instances of the body field. In some circumstances the body field could be as large as 20M.

I would like to implement a hook that when a user visits a certain URL like `node/1/body/0`, then when `node_load` is called, only the body field with `delta == 0` is loaded into `$node` object, so it won't affect much for the performance.

Is it possible? Thanks in advance!

# Answer
> 2 votes
After a long research, found a solution :-)

You can do it using views module and views\_field module. Follow below steps to achieve the solution without doing a full node load or full field items load so that you can achieve the performance you are looking for !

* Install views module
* Install views\_field module
* Go to the body field settings page and enable the base table by checking " Expose as base table" checkbox.
* Create a new view with base table as "Field Body" while creating a new view in show dropdown.
* Remove fields in the field list
* Set the path as node/%/body/%
* Add field "Field Tables: Body \> value"
* Add contextual filter "Field tables: field\_body =\> Entity id" and set default value as "Raw Value from URL" and Path component as "2"
* Add one more contextual filter as "Content: Body:delta" and set default value as "Raw Value from URL" and Path component as "4"

That's it !! It worked for me !!

By implementing above solution, views module directly queries body table with delta and entity id as filters and get's the body value which you will be looking for without loading full node or field body items !!

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


# Question
Title: Show / Hide administration menu (module)
Is it possible to use a javascript function for a link in Drupal? I would like to make an option to show/hide the administration menu when clicked on the Drupal icon. Something simple like this:

```
  $links['icon'] = array(
    '#title' => theme('admin_menu_icon'),
    '#attributes' => array('class' => array('admin-menu-icon')),
    '#href' => 'javascript: alert("ok")',
    '#options' => array(
      'html' => TRUE,
    ),

```

# Answer
Very simple... Just found it myself :)

```
'#attributes' => array('onmousedown' => array('alert("ok")')),

```
> 2 votes

# Answer
I quickly made a small module to show/hide the administration module when clicking on the Drupal icon. Sometimes the menu bar is just anoying me ;)

```
function mymodule_init() {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/adminmenu.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));
}

function mymodule_theme_registry_alter(&$theme_registry) {
    if (!empty($theme_registry['admin_menu_icon'])) {
        $theme_registry['admin_menu_icon']['function'] = 'mymodule_admin_menu_icon';
    }
}

function mymodule_admin_menu_icon($variables) {
  return '<img onmousedown="jQuery(\'#admin-menu\').toggleClass(\'collapsed\')" class="admin-menu-icon" src="' . $variables['src'] . '" width="16" height="16" title="Show / Hide" alt="Show / Hide" />';
}

```

And the CSS part:

```
#admin-menu.collapsed {
    position: fixed;
    width: 20px;
    height: 20px;
    overflow: hidden;
}

```
> 0 votes

---
Tags: 7, javascript, routes
---


title: Denying access to node form edit

text:
# Question
Title: Denying access to node form edit
I need to make some checks on node access form based on user/role attributes that cannot be handled by Drupal core modules, so i think to do them in \_form\_alter hooks.

Which is the best thing to do when the user has not access to the form edit ? I can do a drupal\_goto(...) but i would like to stay in the same form, showing an access denied command. How can i do it?

# Answer
I think the standard way to handle this would be to implement `hook_node_access()`, make your checks there, and deny access if any of your conditions aren't met.

This will result in the standard 403 page when a user without the correct permissions tries to access the page, which semantically speaking would probably be the best result.

The code might look something like:

```
function MYMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'my_type' && ($op == 'create' || $op == 'update')) {
    if ($account->something == 'something') { // allow access
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }

  // Return the default ignore value if your module doesn't need to get involved in this decision
  return NODE_ACCESS_IGNORE;
}

```
> 4 votes

---
Tags: 7, forms
---


# Question
Title: Drupal7 multistep module - how to skip validation on previous
I created a multistep node form in Drupal7 using the multistep module (http://drupal.org/project/multistep)

I patched the module so it would work (previously Drupal complained about required fields that weren't on the current step). The module is working fine now, the only thing is that if I press the previous button, it still validates the current step. I want to skip this validation, so the current step is only validated if I press the next or done button.

I digged into the module code, but really cannot figure out what to search for.

Can anyone help me on this?

Edit: Here's my form\_alter function for multistep:

```
function multistep_form_alter(&$form, &$form_state) {
if (isset($form['#multistep'])) {
  $excluded_children = _multistep_gather_excluded_fieldgroup_children($form, $form['#multistep']['current']);
  $current_children = _multistep_gather_current_children($form, $excluded_children);

  $prev_excluded_children = _multistep_gather_excluded_fieldgroup_children($form, $form['#multistep']['previous']);
  $prev_current_children = _multistep_gather_current_children($form, $prev_excluded_children);

  // Apply limit validations to all submit fields.
  foreach (element_children($form['actions']) as $key) {
    if ($key == 'previous') {
        if (isset($form['actions'][$key]['#type']) && $form['actions'][$key]['#type'] == 'submit') {
          $form['actions'][$key]['#limit_validation_errors'] = $prev_current_children;
        }
    }
    else {
      if (isset($form['actions'][$key]['#type']) && $form['actions'][$key]['#type'] == 'submit') {
          $form['actions'][$key]['#limit_validation_errors'] = $current_children;
      }
    }
  }
}

```

}

# Answer
> 3 votes
I'm not familiar with the multistep module, but in Drupal 7 this functionality can normally be accomplished by using #limit\_validation\_errors. It would probably be best to alter the form(s) that you need with hook\_form\_alter (or a variation of it) in a custom module. A basic untested example of what I described:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'THE_RELEVANT_FORM_ID') {
    $form['THE_PREVIOUS_BUTTON_KEY_NAME']['#limit_validation_errors'] = array();
  }
}

```

---
Tags: forms
---


# Question
Title: Displaying Taxonomy Terms which are used by a Content Type
I have created a taxonomy named Category which has a number of terms like Agriculture, Business, Computers, etc.

I have created three content types viz. Products, Suppliers and Buyers. All of these types use the terms from the Category taxonomy.

What I am trying to do is create a block named Supplier Categories which as the name suggests, displays a list of terms from the Category taxonomy which are associated to Suppliers. So say if you have Suppliers associated to the Agriculture and Business categories then this Block should show them. It shouldn't show Computers though because no Supplier uses this term.

I am not sure whether this is possible or not but I have spent a lot of time playing with blocks but I couldn't get it to work.

By the way, I am trying to do this using Drupal 7.

# Answer
> 5 votes
You should use Views. Here are the steps to do to achieve what you would like to do:

1. Create vocab. "Category":
2. Create content type "Suppliers" with a "Term reference" field to "Category" vocabulary:
3. Create three "Suppliers" contents in "Agriculture", "Business" and "Blabla" categories - so these 3 should be listed in your block.
4. Add a new view at `admin/structure/views/add` with these settings:
5. Add a new field "Content: Category":

(here are the settings)
6. Remove "Content: Title" field ( , )
7. Set some descriptive names (like machine name, block name, display name, etc.), AND set Sort Criteria to "Content: Category (asc)":
8. Save
9. Go to `admin/structure/block`, set "Supplier Categories block" to be displayed in the "First sidebar" (or "Sidebar first" in Bartik) or any other, then hit "Save blocks":
10. You are ready.

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


# Question
Title: When does Drupal load variables from the database?
I am writing a report module so that users can flag posts and write a description. This module has a block that shows the unwatched reports; every time this block is shown it gets the number of unread reports from a table.

Is it better to use the Drupal variable system to set the number of unread reports? When does Drupal load the variables from the database? Does it load them when I call `variable_get()`?

# Answer
If the values need to be continuously updated, then it is better not to use `variable_get()`/`variable_set()` for storing it. This is because every time variable\_set() is called, it clears the cache containing the values of the variables, which means that the next time a page is required, the Drupal variables will be loaded from the database, and not from the cache, with consequent lose of performance.

In such case, it is better to count the number of unread reports when reading from the database table containing the report data. This means the database table should contain a unread field that is set to `TRUE` when the report has not been read.

The values of the Drupal variables are loaded from the database, or the cache, when Drupal is bootstraping; the called function is variable\_init(), which first checks the cache, and loads the values from the database, if the cache is empty.

```
  if ($cached = cache_get('variables', 'cache')) {
    $variables = $cached->data;
  }
  else {
    $result = db_query('SELECT * FROM {variable}');
    while ($variable = db_fetch_object($result)) {
      $variables[$variable->name] = unserialize($variable->value);
    }
    cache_set('variables', $variables);
  }

```
> 2 votes

---
Tags: 6
---


title: Why is this query not working?

text:
# Question
Title: Why is this query not working?
I have this snippet:

```
$nid = db_query("select nid from {node} where title = :title", array(':title' = 'scrivimi'))->fetchField();
dsm($nid);

```

It should work, at least from what I've read around the drupal api reference, but it doesn't.

I think the problem is with placeholders. In fact, if I execute the query without them, it runs perfectly, and returns the expected result!

Can you help me please?

I am using Drupal 7 (updated to the latest version), and I am testing this code using the Devel module.

# Answer
> 0 votes
There is a typo in your code: In the array literal, you are using `=` instead of `=>` which should separate the array index from its value.

The correct code is the following one.

```
$nid = db_query("SELECT nid FROM {node} WHERE title = :title", array(':title' => 'scrivimi'))->fetchField();

```

As side note, every SQL reserved words should be written in uppercase.

# Answer
> 3 votes
You have a tiny error in your code, the placeholder array should be

```
array(':title' => 'scrivimi')

```

not

```
array(':title' = 'scrivimi')

```

---
Tags: 7, database
---


# Question
Title: How to enable block "overlay" with a gear
How to enable the gear in the top-right corner of a block in Drupal 7 as shown in the screenshot below?

I have several Drupal 7 installations with Bartik theme and only one of them has it and I can not find, where to enable it for the others.

# Answer
> 3 votes
You just need to turn on the core Contextual Links module, and make sure that all roles that should be able to see those links have the "Use contextual links" permission.

If it's still not showing, check to see if your theme has a custom block.tpl.php file. If so, make sure that the `$title_prefix` and `$title_suffix` variables are being printed out (see the original template file).

The contextual links output is contained in one of those vars (I think it's `$title_suffix` actually) so the links won't be printed unless the correct one of those vars is also printed.

---
Tags: 7
---


# Question
Title: Custom block doesn't work correctly when not logged in
So I have a custom block module that displays three links, which then when clicked, reload the page and redirect to checkout based on a GET variable.

```
function innovista_donate_contents() {
  if(isset($_GET['d'])){
    switch ($_GET['d']) {
      case 1:
        $product_id='6';
        break;
      case 2:
        $product_id='8';
        break;
    }
    commerce_cart_product_add_by_id($product_id, $quantity = 1, $combine = TRUE);
    drupal_goto($path = 'checkout', $options = NULL, $http_response_code = 302);
  }
  else {
    return '<div class="col8wrap donate">
      <a class="dhover" href="?d=1">Link 1</a>
      <a class="dhover" href="?d=2">Link 2</a></div>';
  }
}

```

The issue is that if you are not logged in then often the top half of this function that uses the GET var doesn't work. I thought it might be a cache issue so cleared the cache but this hasn't resolved the issue. Any idea what is going on here?

# Answer
You block is build on the first page request. The else flow is followed. Depending on you settings the page or block is cached. Logged in users don't have cached blocks.

That it worked now and then for anonymous was probably due to your cache clears.

You should create a callback using hook\_menu() like

```
function innovista_donate_menu() {
  return array(
    'innovista/addtocart' => array(
      'title' => 'Innovisata add to cart',
      'page callback' => 'innovista_donate_add_to_cart',
      'access callback' => TRUE, // Accessible for everybody
      'type' => MENU_CALLBACK,
    ),
  );
}

function innovista_donate_add_to_cart() {
  if(isset($_GET['d'])){
    switch ($_GET['d']) {
      case 1:
        $product_id='6';
        break;
      case 2:
        $product_id='8';
        break;
    }
    commerce_cart_product_add_by_id($product_id, 1, TRUE);
    drupal_goto('checkout');
  }
}

```

Your block can now contain just the links. You can now disabled PHP input filter probably too.

(Note I changed your drupal\_goto and removed tabs)
> 3 votes

---
Tags: 7, commerce
---


title: Drupal 7 Update Manager not working

text:
# Question
Title: Drupal 7 Update Manager not working
Update manager takes me to the page where I select the checkbox for the updates I need. I check the box of the module and then it downloads the update. After the download it tells me I should put my site in maintenance mode with a checkbox that is on by default. The button says "Continue" to install the updated module.

My problem lies after this point. No updates are installed and after clicking "Continue" I get booted to my home page with the message "Operating in maintenance mode. Go online."

So currently the only way to update my modules is manually. Update manager doesn't work for me. Any pointers as to why it behaves the way it does?

# Answer
> 0 votes
Does yoursitename.something/update.php runs after you put it your browser location. I can only guess maybe your site hosting space is full or you might not have given update permission to the role by which you are updating the site.

---
Tags: updating
---


# Question
Title: How to replace teaser/content for anonymous users
I'm kind of new to Drupal so please bear with me. My question is, is it possible to replace the teaser/content for anonymous users? I have some restricted content but I don't want it to be removed and hidden from anon users, just show something that says they should be logged in to view the content/teaser. I've searched for hours and everything that comes up hides the content completely. I've seen a module that kind of does this thing (restricted content module) but it's only available on d6. I'm using d7.

Thanks in advance!

# Answer
> 1 votes
You can separate teaser from body as a new field, and use module "Field permissions" or similar modules.You can control access for that field.

Another way is custom module which use hook\_node\_view or hook\_node\_grants\_alter to control if user can access node.

# Answer
> 1 votes
For displaying different teaser for anonymous user, you can create a custom tpl for that node type and put your message in it.

```
global $user;
if ($user->uid) {

  //Default code for node teaser/content

} else {
  echo "Your custom message";
}

```

Make sure you place your tpl in theme folder.

---
Tags: views, 7
---


title: How to add logic to Webform

text:
# Question
Title: How to add logic to Webform
Using webform 3 module, how to add logic to my multi-step form so that I can choose what to display on second step based on the choice from step1?

I have been successful doing this using Forms API, but then I loose the ability to do webform reporting(analytics). Is it possible to combine form (design, analytics and validation) using "webform module" with logic using Forms API? or is there a better solution?

# Answer
It appears Webforms has conditional rules which works great. Also there is a module called Webform Conditional for in page conditional statements.
> 3 votes

---
Tags: 7, webforms
---


# Question
Title: Using drupal_goto for checkout redirection to add $_GET variable, but gets overwritten
So I want to do redirect to the following URL:

> http:/www.url.com/checkout?foo=bar

Tried using this:

```
drupal_goto($path = 'checkout', $options = array( 'query' => array( 'foo' => 'bar')), $http_response_code = 302);

```

Now it works, but instally redirects to this:

> http:/www.url.com/checkout/order\_id/

...meaning that I lose the GET variable. How do I do this? The same happens if you just type /checkout into the address bar, it redirects to checkout/order\_id. I think it might be commerce doing this automatically. Any idea how to resolve this?

# Answer
> 1 votes
So the checkout URL path requires an order id else it is redirected by the commerce system.

To combat this issue I needed to get the current user's order ID, if they didn't have an order, one needed to be created, so that we do have an order ID. Once you have this you can then use drupal\_goto with the path \*checkout/order\_id\*. The checkout URL is now valid meaning the GET vars can be included and are no longer overwritten with a redirect.

```
global $user;
     $user_id = $user->uid;
     if($user_id){
        $uid =  $user_id;
     }else{
        $uid = 0;
     }
      $order_id = commerce_cart_order_id($uid);
      if(!$order_id){
        commerce_cart_order_new($uid);
         $order_id = commerce_cart_order_id($uid);
      }

 drupal_goto($path = 'checkout/'. $order_id, $options = array( 'query' => array( 'amount' =>  $amount, 'allocation' =>  $allocation )), $http_response_code = 302);

```

# Answer
> 1 votes
`drupal_goto` should work just fine. You can confirm (e.g with Firebug) that it does the initial redirect to where you want (including `foo=bar`). Then you'll see a second redirect to the plain URL which is being performed by another code/module that you haven't told us about.

---
Tags: 7, commerce
---


# Question
Title: Services: Getting error 406 Node type is required - but I have specified the node type
I'm trying to create a node using jQuery to POST JSON.

I get the following error returned by the server: Failed to load resource: the server responded with a status of 406 (Not Acceptable: Node type is required)

However, the type is definitely specified in my JSON string:

```
var data = '{"title":"Sample post ",
  "type":"article",
  "field_link":
            [{
             "url":"http://www.google.com",
            "title":"My title"
            }],
  "body":
            {
             "und":[{"value":"comments about something"}]
             }
  }';

```

# Answer
1. try to observe the order of fields like: type \> title \> body \> fields
2. that is the widget type of "field\_link"?
3. add "und" to this field

```
{"title":"Sample post ",
"type":"article",
"body":{
"und":[{
"value":"comments about something"}]},
"field_link":{
"und":[{
"url":"http://www.google.com",
"title":"My title"}]}}

```
> 1 votes

---
Tags: services
---


# Question
Title: What do all these problem have in common (can't find the origin)?
A series of problems appeared in my install and I need help to narrow them down to a probable cause.

Most problems come in Views

**1)** All the dropdown menus that group options are gone. Clearing the cache will then display then again for once. Reloading the page again reproduces the issue.

**2)** Some block views with ajax/exposed filters are broken: instead of reloading themselves they call the home page with the arguments in the url: `http://www.mysite.com/?field_tags_tid_i18n_op=or&field_tags_tid_i18n=All&status=All`

Again, clearing the cache may solve the issue, but only once

**3)** Here and there, some glitches such as an geofield map not showing in a form until clearing the cache. And again, clearing the cache is only a one time fix as the issue reproduces next time the page is loaded.

I have tried the following: \- Clear the caches (All cache taken indepently work except CSS and Javascript, Theme and tokn regsitry, and update data) \- Clear the content of cache tables directly in mysql \- Remove all performance otions (aggregate css and javascript, cache,...)

# Answer
> 0 votes
So the problem was the dhtml-menu module with the "Expand on bullet option"

---
Tags: views, ajax, theming
---


title: Sort by content types in a view

text:
# Question
Title: Sort by content types in a view
I have 12 content types and a view that shows the title and description of each piece of content.

I want to sort the results of the view as follows: First, node types 1, 4, 5 and 9. Then, node types 2, 6, 10 and 12. And finally, node types 3,7,8 and 11.

Is it possible to sort the results of this way?

Thanks.

# Answer
you can test this with a custom module to alter the query of the view. for example:

```
<?php
function nameofmodule_views_query_alter(&$view, &$query) {
    if($view->name == 'nameofview') {
            $query->orderby[0] = "node.type = 'nodetype1'  DESC, node.type = 'nodetype4'  DESC, node.type = 'nodetype5'  DESC, node.type = 'nodetype9'  DESC, node.type = 'nodetype2'  DESC, node.type = 'nodetype6'  DESC, node.type = 'nodetype10'  DESC, node.type = 'nodetype12'  DESC, node.type = 'nodetype3'  DESC, node.type = 'nodetype7'  DESC, node.type = 'nodetype8'  DESC, node.type = 'nodetype11'  DESC";
    }
}
?>

```
> 4 votes

# Answer
Tried several things, but the one bulletproof solution that I could come up with is to use Views Attachments

1. add a page display, filter by node type 1.
2. add an attachment display, filter by node type 4, attach to the page display, after its content.

Repeat 2 for each of the remaining node types in the desired order.

It will be a big view, but should do the trick.

Edit: that is the best solution I came up with, without an extra module.
> 4 votes

# Answer
I am unaware of a way to do this using the Views UI.

It should be possible to do this via `hook_views_query_alter` and using `ORDER BY CASE` syntax.

Some rough code would look like

```
function mymodule_views_query_alter (&$view, &$query)
{
  if ($view->name == "the_view_machine_name") {
    $query->orderby = array("
      CASE node.type
        WHEN 'content_type_1' THEN 1
        WHEN 'content_type_4' THEN 2
        WHEN 'content_type_5' THEN 3
        WHEN 'content_type_9' THEN 4
        WHEN 'content_type_2' THEN 5
        WHEN 'content_type_6' THEN 6
        WHEN 'content_type_10' THEN 7
        WHEN 'content_type_12' THEN 8
        ELSE 1000
      END
    ");
  }
}

```

If the two content type groups are equivalent, then just make the weights the same for each group.

However, I am not totally sure if I have used this syntax before with this hook before (can't find the site where I used this recently...). Also double check the syntax as this is untested.
> 4 votes

# Answer
One idea that might be useful for someone searching for the solution in Drupal 7. I wanted to put one content type first, so this was the solution:

1. Find the field used to enter taxonomy terms for the vocabulary that you put your content type into
2. Add that field as the first sorting criteria (desc in my case). It will put that content type in front of the others.

Probably this could work with multiple content types, but in this case one field was enough.
> 1 votes

---
Tags: views, 6
---


# Question
Title: How can I create a user object in a custom form and save it?
Basically, I want to create a user object in a custom form and save it in the database.

This is my custom form and its handlers.

```
function registerme_newform($form, &$form_state) {
  $form['account details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account Details'),
    '#description' => t('Enter Personal Credentials'),
  );

  $form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#default_value' => t('Be sure of your first name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your first name'}",
    'onfocus' => "if (this.value == 'Be sure of your first name') {this.value = ''}",
    ),
  );

  $form['account details']['last name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#default_value' => t('Be sure of your last name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your last name'}",
    'onfocus' => "if (this.value == 'Be sure of your last name') {this.value = ''}",
    ),
  );

  $form['account details']['email'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Mail'),
    '#required' => TRUE,
    '#default_value' => t('Email acts as username.Do not forget it!'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Email acts as username. Do not forget it!'}",
    'onfocus' => "if (this.value == 'Email acts as username. Do not forget it!') {this.value = ''}",
    ),
  );

  $form['account details']['password'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 60,
    '#size' => 60,
    '#required' => TRUE,
    '#description' => t('Password should be at least 6 characters long.'),
  );

  $form['home'] = array(
    '#type' => 'fieldset',
    '#title' => 'Home Address',
    '#description' => t('Enter Personal Residential Credentials'),
  );

  $form['home']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
  );

  $form['home']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
  );

  $form['work'] = array(
    '#type' => 'fieldset',
    '#title' => 'Work Address',
    '#description' => t('Enter Official Address'),
  );

  $form['work']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
  );

  $form['work']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
  );

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

  return $form;
}

function registerme_newform_validate(&$form, &$form_state) {
  if ($form_state['values']['account details']['first name'] == 'Be sure of your first name') {
    form_set_error('first name',t('Please enter your first name'));
  }
}

function registerme_newform_submit(&$form, &$form_state) {
  dsm($form_state);
}

```

Is `user_save()` the correct function to save a user object?

# Answer
> 2 votes
The code you should use to create a new user account in the form submission handler is similar to the following one.

```
$account = new stdClass();
$account->is_new = TRUE;

$edit = array(
  'name' => $username,
  'pass' => $form_state['values']['password'],
  'mail' => $form_state['values']['email'],
  'init' => $form_state['values']['email'],
  'status' => 1,
  'access' => REQUEST_TIME,
  'field_fname' => $form_state['values']['first name'],
  'field_lname' => $form_state['values']['last name'],
);

user_save($account, $edit);

```

The form shown in the question does not request a username. Replace `$username` in the code with the correct value.

Setting `$account->is_new` is important, or Drupal will not create a new account.

As side note, a validation handler does not need to check that a required value has been submitted, since that is done from Drupal core.
Instead of using JavaScript code to set the initial value for a field, you should use that value as placeholder: a value that is shown as guideline before users enter a value in the field. That should be done if it does not repeat information already given in the form element description, for example.

```
$form['account details']['email'] = array(
  '#type' => 'textfield',
  '#title' => t('E-Mail'),
  '#required' => TRUE,
  '#default_value' => "",
  '#description' => t('Email acts as username. Do not forget it!')
  '#attributes' => array(
    'placeholder' => t("Your email"),
  ),
);

```

Also, the default value for a form element should be either a value previously entered for the same form, from the same user, or an empty value. It should not be a value like `t('Email acts as username. Do not forget it!')` which then forces you to check if that is the submitted value and return an error from the validation handler. It could also confuse users who can think the form is prefilling the form element for them, while it is giving a description for the form element, which should instead be shown as `#description`.

---
Tags: 7, forms, users
---


# Question
Title: Form API image upload form and File Entity; images not listed in admin/content/file
I used Form API to create an image upload form, where images get uploaded via managed\_file. The upload process works just fine, but the uploaded files don't get listed in the admin/content/file overview that is provided by the File Entity Module. The overview only shows those files that were uploaded via file/add, File Entity's own upload form.

My code is:

```

/**
 * Create an image upload form
 */

function upload_form_image_form($form, &$form_state) {

  // Image file
  $form['image'] = array(
    '#type' => 'managed_file',
    '#name' => 'image',
    '#title' => t('Image file'),
    '#size' => 40,
    '#description' => t("Image should be in JPG format."),
    '#upload_location' => 'public://',
    '#required' => TRUE,
  );

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

  return $form;
}

/**
 * Submit the upload form and scale the image down to standard resolution
 */

function upload_form_image_form_submit($form, &$form_state) {
  if (isset($form_state['values']['image'])) {

    $image = file_load($form_state['values']['image']);

    $loadedimage = image_load($image->uri);
    list($width, $height) = getimagesize($image->uri);
    if ($width/$height >= 1) {
      image_scale($loadedimage, 900, null, $upscale = FALSE);
      }
    else {
      image_scale($loadedimage, null, 900, $upscale = FALSE);
      }

    image_save($loadedimage);
    $loadedimage->status = FILE_STATUS_PERMANENT;

  }
}

```

# Answer
I think your problem is coming from calling `image_save` and not `file_save`. They are non synonymous so far as I can tell.

A `managed_file` is an uploaded file, and usually records an owner of the file with `file_usage_add()`. This is how drupal can manage whether the file is still needed by the system or can be unlinked or deleted when cron is run.

See this other drupal stackexchange answer on how to use the managed\_file FAPI element. It should answer your question on how to get the (original) file saved. You could then create derivatives of the file with image processing as you've already successfully done; after the original file is saved.

I don't believe there is a streamlined solution for this in the file\_entity module or in any image functions (I doubt it, as one thing is to upload and manage the file itself -- and another is to do proccessing on the image itself).
> 1 votes

---
Tags: forms, files
---


# Question
Title: Views-overriden taxonomy/term page returns not found
I am trying to override the default taxonomy/term/xxx page with a page created by views.

My view: I have followed the usual instructions with using url taxonomy/term/%, gave it a contextual filter that is validated to a term name. In the preview results box of this view, I can use a term as an argument, and get the results correctly.

But when use the url in the real site, I get a 404. Regardless what the url alias pattern is for the default taxonomy term pages, when this view is enabled no term will return a page.

Turning my view off-\>term page urls work Turning my view on -\>term pages stop working.

I have no other view with the same URL enabled.

# Answer
> 1 votes
I was able to solve this only by duplicating the "taxonomy" view. This view's argument configuration makes it a viable solution.

After configuring/enabling this view, you can set the taxonomy url aliases to work in the same way.

A working example: http://www.indice.gr/portfolio/all shows "all" projects, wheras http://www.indice.gr/portfolio/mobile-application shows projects under the mobile-application term. Yay!

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


# Question
Title: Can I create a table with hook_schema that has two timestamp fields?
For my module I want to create a table with an updated\_on and created\_on field, both of type timestamp.

I found this can be done with mysql\_type, but you need to specify a default value for that column or it won't work. So I'm using CURRENT\_TIMESTAMP.

However, you cannot use CURRENT\_TIMESTAMP for both columns as explained here and Drupal by default does not seem to accept zero date fields, as discussed here.

Is is somehow possible to create a table using hook\_schema with two timestamp fields without touching Drupal core? I'm using Drupal 7.

I know Drupal uses unix timestamps for dates, but it feels more natural to me to use the MySQL timestamp field and work with that (although Drupal seems to think otherwise)

# Answer
> 0 votes
I searched around and don't think this is currently possible. In the end I reverted to using the unix timestamps that Drupal by default uses anyway. Instead of the current timestamp, I now just add REQUEST TIME to the db statements.

---
Tags: 7, database
---


# Question
Title: Drupal Commerce - add fields to product or product display?
Ive used Ubercart before but im making my first site with Commerce. Im wondering if I should add fields (eg image and description) to my product or product displays?

Im making a site where most of my product displays will relate to one product only.

In some cases however you will have a choice of different weights to purchase. I dont yet know if Ill do this with multiple products and one product display, or if another method would be simpler.

In the future I may want to make multipacks, so combine 10 products into a single purchase and then either give a discount on this pack, or a discount on the total price (which would allow users to substitute the chosen products so long as the total price is the same). Thanks

# Answer
I've been through the same hesitations, and although my site will not have initially any selling activity (I'm using Commerce just as a framework for presenting products, Cart disabled) I decided to build the whole product catalog on the Commerce foundation. Thus, if the decision to open the store comes up some day, it will be relatively easy to open. No revolution or migration would probably be involved.

Thus, before I even get to see the cart, I had to answer lots of abstract question to myself upfront. Basically I worked out two rules of thumb which seemed to guide me through doubts:

1. Adding fields to product or product display? - go the Product way when the field describes a property that could be common for all product displays for that product. Of course, by having fields on product displays you have the power to make the product displays different, but you face the risk of multiplicating need for change, when something needs to be altered.
2. As per what should make a separate product, and what just an attribute - think of a Product as of SKU or a barcode - a unique stock identifier. This has to be unique, this will be bounding all Product displays and orders to a Product. Whatever has to be distinguished, discerned in stock reports or invoices, should be a separate product. So, basically, would you be fine with SKU like TSHIRT, or would you prefer TSHIRT-MENS, or would you need TSHIRT-MENS-XL, or perhaps TSHIRT-MENS-XL-BLUE... It all depends on the particular store and bookkeeping. But the more detailed you go on the Product level, the more data and images you will have to enter into store.

I don't have a case of multipacks and such, but I imagine that you would definitely need a separate product for that, to be able to have a special bundle price for it, and - as I mentioned: - you'd probably want to see on the report: TSHIRT-MENS-5-PK to see whether you do a better business when selling bundles or multipacks.

Well, that's my opinion and I'd be happy to listen to other people's insights. Maybe my philosophy is wrong...
> 1 votes

# Answer
I add all fields that will never change depending on the variations to the product display. For the fields that will change based on variation, those fields go on the product itself.

Example:

A tee-shirt from "Rockstar Threads," a brand, and a tee-shirt from "Basic Clothes," another brand. Each shirt has two colors each, red and black.

The red Rockstar shirt is the same brand as the black Rockstar shirt. The red Basic shirt is the same brand as the black Basic shirt.

So the "brand" field gets attached to the product display. The "color" field gets attached to the product. Now, when I create a new product, for each variation I can add a color, but I only choose a brand once since it's attached to the display. All in all, anything that will remain constant across all variations is attached to the display. Anything that will change, attach to the product.
> 2 votes

# Answer
to my understanding the product display is just that - a presentation of the product. The presentation may be the same for several variations of the product like sizes of a T-shirt design. I would suggest you go with the pictures on the product presentations - not the product themselves. to me it sounds like this is one product display and many products or product variations.
> 0 votes

---
Tags: 7, commerce
---


title: Table form with two checkbox columns

text:
# Question
Title: Table form with two checkbox columns
I know it is fairly easy to create a table form with one column of checkboxes using table\_select. But I would like to have two columns, preferably on the right of the text (as opposed to checkboxes in the left margin with table\_select).

I looked at the code of the permissions table in core, but that one seems closely integrated with theming and I would like to avoid messing with that.

What would be the best way to achieve this? I'm using Drupal 7.

# Answer
This does not seem possible.

However, I found that with tabledrag I could do what I wanted. Instead of having two checkboxes, I used the dragging option instead of one and left the other checkbox in the row you can select by dragging upward. This had the added benefit of being able to specify the order for the items.

The simple table drag example was easy enough to follow and implement.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to create an extra field in the profile module to only accept the numeric values?
I am creating extra fields in the user registration form. for this I am using the profile module.

In this module there is no option form creating a text field which should only accept the numeric values just like in drupal 7.

So how will I create such field in the user registration form?

Any idea?

# Answer
> -1 votes
You can add a custom numeric validation to profile form using form alter. First Add single line text box to profile form then with form alter define custom validation function.

```
function module_name_form_alter(&$form, $form_state, $form_id){
  if ($form_id == 'profile_form_profile') {
      $form['#validate'][]='numeric_validation';
  }
}

function numeric_validation($form_state){
   //the form state variable will contain your text box value,
   //do your custom validation
   //if not numeric add error
      form_set_error("validate",'You must enter numeric value');
}

```

# Answer
> 1 votes
Install CCK module. Enable the **number** module that comes with CCK module. Once you enable the module you can able to add integer field to the Profile Content type if you are using content\_profile module to add fields to registration.

See the screenshow below that i just got to do it using CCK, Number, Content Profile module in Drupal 6.

---
Tags: 6, entities, users
---


# Question
Title: Are there terms to distinguish between the different levels of Drupal Core?
"Core" seems to cover over a multitude of things, encompassing all the modules that ship with the Drupal code base. But there seem to be levels of "core"-ness, and I'm wondering if there is official terminology to distinguish between these. For example:

1. There is the code that is not part of any module. Does "core" include this officially? It's not clear to me.
2. There are required modules: without these (at least in Drupal 7) you can't really build a Drupal site.
3. There are all the default modules that are part of Core. You can turn many of these off without a problem, but they're still considered "core".
4. There are modules that are turned off by default (PHP Filter) and which may even be considered a bad practice to use under normal circumstances (PHP Filter, again).

If I were naming these levels, I might call them

1. The Drupal Kernel
2. Deep Core Modules
3. (Normal) Core Modules ("Core Modules" would include 2 and 4 as well)
4. Outer Core Modules

But it seems like Dries may have an official terminology already. Is there such a thing?

# Answer
I'm not aware of any official definition of the various levels.

I will however, referring to your suggestions, explain a bit about what levels there are.

1. The Drupal Kernel is actually a component in Drupal 8, which is a Symfony Kernel
2. "Deep Core Modules" could be the include files that are not even modules. Some files, for example database.inc, bootstrap.inc and module.inc are so fundamental that core cannot function without them. (There are some more .inc files however that reasonably could become modules, I don't know why they are not)
3. Core modules then, core parts that are written in the same style as contrib modules, but are still so fundamental that core wouldn't work without them. There's a system module that manages a lot of low level administrative functionality. The node module is (in D7) still required. Field sql storage cannot be turned of either.
4. Outer Core Modules, are all the other things that are shipped with core because they are commonly used, but not necessary for Drupal to function. The forum, taxonomy terms, the user interface for the field system etc.

Again, I'm not familiar with any official terminology, other than all of it being "Core". When people work on core, I only hear references to the individual "components" of core, as specific in the Drupal issue queue.

When I hear "actual core", I think of levels 1 - 3.
> 3 votes

# Answer
If you can't turn the module off, it's Actual Core. If you can, it's Extended Core.
> -1 votes

---
Tags: 7
---


# Question
Title: How to add another color to theme color pallette?
I have custom theme which is using Color Pallette from Bartik. I want to add another color options:

```
 'fields' => array(
    'top-bar-' => t('Top Bar background'),
    'top' => t('Header top'),
    'bottom' => t('Header bottom'),
    'base' => t('Main background'),
    'sidebar' => t('Sidebar background'),
    'sidebarborders' => t('Sidebar borders'),
    'footer' => t('Footer background'),
    'titleslogan' => t('Title and slogan'),
    'text' => t('Text color'),
    'link' => t('Link color'),
  ),

```

`top-bar-` is id of top container (someone named it `top-bar-`, anyway it's best to remains the same)

In `schemes` array I added default color to every schema, e.g.:

```
    'top-bar-' => '#666666',

```

Now in colors.css I added:

```
#top-bar- {
    background-color: #666666;
}

```

I cleared cache but my new color pallette options doesn't appear in theme settings form :( I read a few tutorials about this topic, but in my case it just don't work.

# Answer
It's starts working when I changed color.module in line 234 (added TRUE param):

```
$palette = color_get_palette($theme, TRUE);

```

Caution: This removes any custom colour palette so you might want to note the colour settings somewhere

**EDIT**

Now I have removed TRUE param from code, my new field still appears and everything is working correctly.

Anyway at last problem is trivial to solve, just disable and enable theme again, but it remove blocks settings etc on this theme.
> 2 votes

---
Tags: 7
---


# Question
Title: Is there a product.tpl.php for ALL product types in Drupal Commerce?
Or do you need product-type1.tpl.php, product-type2.tpl.php, etc? I would like to theme every single product on the site but there are multiple product types.

# Answer
> 2 votes
You could do the following in your theme processing...

```
function YOURTHEME_process_node(&$vars) {

    //dsm($vars);
    //dsm($vars['theme_hook_suggestions']);

    // If some node type then...
    if ($vars['node']->type) {
                // add a template suggestion
        $vars['theme_hook_suggestions'][] = 'node__product';

    }

}

```

Then you add a template file 'node--product.tpl.php'.

---
Tags: theming, commerce
---


# Question
Title: How to Save a Node Object reached from another Server?
I'm implementing the Node Object passing one Site to another. I am now able to send the `$node` object across the sites. But the problem now again is i can NOT do `node_save($node)` simply.

* I can NOT get the object as Drupal valid $node

# Answer
Are you working on a multilingual site? Trying to save a node that have different language than expected, for example "it" instead of "und" fails, event if the node is cloned from another site in which is working well.

You could also try to unset($node-\>nid) unset($node-\>vid)

they are not required in order to create a new node.
> 0 votes

---
Tags: nodes
---


# Question
Title: Add extra html to ubercart cart and checkout pages
I need to wrap ubercart cart, cart/checkout and other front-end pages in extra html, but cannot find a way to do it (some template files or way to add my extra html).

For example, mydomain/cart ubercart content is inside

```
<div id="cart-form-pane"></div>

```

, and i need to add more html before and after that div.

I could watch for ubercart in page.tpl.php with current\_path(); and on occurance add that extra html, but would like to know is there any more propper way.

Update: it is Drupal 7 with Ubercart 3

# Answer
You can achieve this in following ways, 1) define a template file:- in your template.php, define a template file for checkout page

```
/**
* Implements hook_theme().
*/
function themename_theme($existing, $type, $theme, $path) {
  $items = array();

  $items['uc_cart_checkout_form'] = array(
  'render element' => 'form',
'template' => 'uc-cart-checkout-form',
  'path' => $path . '/templates/',//where the tpl files are located
   );

   return $items;
 }

```

Then in your templates folder create a file uc-cart-checkout-form.tpl.php, here you can render your form with additional htmls

2) Override the theme

Check this instruction on Ubercart How to Theme the Checkout pane in Ubercart 3, by following this you can include your custom html.

Similarly the above methods are applicable to cart page also
> 2 votes

---
Tags: theming, ubercart
---


# Question
Title: How to display forum on a custom URL on my site?
The default URL of forum is `./forum` but I want it to move to `./discuss/forum` How can i accomplish same?

# Answer
> 1 votes
You can use pathauto, url alias to your forums to achieve the same. if it is a custom menu you can use hook\_menu\_alter(). or an .htaccess re-direct if it is a permanent change

---
Tags: 7, nodes
---


# Question
Title: Adding different classes to menu item list
I'm trying to override the way that menu items are displayed. I have the following function :

```
 function newtheme_item_list($items = array(),$title=NULL,$type='ul',$attributes=NULL)
 {
 $positions = array("","second","third","forth");
if (!empty($items)) {
$output .= "<$type" . drupal_attributes($attributes) . '>';
foreach ($items as $item_key=>$item) {
  $attributes = array();
  $children = array();
  if (is_array($item)) {
    foreach ($item as $key => $value) {
      if ($key == 'data') {
        $data = $value;
      }
      elseif ($key == 'children') {
        $children = $value;
      }
      else {
        $attributes[$key] = $value;
      }
    }
  }
  else {
    $data = $item;
  }

  if (count($children) > 0) {
    $data .= theme_item_list($children, NULL, $type, $attributes); // Render nested list
  }
  if ($item_key > 0)
  {
    $attributes['class'] = ' nav_separator '.$positions[$item_key].'-nav';
  }
  if($item_key == 0) {
    $attributes['class'] = 'first-nav';
  }
  elseif($item_key == count($items)-1){

    $attributes['class'] = ' last-nav';
  }

  $output .= '<li' . drupal_attributes($attributes) . '>'. $data .'</li>';
}
$output .= "</$type>";
}
$output .= '</div>';
return $output;

}

```

In the page.inc.php i have the line:

```
print theme('links', array('links' => menu_navigation_links('main-menu'),'attributes' => array('class'=> array('links', 'site-menu'))));

```

This it should add some different classes to my menu but instead i get this error:

```
Recoverable fatal error: Argument 1 passed to drupal_attributes() must be an array, null given, called in D:\EasyPHP-5.3.5.0\www\drupal\themes\newtheme\template.php on line 12 and defined in drupal_attributes() (line 2301 of D:\EasyPHP-5.3.5.0\www\drupal\includes\common.inc).

```

# Answer
> 2 votes
Your function signature is off, it should be like this:

```
function newtheme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];
  ..
}

```

You should check the docs, when creating theme functions.

---
Tags: 7, routes
---


title: Make content be aware of the section

text:
# Question
Title: Make content be aware of the section
I have a site divided by in multiple section which are actually some taxonomy views (taxonomy/term/term\_ID).

It works like this:

* I have some specific blocks for each section.
* Content can be found in multiple sections

The problem is that (because the node is part of multiple section) I don't know how to display the same blocks on the node page as the ones in the section the user just left.

Any ideas? Thanks

# Answer
> 0 votes
I ended up using contextpphp module and adding a SESSSION variable as a reaction to each section. Then checked this variable as a condition for another context.

# Answer
> 0 votes
You can use context module and create two different contexts by adding conditions as path.

Enable the reactions as blocks and add same blocks in different sections using two context that you created !

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.

Hope it solves the problem :-)

---
Tags: 7
---


# Question
Title: Why default template suggestion use double dash instead of single dash?
```
block--module--delta.tpl.php
page--front.tpl.php

```

As above example, what is the reason behind double dash? Why not use single dash like `page-front.tpl.php`?

# Answer
> 2 votes
I do believe it's just to add separation on the off-chance that the region/content type/page name has a dash in it, itself. `block--my-impressive-module--delta.tpl.php` is a lot easier to see that the intended target is `block` named `my-impressive-module`, than if it were `block-my-impressive-module-delta.tpl.php` (now there's no separation between the three name sections). It's possible for a region/content type/page name to have a dash, but none will have two dashes, so it's a reasonable substitution.

# Answer
> 0 votes
Drupal uses this convention to determine what file to use. If the name contains a double-underscore ('\__') and there isn't an implementation for the full name, the part before the '\__' is checked. This allows a fallback to a more generic implementation.

Drupal converts double unscores to dashes, for example when a template suggestion is created in code you would do the following:

```
$vars['theme_hook_suggestions'][] = 'page__something';

```

The template for this is...

```
page--something.tpl.php

```

If 'page--something' can't be found it will default to...

```
page.tpl.php

```

If your page was 'products page' for example your template would be...

```
page--products-page.tpl.php

```

The single dash acts a space.

---
Tags: 7, theming
---


title: How to have a three column in node page

text:
# Question
Title: How to have a three column in node page
I want to have a three column in node page, my page width is 940px, and one column is 300px + 20px right margin, so 3 column is 960px, but the main width is 940px, I want to 3 column in one row, how to do that? how to modify node.tpl.php?

# Answer
I don't understand why this isn't a simple case of changing your CSS? You're adding 20px to 940px so that equals 960px. You must either use CSS3 (box-sizing: border-box;) or minus your extra 20px from 940px...which would be 920px. Standard box model stuff but maybe I'm missing something in your requirements.
> 2 votes

# Answer
You can use modules like panels and theme like Omega without writing code or messing your node.tpl.php.

Omega theme provides so much flexibility to have a responsive design as well. It can support various types like three column, two column and 960GS.

Panels in combination with omega and also as a standalone can support your requirements.

**UPDATE:**

1. http://drupal.org/project/ninesixty will help you in your case
> 1 votes

# Answer
Try using Display suite module, install the module then go the manage display of you content type and at the bottom of the page you should change the layout for you content type.

after that put your fields in the correct places.

with some CSS work you will get what you want
> 1 votes

# Answer
So, you need 940px width on some pages and 960px on others? That's not the greatest design choice (ideally, refactor your 960 width pages to fit in 940 like the rest, or just make all of them 960), but you can do that with a class in your custom templates.

In page.tpl.php, find your main "wrapper" div (the one that's stuck at 940px). Then in CSS do:

```
div#wrapper { width:940px; } /* Normal width */
body.three-col div#wrapper { width:960px; } /* three-column layout */

```

Now in your custom `node--whatever.tpl.php`, add an additional class to the `<body>` tag (`three-col`), and the content area will give you your extra 20 pixels.
> 1 votes

# Answer
You could change/overwrite the right margin to 13 pixels, for example.
> -3 votes

---
Tags: nodes
---


# Question
Title: Change date format for the example dates given below date field
I'm using Drupal 7, with the latest date module release. I've added a date field to an event node type I created. However, when I go to create a new event, the example date given (the date format description) underneath the date field uses the American date format of m/d/y. I want to change it so that the example date uses the English date format of d/m/y. Can someone tell me how to do this. I did change all the date formats in the date format section to UK date formats, but this hasn't made any difference. I also changed the timezone to Europe, also with no effect.

I'm sure there is something simple I'm missing?

# Answer
> 5 votes
You can change the format in field settings. Follow below steps to change.

* Go to admin/structure/types
* Click on manage fields next to your content type
* Click on edit link next to the field

---
Tags: 7, datetime
---


# Question
Title: How do I insert a <span> </span> tag outside the <a> </a> tag on my main menu
I have been scouring the web trying to find a way to get a tag just AFTER each of my main menu items. Looking at this solution I am able to get a tag in there, but it's INSIDE the link. I just don't want it to be a link.

I'm pulling my hair out trying to figure this out. I just don't know enough PHP to place it outside the link. This is what I have so far in my template.php:

```
function motg_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}

if ($element['#original_link']['menu_name'] == "main-menu"){

$element['#title'] .= '<span class="description">'.$element['#localized_options']['attributes']['title'].'</span>';
}

$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

Any help would be great!

# Answer
> 0 votes
If you want your menu link to be like this `<li><a>Link 1</a><span>Description</span></li>`, ie., the description is outside the `<a>` tags, then try the code below.

```
function motg_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $description = '<span class="description">' . $element['#localized_options']['attributes']['title'] . '</span>';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . $description."</li>\n";
}

```

The reason your code didn't work was, you used the description tag within the `l()` function. In drupal the `l()` function always renders an `<a>` tag and so the description was inside the `<a>` tag.

---
Tags: routes
---


# Question
Title: Best practices to hide elements on a page
So at the moment I can use:

* CSS using display: none
* function hide(attribute) using hook\_preprocess\_page()
* remove title code from page.tpl.php

And I'm sure there are much more! I'm kinda new to drupal so wondering what you guys think is better practice. Ie...

If I want to hide the page title I would use... If I want to hide the timezone configuration block on user profile I would use...

Thanks!

# Answer
As Alex Gill mentioned in the comments this is an open ended question.

My guidelines though are as follows:

* never hide something via CSS if you can hide it via application code, especially if you don't really want it inside the HTML. Hiding stuff with CSS is only acceptable if you want to have them "preloaded" in order to display them later on using javascript
* hiding something via module (e.g code from your features module, if you have one) is good since it can work with any template

In regards to hiding form elements please note that:

* hiding stuff with CSS still makes it possible for "smart" users to alter the hidden defaults, possibly via Firebug etc. So you *should not* assume that users will not be able to alter form elements that they cannot see.
* removing form elements via code may have side effects down the line in case you've removed stuff that is expected in validate functions. E.g if you've removed a mandatory form element then it'll never get submitted.
> 3 votes

---
Tags: theming
---


# Question
Title: how to implement a data receiver service in Drupal
I have a Drupal site which will host a flash application. The application will be inserted in a node body (or as an attachment, not sure yet). I would like this application to send some data to Drupal (e.g. a game progress and score) using Javascript.

What I achieved so far is the ability to have the game score displayed in a Javascript alert window in Json format. Next step would be to send it to Drupal and I want to save it to a table. I don't know how to do the "**Send it to Drupal**" part. What is the right way to do it, so it's hacker-proof etc?

# Answer
If you do it the JS part, Drupal part will be quite easy.

Create module with form that handle data transfer to Drupal and submit this form via Ajax https://drupal.org/node/752056

It can be helpful too: Match JSON POST data with custom node fields
> 0 votes

---
Tags: 7, ajax, javascript
---


# Question
Title: Only one module implements hook_tokens()?
I've declared a `[module-name]_tokens()` hook but when I output the contents of `module_implements('tokens')`, only my module appears in the list. I know that there are many more modules that implement `hook_menu()`; why do I get only my module listed? Where shall I look for possible errors?

# Answer
```
$hooks = module_implements('tokens');
print_r($hooks);

```

It returns the follwoing

> Array ( \[0\] =\> token \[1\] =\> date \[2\] =\> domain \[3\] =\> entity\_token \[4\] =\> facetapi \[5\] =\> logintoboggan \[6\] =\> name \[7\] =\> node \[8\] =\> scheduler \[9\] =\> system \[10\] =\> taxonomy \[11\] =\> token\_custom \[12\] =\> user \[13\] =\> views \[14\] =\> field \[15\] =\> menu )

The only place which i see is it is cached, try clearing the cache or try the following

```
 module_implements('tokens', FALSE, TRUE)

```

The third params is reset to reset the cache.
> 0 votes

---
Tags: hooks, tokens
---


title: UC Feeds - updating products by SKU

text:
# Question
Title: UC Feeds - updating products by SKU
The main idea is updating prices via feeds. If SKUs are unique, we can update products using this parameter.

Unfortunaly module UC Feeds is able to create only new producs. How to modify UC Feeds for updating products ability?

# Answer
> 1 votes
How about following these steps?

* Save the original import file
* Update the original file
* Delete the last import
* Import again

---
Tags: 7, ubercart, feeds
---


# Question
Title: How can I specify language for Parent Item options on node create/update page?
The site in question is running **Drupal 7** and has a sub-folder structure for the languages. E.g. http://site.tld/ for default language and http://site.tld/en/ for english.

The editors can choose if they want their admin interface in either language by logging in on the user page for any available language.

My problem now is that on the node create/update page, Drupal seems to use the global `$language` to determine what options to retrieve for the *Parent item* under *Menu settings*, rather then using the current node's language.

So if an editor is editing a node in the default language but on the english interface, only english menu items will be in the select list mentioned above. When saving the node, the Parent item will be reset to the base of the menu and the previous menu structure will be lost.

What I want is a way of altering the chosen language for when that option list is being built. I suppose one way would be to use `hook_form_alter` and rebuild the options for that field, but that doesn't feel like the right way of doing it.

Is there another way of solving this issue?

**UPDATED**

It doesn't necessarily need to work perfectly. I guess one way would be to have one language neutral menu and then localize the menu items instead. That would bloat the main menu though, especially when there are multiple languages.

Yet another *hack* would be to do as @reptilex suggested in his answer and then overwrite the admin translations with one language. I'd prefer not to though.

# Answer
> 0 votes
I have a similar problem, I have decided that I don't want to ajax reload the form when the language is changed because things like entity relationships (which is my current problem) don't work even then.

My advice is to force the language of the editing / adding node to be the same as the interface. For creating/ adding this is easy you set it for the content type when you edit the multilingual settings. The translation interface redirects correclty and the content creation too (it expects you to be in the language you want to create).

So with that option you would be on the safe side, EXCEPT when you are in pages like "find content" and use the edit link or write the url by hand. What I am trying to do now is to force a redirect when you try to edit the link by a url like /node/223/edit. This is something that should be possible with hook\_menu\_alter.I would force a redirect to \[language of the content\]/node/223/edit.

I would have thought that there was a better possibility but I have found none. I will be monitoring this question to see if someone has a better idea or there is a much better solution out there.

---
Tags: nodes, forms, routes, i18n-l10n
---


# Question
Title: Difference between "site:current-user:field-foo" and "account:field-foo" in setting a Rules condition?
What is the difference between "site:current-user:field-foo" and "account:field-foo" in the Rules "Add a new condition"?

# Answer
As I mentioned in the comments the variables you have available to you in a rule depend on the context it's in.

`[site:current-user]` is a global token available to any rule and will always return an object relating to the currently logged in user.

The `[account]` token is there because you're responding to the "After saving a new user account" event; that event passes an object relating to the user object that has just been saved (for obvious reasons).

I guess the main distinction is that the former will always give the currently logged in user, while the latter could be a different user object altogether (if, for example, an administrator had created the account).
> 2 votes

# Answer
In the "After saving a new user account" event, \[account:field-foo\] is referring to the account being saved, while \[site:current-user:field-foo\] is referring to the currently logged-in user, which possibly is the user who created the new account, or caused the account to be automatically created.

In the case of an administrator creating an account for another user, \[site:current-user:field-foo\] would be for the administrator account.
> 1 votes

---
Tags: rules, tokens
---


# Question
Title: How can I use REST API to create a node with status/tags/data
Follow the Services module document, I can only create nodes using *REST API* with *type, title* and *body*. But I am not able to create nodes with more parameters such as *tags, status* and *date*.

Need help.

# Answer
You should have look at drupal docs but for understanding that first install Devel module - it really helps you to discover field names.
> 1 votes

---
Tags: services, 8
---


# Question
Title: Why can't I find my uploaded file on disk?
I have a form with a file upload widget:

```
$form['myFile'] = array(
    '#tree' => false,
    '#type' => 'file',
    '#title' => t('Choose a file')
);

```

In the form validation handler, I upload the file and validate it with:

```
$validators = array(
    "file_validate_extensions" => array(variable_get("allowed_extensions")),
    "file_validate_size" => array(variable_get("max_image_size"))
);
$file = file_save_upload('myFile', $validators);
$form_state['file_storage']['myFile'] = $file;

```

Then, in the submit handler, I save the file using:

```
$file = $form_state['file_storage']['myFile'];
file_save($file);

```

This seems to work fine as I can find an entry for the file in the `file_managed` table:

```
+-----+-----+--------------+-----------------------------+------------+----------+--------+------------+
| fid | uid | filename     | uri                         | filemime   | filesize | status | timestamp  |
+-----+-----+--------------+-----------------------------+------------+----------+--------+------------+
|  49 |   1 | download.jpg | temporary://download.jpg    | image/jpeg |     5410 |      0 | 1350312114 |
+-----+-----+--------------+-----------------------------+------------+----------+--------+------------+

```

The problem is that I can't find the file anywhere on disk:

```
$ su -
Password:
# updatedb
# locate download.jpg
/home/me/Pictures/download.jpg

```

As you can see, the only `download.jpg` found is the one in my pictures folder which I passed into the form. I can't find anything *on the server* (in `/var/www/`). So where is the file? Is it a BLOB in the drupal database? Has it simply not been uploaded properly? If so, what did I do wrong?

# Answer
You're just missing the third parameter for `file_save_upload()`:

> $destination: A string containing the URI $source should be copied to. This must be a stream wrapper URI. If this value is omitted, Drupal's temporary files scheme will be used ("temporary://").

The uri in your table is `temporary://download.jpg` which seems to support that.

To save your file in the public file system you just need to pass that parameter in:

```
$destination = 'public://some/folder/';
$file = file_save_upload('myFile', $validators, $destination);

```
> 5 votes

---
Tags: 7, files
---


# Question
Title: How to theme specific taxonomy term page?
> **Possible Duplicate:**
> Theme specific taxonomy page

I have a taxonomy term page that shows all the related terms with their details ... i just need to show the list of the terms as links to node page. Which is the best way to do it?

EDIT: i tried to create taxonomy-term--VOCAB.tpl.php file, it is read but $content variable is empty .... so i don't understand how Drupal handles it.

# Answer
> 0 votes
The best way is to show it by Views module. You blocked default viewing of taxonomy and change it to Views. Video include.

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


# Question
Title: Move File Field storage from public:// to another stream wrapper (like s3://)
I've been looking around for this a bit, and it seems like it would be relatively easy in Drupal 7, since D7 supports stream wrappers, and Fields are part of core... but I can't find any documentation.

I have a file field with a few thousand files attached to nodes, and it's using public:// right now.

I also have the AmazonS3 module installed, and some other file fields are already set to use the s3:// stream wrapper.

I now want to migrate the file field using `public://` to `s3://`, and I want all the files already uploaded to the site's files folder to switch to s3. I can manually copy over the files to a bucket on S3, but what exactly would I need to do in Drupal/the database to get the files to be loaded over s3 instead of public?

I thought about just writing a custom query to update all rows in the `file_managed` table with `public://custom/path` to change to `s3://custom/path`, but (a) there are some older files that were migrated with different paths than `custom/path`, and (b) I'm not sure if this is the right way to get Drupal to use S3.

\[**Edit**: Just noticed the file\_move() function in the API—would I be able to move files using this (after switching the field storage in the Field UI) instead of having to manually copy files and update the database?\].

# Answer
For the paths that match across the two servers you can just change the paths in `file_managed` to start with `s3://`, clear the caches, and the S3 module will handle the rest.

This module should be really helpful, I've just written a module for someone which is pretty similar to what you're trying to do (except the files are pruned from the local file system to S3 on a cron) and the module in that link was a great starting point.

Since the S3 module implements a fully functional stream wrapper you can use all of the usual file functions (`file_copy`, `file_move`, `file_delete`, etc) as normal, without having to worry about where the files are.
> 2 votes

---
Tags: files, stream-wrappers
---


title: draggableview on grouped taxonomy tag

text:
# Question
Title: draggableview on grouped taxonomy tag
I have a content type with a taxonomy tag and some fields.

i use these content type in a view which groups the nodes by its tag and print out some fields.

now i want these tags in a specific order, which should be easily changed, e.g. by draggableviews and i also need the content under these tags in a specific order. so i need a draggableview inside a draggableview... (yo dawg) somehow...

is it somehow even possible to sort these tags and then sort the content in the tags?

# Answer
> 0 votes
Okay, found out it works when just applying one draggable view and sort a list of all nodes. if the taxonomy tags are allready in the right order and are under another, the grouping will be sorted by the order of the nodes...

this is sufficient for me, but maybe someone has a better solution?

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


title: Commerce South African Payment method

text:
# Question
Title: Commerce South African Payment method
I’m busy with a Drupal 7 Commerce site, and I need a correct and working payment method to handle the payments in ZAR (South African Rand) and not in any other currency.

# Answer
This answer probably is too late, but for the sake of other South African users coming across this question: I have a sandbox module for using Paygate as your payment gateway. It is developed for Drupal 7 Commerce and it's currently live on a few websites I've worked on.

You can get the module here, but you'll need to know how to use git to download it.
> 3 votes

---
Tags: 7, commerce
---


title: downgrade drupal 7 to drupal 6

text:
# Question
Title: downgrade drupal 7 to drupal 6
I need to downgrade Drupal 7 installation to Drupal 6, how should I handle it? I have pretty much blank Drupal 7 install (w/ bunch of users, which I really don't want to loose), but the module that I need only works on Drupal 6.

*** UPDATE ***

following is a module that I'd like to use w/ Drupal: Clickbank IPN | drupal.org and as you see developer(s) don't have anything other then d6 release.

Is there a way to export users from D7 and import then to D6?

# Answer
You wont be able to find any easy solution to downgrade from 7 to 6. The best option is to either find an alternative to the module that is not available for D7 or check the issue queue of that module you might find the dev release of the module. OR If only users are important to you then just export the users from D7 and import them on D6.
> 2 votes

# Answer
Downgrading from Drupal 7 to Drupal 6 involves a lot of manual work. For example, the password hashing algorithm in Drupal 7 is not compatible with the one in Drupal 6.

I strongly advice against it and instead look for some other way to implement the functionality you are missing.
> 1 votes

---
Tags: 7
---


# Question
Title: PHP filter field behavior with Rules - can't use curl_exec
I am on Drupal 7. I am trying to use Rules to execute custom PHP code. I am using PHP filter in order to achieve that. Inside that PHP filter I will use curl. The idea is to communicate with a remote API.

I already have one Drupal website running this code I want to use and it works like a charm. On this website I am using Rules, PHP filter and curl.

The issue is that I am porting the EXACT same code to a new website using the same set of tools (Rules, PHP filter, curl), but I can't save my code into PHP filter.

The field will allow me to save this

```
$data = array(
'User'          => 'someuser',
'Password'      => 'somepassword',
'Subject'       => 'Something',
'Message'       => 'Something',
'StampToSend'   => $account->created,
'MessageTypeID' => 1
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://someurl.com");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

```

When I add the last line "$response = curl\_exec($curl);", then Drupal won't save my Rule. No error messages, no messages in the Drupal logs, no anything. It will just fail to save the field. I can save all the code above, and Rules with PHP filter will accept it. When adding the curl\_execute line, it simply won't save.

Any ideas on what I could do? Thank you!

# Answer
I solved the issue by moving the code to a custom module, then everything worked. My best guess is that the PHP filter is somehow interpreting the code and filteirng out stuff it considers innapropriate.
> 0 votes

---
Tags: rules
---


# Question
Title: Allowing a user to control and/or view their own revisions
Is there a way to allow a user to view and/or edit only their own revisions? I don't want another user to be able to view other people's revisions. Is there a module for this?

# Answer
> 1 votes
The revisioning module gives you this ability:

> Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions.

---
Tags: 7, nodes
---


# Question
Title: How to terminate a batch when an error occurs
I've read this: http://api.drupal.org/api/drupal/includes%21form.inc/function/batch\_set/6 and through the source code, but I cannot see how a batch operation can flag that an error has occurred to show the error message.

I can set `$context['finished'] = 1.0;` to end the batch, but I cannot see how to set `$current_set['success']` to FALSE to abort the batch and show the error message to the user.

How is this done? Is there a good example somewhere?

# Answer
> 3 votes
To set `$current_set['success']` to `FALSE`, you can use the following code.

```
$current_set = &_batch_current_set();
$current_set['success'] = FALSE;

```

To set the messages to show to the users, you can use the following code.

```
$batch_context['results'][] = 'The error to be shown to the user';
$batch_context['finished'] = 1.0;

```

`$batch_context` is the last argument passed to the operation callback.

The "finished" callback receives `$current_set['success']`, and `$batch_context['results']` respectively as first, and second argument. It can show the errors to the users using `drupal_set_message()`.

### References

---
Tags: batch-operations
---


title: Theme Entity Reference output

text:
# Question
Title: Theme Entity Reference output
I have a content type called SimpleNewsletter which has an Entity Reference field called `field_newsletter_content`. Multiple articles are linked with one SimpleNewsletter node. Under Manage Display of SimpleNewsletter, I can manage which fields to display.

But I have a situation where I only need to display certain fields not all the fields (ex: "Node Title")

In order to theme `field_newsletter_content` field I have created a new file called `field--field_newsletter_content.tpl.php`

Is it possible only to display certain fields?

# Answer
> 3 votes
Maybe you could use the teaser for displaying your entityreference nodes. Under Manage display under format for the entity reference field, choose Rendered entity, choose settings and use teaser instead of full mode.

Go the the display settings for the content type that is being referenced and apply your display settings for the teaser display.

# Answer
> 1 votes
In Drupal 7 custom add a new display mode like 'Teaser' or 'Full content with hook\_entity\_info\_alter()

Add a view mode

```
  /*
    * Implements hook_entity_info_alter().
    */
    function MYMODULE_entity_info_alter(&$entity_info) {
      $entity_info['node']['view modes']['NEW_DISPLAY_TYPE'] = array(
        'label' => t('Title only'),
        'custom settings' => TRUE,
      );
    }

```

Go on
Structure -\> Content type -\> Article -\> Manage display -\> Title only
and set to visible only the title.

Go on
Structure -\> Content type -\> SimpleNewsletter -\> Manage display
and, in the field\_newsletter\_content row, select 'Rendered Entity' as Format

Go the the gear on the right and select 'Title only'

Now in your Newsletter node you will have displayed only the title of the connected article

# Answer
> 0 votes
On Manage Display you can on Format select \<hidden\>.

# Answer
> 0 votes
Have you considered using the module display suite to have more control of your display. Also with display suite you can have more control of your view modes and layout, if you active field templates that it comes in the display suite extras (not activate it by default) you can even have more control of your css and output. There are some videos that are good...display suite video. they explain better the power of this module. It is totally worth the time invested in learning this tool.

For your case I think it would really help to use view modes to control the way to render your entityviews modes. I hope it helps

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


# Question
Title: Get the t function to work in a custom php file
I am having a custom hand coded PHP page within a Drupal module that loads in a fancybox. I want the Drupal t() function to work in it. What should I include in the file to make it function?

# Answer
> 2 votes
Include these lines in your php file

```
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

# Answer
> 0 votes
By default the t() function is accessible from any custom module.

You shouldn't have to include any other files/code.

---
Tags: 7, i18n-l10n
---


title: Safely delete book and its child pages

text:
# Question
Title: Safely delete book and its child pages
I have a site with two books, each having about 300-350 pages each. I want to delete one of the book and its child pages.
I was able to load the pages using some custom coding. I also came across, `node_delete()` function which has the following code snippet:

```
db_delete('node')
  ->condition('nid', $nids, 'IN')
  ->execute();
db_delete('node_revision')
  ->condition('nid', $nids, 'IN')
  ->execute();
db_delete('history')
  ->condition('nid', $nids, 'IN')
  ->execute();
db_delete('node_access')
  ->condition('nid', $nids, 'IN')
  ->execute();

```

So, it deletes data from four tables; but I suspect there are other tables, from which the data needs to be deleted as well (one of them being `book` table). Could you please point out which of the tables needs to be checked?

# Answer
> 0 votes
book\_delete module will address your issue !

> Book Delete adds the ability to delete entire books to the book administration page (admin/content/book). It uses a batch operation to allow deletion of large books.

Take a backup of database before doing any delete actions :-)

It just worked as expected !! Follow below steps.

* Install module
* Clear Drupal Cache
* Go to admin/content/book
* Select the book you want to delete and click on delete book link next to it.
* Confirm delete !

That's it :-)

---
Tags: 7, nodes
---


# Question
Title: CCK Images broken (because of path) on multisite after copying/moving site
I've just encountered an issue I haven't seen seen before: after copying the dB/files to a new location on the server, none of the CCK images are working, regardless of if ImageCache is used or not. In other words, even when editing a node, the image preview is missing because the path is obviously wrong.

For one example, the path should be /sites/dev-\[site-name\]/files/homebanners/\[image-name\].

Instead it is /sites/dev-\[site-name\]/files/sites/\[original-site\]/files/homebanners/\[image-name\].

What I can't figure out is why.

Here's the steps taken:

1. Copy the dB
2. Copy the files. I forget why but the new sites/\[site-name\] mapping changes to sites/dev-\[site-name\] for the dev site (where the images are broken).
3. Adjusted .htaccess RewriteBase & Rewrite Rules, and the base\_url for each settings.php file
4. Set the new files location at admin/settings/file-system
5. Cleared the cache For the imagecache files, and used Drush to flush and re-build the images

For all but one site, the files use the Public setting, but the problem persists regardless of if the files are set to public or private.

Any help would be most appreciated.

# Answer
Changing site URL with a multi-site setup in Drupal 6 is problematic as the paths in the file table will be incorrect. (See Migration failed)

In Drupal 7, you set up multi-site aliasing via the `sites.php` file (copy and edit the existing `examples.sites.php`), which should be stored in the `/sites` directory.

For Drupal 6 you can try applying the multi-site aliasing patch.

As a last ditch effort (not best practice) you can also try editing the database (e.g. system and files tables) to change the file paths to reflect the new path.
> 0 votes

---
Tags: media
---


# Question
Title: Keep line breaks when printing custom plain text textarea field
I'm using Drupal 7. I'm printing out a custom plain text textarea field in the node template using the following code:

```
print ($taxonomy_term->field_address['und'][0]['value']);

```

However, when I print it out I lose all the line breaks. Is there a way I can keep the line breaks in when I print out the field value?

I have already changed the plain text format to add "limit allowed HTML tags" rule for `<a> <br> <p>`, and removed the "display any HTML as plain text" rule.

Many thanks,

Ben

# Answer
I worked it out. I just needed to use the following code:

```
print nl2br($taxonomy_term->field_address['und'][0]['value']);

```

This uses the print nl2br function to convert line breaks to `<br>` tags.
> 4 votes

---
Tags: 7
---


title: Feed importer View

text:
# Question
Title: Feed importer View
I have created a Feed Importer with CSV as Parser and Proccesor as Self Node processor which is attached to a content type. The feed works fine when importing to the content type, however I would like to create a Table View that displays the imported feed. Can someone help me. Thanks.

# Answer
I figured it out how in views but how would I make it so the view table include all of my feed importers, for example csv, xml, etc.
> 1 votes

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