# Question
Title: Custom module field displays twice when adding content
I've created a module consisting of 5 fields. I've set the number of values unlimited, and when I do, 2 of the custom fields are displayed (see image). How can I get a default of 1 custom field type to display?

This is the .module:

```
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

include 'cloudinary/src/Cloudinary.php';
include 'cloudinary/src/Uploader.php';
include 'cloudinary/src/Api.php';

$cloud_name = variable_get('cloudinary_cloud_name');
$api_key = variable_get('cloudinary_api_key');
$api_secret = variable_get('cloudinary_api_secret');
$api_url = variable_get('cloudinary_editor_url');

function cloudinary_menu() {
    $items['admin/config/cloudinary'] = array(
        'title' => 'Cloudinary',
        'description' => 'Interact with cloudinary.',
        'position' => 'right',
        'weight' => -5,
        'page callback' => 'system_admin_menu_block_page',
        'access arguments' => array('administer site configuration'),
        'file' => 'system.admin.inc',
        'file path' => drupal_get_path('module', 'system'),
    );
    $items['admin/config/cloudinary/settings'] = array(
        'title' => 'Cloudinary settings',
        'description' => 'Configure cloudinary.',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('cloudinary_admin_settings'),
        'access arguments' => array('administer site configuration'),
        'type' => MENU_NORMAL_ITEM,
        'file' => 'cloudinary.admin.inc',
    );
    return $items;
}

/**
 * Implements hook_field_info().
 * define the field type
 */
function cloudinary_field_info() {
    return array(
        'cloudinary' => array(
            'label' => t('Cloudinary image selector'),
            'description' => t('Search for images and select one for display.'),
            'default_widget' => 'cloudinary_widget',
            'default_formatter' => 'cloudinary_formatter',
            'settings' => array(),
            'instance_settings' => array(),
        )
    );
}
/**
* This is the "Field type" dropdown
*/
function cloudinary_field_widget_info() {
    return array(
        'cloudinary_widget' => array(
            'label' => t('Default'),
            'field types' => array('cloudinary'),
        )
    );
}

/**
*/
function cloudinary_field_widget_form(&$form, &$form_state, $field, $instance, $lang, $items, $delta, $element) {

    //TODO: this is temporary! Need to figure out how to pull it in properly
    //this sets the finder url to the service i.e. localhost or whatever
    drupal_add_js(array('cloudinary' => array('finderUrl' => variable_get('cloudinary_editor_url'))), 'setting');
    drupal_add_js(drupal_get_path('module', 'cloudinary') . '/assets/js/cloudinary.js');
    drupal_add_css(drupal_get_path('module', 'cloudinary') . '/assets/css/cloudinary.css');

    $item =& $items[$delta];

    $element['publicID'] = array(
        '#title' => t('Public ID'),
        '#type' => 'textfield',
        '#required' => FALSE,
        '#default_value' => isset($item['publicID']) ? $item['publicID'] : '',
    );

    $element['url'] = array(
        '#title' => t('Url'),
        '#type' => 'textfield',
        '#required' => FALSE,
        '#default_value' => isset($item['url']) ? $item['url'] : '',
    );

    $element['title'] = array(
        '#title' => t('Title'),
        '#type' => 'textfield',
        '#required' => FALSE,
        '#default_value' => isset($item['title']) ? $item['title'] : '',
    );

    $element['caption'] = array(
        '#title' => t('Caption'),
        '#type' => 'textfield',
        '#required' => FALSE,
        '#default_value' => isset($item['caption']) ? $item['caption'] : '',
    );

    $element['alt'] = array(
        '#title' => t('Alt'),
        '#type' => 'textfield',
        '#required' => FALSE,
        '#default_value' => isset($item['alt']) ? $item['alt'] : '',
    );

    $element['credit'] = array(
        '#title' => t('Credit'),
        '#type' => 'textfield',
        '#required' => FALSE,
        '#default_value' => isset($item['credit']) ? $item['credit'] : '',
    );

    $element['ajax_button'] = array(
        '#type' => 'button',
        '#attributes' => array( 'class' => array( 'cloudinary_browse ctools-use-modal') ),
        '#value' => t('Search cloudinary'),
    );

    return $element;
}

function cloudinary_field_is_empty($item, $field) {
    $valid = TRUE;
    foreach ($item as $key => $value) {
        if(empty($value)) {
            $valid = FALSE;
        }
    }
    return $valid;
}

function cloudinary_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {

    //in case we want to validate fields
    foreach ($items as $delta => $item) {
        if (!isset($item['publicID']) ||
            !isset($item['url']) ||
            !isset($item['title']) ||
            !isset($item['caption']) ||
            !isset($item['alt']) ||
            !isset($item['credit'])) {

            $errors[$field['field_name']][$langcode][$delta][] = array(
                'error' => 'cloudinary_fields_missing',
                'message' => t('%title: Make sure all fields are completed. '.
                    'Make sure all fiends are entered.',
                    array('%title' => $instance['label'])
                ),
            );
        }
    }

}

function cloudinary_field_widget_error($element, $error, $form, &$form_state) {
    switch ($error['error']) {
        case 'cloudinary_fields_missing':
            form_error($element, $error['message']);
            break;
    }
}

/**
This appears in the widget dropdown
*/
function cloudinary_field_formatter_info() {
    return array(
        'cloudinary_formatter' => array(
            'label' => t('Cloudinary selector'),
            'field types' => array('cloudinary'),
        )
    );
}

function cloudinary_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $element = array();
    foreach ($items as $delta => $item) {
        $element[$delta] = cloudinary_format_field($item);
    }
    return $element;
}

function cloudinary_format_field($item) {

    $item = array('url' => $item['url'],
        'title' => $item['title'],
        'caption' => $item['caption'],
        'alt' => $item['alt'],
        'credit' => $item['credit']);

    $element['url'] = array(
        'item' => array(
            '#type' => 'container',
            '#attributes' => array( 'class' => array( 'field-item') ),
            'text' => array(
              '#markup' => generate_image($item)
            ),
        ),
    );

    return $element;
}

function generate_image ($item) {

    $fields = array(
        '@url' => substr_replace($item['url'], '/c_limit,h_250,w_250', strripos($item['url'], "/"), 0),
        '@title' => $item['title'],
        '@caption' => $item['caption'],
        '@alt' => $item['alt'],
        '@credit' => $item['credit'],
    );

    $image = t('<figure><img src="@url" alt="@alt"><figcaption><h1>@title</h1><p>@caption @credit</p></figcaption></figure>', $fields);

    return $image;
}

```

This is the .info:

```
name = Cloudinary
description = Interact with your cloudinary account.
core = 7.x
package = Cloudinary
files[] = cloudinary.test
configure = admin/config/cloudinary

```

This is the .install:

```
<?php
/**
* Implements hook_install()
*/

function cloudinary_field_schema($field) {

  $columns = array(
    'publicID' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
    'url' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
    'title' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
    'caption' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
    'alt' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
    'credit' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE));

  return array(
    'columns' => $columns
  );

}

```

# Answer
I think the issue is in the way of checking empty values

```
function cloudinary_field_is_empty($item, $field) {
    $valid = TRUE;
    foreach ($item as $key => $value) {
        if(empty($value)) {
            $valid = FALSE;
        }
    }
    return $valid;
}

```

Make sure you're not checking for extra elements, a quick test would be to check for each element:

```
return empty($item['url']) && empty($item['title']) && empty($item['caption']) && empty($item['alt']) && empty($item['credit']);

```
> 2 votes

# Answer
As far as I know, You have to remove the last element manually. I haven't found a better solution yet. Achieving this for a 'node' form is easy, about other entity types, I don't really know if there is a proper general hook. There should be a hook for modules using Entity API...

Anyway here is how it's done, I've tested it with your module and it works. Also note this code is not specific to any particular field, You could use it as a general site-wide module:

```
/**
 * Implements hook_form_NODE_FORM_alter().
 */
function cloudinary_form_node_form_alter(&$form, &$fs) {
  foreach (array_keys($form) as $fname) {
    // Pull out field API form elements.
    if (substr($fname, 0, 6) != "field_" || empty($form[$fname])) {
      continue;
    }

    // Use field's own language not to break multilingual installations.
    $lang = $form[$fname]['#language'];

    // Decrease delta by one and get rid of the last delta;
    $max_delta = $form[$fname][$lang]['#max_delta']--;
    unset($form[$fname][$lang][$max_delta]);
  }
}

```

PS: If it broke anything you can remove the `foreach` and use a callback and see if this behavior is enabled for this particular field instance/type. You can then add some extra configuration to all the fields with related hooks: `Enable cloudy last delta remover for this field?` but ofcourse with a more site-admin not-very-technical friendly description.
> 1 votes

---
Tags: entities
---


# Question
Title: How can I pass page variable to a form builder function in a custom module?
I have an entity page where the entity has an email field. On that page, there is a form built in a custom module. What I'd like to to is that on form submit, the module sends an email to the address that is the value in the entity field.

So somehow I need to pass that email address to the form submit function.

What is the best way of doing this?

# Answer
One way is to put either the e-mail or an ID referencing the e-mail (the NID of the node where it is stored for example) as a hidden field, which will be received by your submit handler hook.

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#hidden
> 0 votes

---
Tags: 7, forms, entities
---


# Question
Title: How to change boostrap seach button class from btn-default to btn-primary?
I'd like to change the class from btn-default to btn-primary like says in here: http://getbootstrap.com/css/#buttons

```
<!-- Standard button -->
<button type="button" class="btn btn-default">Default</button>

<!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
<button type="button" class="btn btn-primary">Primary</button>

```

# Answer
Copy /sites/all/themes/bootstrap/theme/bootstrap/bootstrap-search-form-wrapper.func.php

to

/sites/all/themes/my-bootstrap-subtheme/templates

and edit that file at line 14:

```
 $output .= '<button type="submit" class="btn btn-default">';

```

to:

```
 $output .= '<button type="submit" class="btn btn-primary">';

```

This might be helpful: https://drupal.org/node/225125
> 3 votes

---
Tags: theming, search
---


# Question
Title: Drupal commerce - passing attributes from one module to other
Firstly I am new to Drupal commerce and start learning it on the job as required. So if you see my question as basic functionality in Drupal commerce, please pardon me.

Question: I have a simple commerce site and it look like as follows: Product view -- Shopping cart -- checkout

After checkout, I am adding a new custom module(creating an account for the user and few other things). I need to get the attributes of the product from the shopping cart module. How can I retrieve that information from the shopping cart module to the new custom module that I am building.

Thanks in advance.

# Answer
We already have a rule shipped with the drupal commerce core, which creates the user account on checkout process. It might be a good starting point for you in both ways how it is looping through order information to use in your custom module or you can modify the rule as per your requirement.

Rule is "Create a new account for anonymous user."
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: set field value from function after user account edit/registering action
I need to assign one custom field value from user profile. One field is nickname (this field is filled by user) and I need to generate another field with function.

The function takes nickname and using external library takes this nicknames ID. I need to run one function and save this ID everytime new profile is saved or existing updated.

I can not find good way to do it.

I tried with Rules module setting event after account updated with action evulate value with php, but there i can not load my api library to do the function.

Any information will help me

# Answer
Have you tried hook\_user\_presave() ?

https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook\_user\_presave/7

You have access to all fields of your new user and can pick up your value, call your custom code and get your new id. Then add it wherever you need to.

Use dpm($account) to inspect your user object.(devel module)
> 1 votes

# Answer
Problem was that my module doesnt loaded package. I need to turn off and againt turn on module in modules menu. Now all hooks works. So for everybody. Do it too if hooks doesnt loads.
> 0 votes

---
Tags: entities, rules, users
---


title: Adding "Directions To" to Geofield Map

text:
# Question
Title: Adding "Directions To" to Geofield Map
I have a content type with a Location text field and a Geofield. The Geofield is geocoding the Location field into a coordinate and displaying it to a Google Map embed on the page.

This is working quite well and the map is always marked at the correct location. The problem I have is that the Google Map is quite useless because it doesn't allow the user to do anything with it.

The map shows the location but doesn't allow the user to get directions to it or get the address or anything. When the user clicks on the marker on the map they get a shout out box with the name of the event not the location.

Is there any way I can have the Google Map be more useful? ie add a Directions To button or something like that?

# Answer
I added directions links to my markers, and to the view's attachment that contains a list of locations displayed on the map. To do this create the directions links:

1. Added my content type's `Post Address` field (from the addressfield module) to the views list of available fields.
2. Re-wrote the `Post Address` fields view output with the following:

```
<a href="http://maps.google.com/maps?daddr=[field_cstore_address-premise],[field_cstore_address-thoroughfare],[field_cstore_address-locality],[field_cstore_address-administrative_area],[field_cstore_address-postal_code]">Directions</a>

```
> 0 votes

---
Tags: google-maps, location
---


# Question
Title: Assign custom id for user on registering
I need to assign custom ids for all users. The Id will come from API and its depend on other filled by user custom field. Witch hook should I use and witch variable holds id value?

# Answer
I presume you're referring to a login ID - you should be able to use hook\_form\_alter to access the registration form, and create a default value.

get Devel module and use dpm($form) in that function to look through the array to find the exact element you want to change.

after that you can probably use a number of options to hide the element, including css so that the user can't change it before being submitted.
> 0 votes

# Answer
Are you looking to add a secondary ID field, separate from UID? If so, the user entity is fieldable, and you could probably use hook\_user\_update or hook\_user\_presave to populate the field, using aggregated the data from other user fields.

If I follow you correctly, it would be something like 'field\_1 + field\_2' comprise the new "ID" field you're creating. In which case, one of these hooks will achieve what you're looking for. Feel free to provide further clarification if needed.
> 0 votes

---
Tags: 7, hooks, users
---


# Question
Title: Drupal 7 theme similar to Wordpress Twenty Fourteen theme?
I'm looking for a Drupal 7 theme similar to the wordpress theme Twenty Fourteen. The main factors that I would like to find in a drupal theme are

* the image grid for posts similar to the grid pictured on the theme page
* the menu locked into the side
* responsive

I was hoping to find something with as little modification needed as possible, but I'm not opposed to creating a subtheme and doing some customization. I tried searching some drupal theme repositories like the offerings available on themeforest and template monster but I haven't found anything that caught my eye.

# Answer
> 0 votes
You're going to find Drupal is pretty limited on well made pre-built themes. If you're looking for a good grid system, NineSixty and Boostrap provide a good base to build upon. As far as menu settings and post output, this is typically custom to each site. The post output, for instance, would rely on a custom content type and View to display this information.

---
Tags: theming
---


title: Commerce Event Registration

text:
# Question
Title: Commerce Event Registration
How to create a commerce site which also has the ability to take registration information during/before/after registration?

I am developing a website which offers a variety of training courses. When adding a particular course to the basket, I would like the to be able to take the details of the people (multiple attendees) who will be attending the course.

How can this be achieved?

# Answer
> 0 votes
There's a module for that: Commerce Registration. You've got a registration field attached to your commerce products and you can work from them to build a solution, for a distribution that uses this for events check out COD, that might fit your needs.

---
Tags: commerce, users
---


# Question
Title: Returning an entity from a custom Rules action
I'm new to writing modules and back end dev. I'm trying to write a custom Rules action that takes a list and returns one item from that list to use as a relationship end point.

I've declared the rule here and got it working as far as I can extract one item from the list and put it as a message on screen:

```
function rules_additions_rules_action_info() {
$actions = array(
    'rules_additions_action_get_next_list_item' => array(
        'label' => t('Get next list item'),
        'group' => t('Data'),
        'parameter' => array(
            'list' => array(
                'type' => 'list',
                'label' => t('Select the current list'),
                ),
            ),
        ),
    );

return $actions;
}

```

And can do something like this, for example:

```
function rules_additions_action_get_next_list_item($list) {
    drupal_set_message(t('The item is ' . print_r($list[0], TRUE)), 'status');
}

```

What I want to be able to do is return that list item as an entity so at the next step in my rule set I can do "Add an item to a list" and select it in the rules UI.

I hope this makes sense.

Thanks in advance.

# Answer
If you check the rules hook hook\_rules\_action\_info docs, you'll see the provides element:

> provides: (optional) An array describing the variables the action provides to the evaluation state with the variable name as key. Each variable has to be described by a sub-array with possible attributes as described afterwards, whereas the name of a parameter needs to be a lowercase, valid PHP variable name.

Usage example from commerce\_cart module:

```
  $actions['commerce_cart_product_add_by_sku'] = array(
    'label' => t('Add a product to the cart'),
    'parameter' => array(
      'user' => array(
        'type' => 'user',
        'label' => t('User'),
        'description' => t('Specify the user whose shopping cart order the product will be added to, typically <em>site:current-user</em>.'),
      ),
      'sku' => array(
        'type' => 'text',
        'label' => t('Product SKU'),
        'description' => t('The SKU of the product to add to the cart.'),
      ),
      'quantity' => array(
        'type' => 'integer',
        'label' => t('Quantity'),
        'default value' => 1,
      ),
      'combine' => array(
        'type' => 'boolean',
        'label' => t('Combine similar items in the cart'),
        'description' => t('If checked, the product will be combined added to an existing similar product line item in the cart by incrementing its quantity.'),
        'default value' => TRUE,
      ),
    ),
    'group' => t('Commerce Cart'),
    'callbacks' => array(
      'execute' => 'commerce_cart_rules_product_add_by_sku',
    ),
    'provides' => array(
      'product_add_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Added product line item'),
      ),
    ),
  );

```

Note that you need to return an array from your action with the parameters named, for this example, 'product\_add\_line\_item':

```
// Only return an added line item.
if ($line_item = commerce_cart_product_add_by_id($product->product_id, $quantity, $combine, $uid)) {
  return array('product_add_line_item' => $line_item);
}

```

So potentially you could provide as many elements as you need in your actions for further actions or rules components.
> 0 votes

---
Tags: rules, actions
---


title: Custom Content Pane Title

text:
# Question
Title: Custom Content Pane Title
I created a custom content pane, however, I'm having some issues trying to hide the title on the page and was wondering if anyone knew of a module for this?

Here's the quick breakdown:

I created a new custom content pane:

Above I have given the custom content pane no title, however, this is how it shows up:

I'd really like to make it look more descriptive.

If I add a title it will show on the variants \> content page (image below), but unfortunately, it also shows up on the actual page as well.

Live page:

Any and all help would be greatly appreciated. Thank you!

# Answer
> 1 votes
Have a look at:

`ctools_custom_content_type_admin_title`

```
/**
 * Callback to provide the administrative title of the custom content.
 */
function ctools_custom_content_type_admin_title($subtype, $conf) {
  $settings = ctools_custom_content_type_get_conf(ctools_custom_content_type_content_type($subtype), $conf);

  $output = t('Custom');
  $title = !empty($settings['admin_title']) ? $settings['admin_title'] : $settings['title'];
  if ($title) {
    if ($settings['custom_type'] != 'fixed') {
      $output = t('Custom: @title', array('@title' => $title));
    }
    else {
      $output = $title;
    }
  }

  return $output;
}

```

If the admin title is used, and the custom content type is not set to 'fixed' (see `ctools_custom_content_type_get_conf`), it will use your user input admin title for admin display there.

---
Tags: panels
---


# Question
Title: Mystery "test" text showing on page after views module update
I've got an instance of mystery text showing on my blog.

Here's the scenario: I've just run the security update to 7.x-3.8 on a drupal site running 7.28 on my local machine, and didn't see this issue. When I ran the updates on the live site the issue appeared.

On the homepage blog, at the bottom of every post there is the word "test". I know it's outside of the body field tag, but I have no idea where it's coming from. Seen here: http://susanhoodbooks.com/

I've checked the code of the view, the templates, the contents of the nodes and I can't find anything. I'm hoping to ask for some suggestions of where I might look next before I revert the modules. again, I haven't been able to recreate this on my local.

Please let me know if I need to supply any other information. Thanks

# Answer
Looking at the DOM, it appears to be coming from Views. Since it's in a

tag, I would suggest looking to see if there is a unused field that might be the culprit.
> 0 votes

# Answer
I can see there is some jquery script adding the string 'Test' for each view row . Look into your code base for the string '.view-id-blog .views-field-body' and you'll find out from what file is it coming.

You may also want to disable javascript aggregation for sometime, and then see the exact file name in the developer tools directly.
> 3 votes

---
Tags: 7, views, upgrading
---


# Question
Title: Unable to show the Uploaded Image by the user in user submitted form for node
On my site, we have a form which directly adds data into one content type. When user submits the form, all the field data is inserted. It's working fine except the Image field.

What I want is that the image field is automatically uploaded and is shown as automatically uploaded in the node admin. In the code below, I am providing a static image just to make it work and it still doesn't :(.

I have been banging my head on it for hours and hours and I'll be very thankful if you can provide me with any hope or solution ....

So with the following code, I've been able to upload the Image in the `public://tmpprofiles` folder. The problem is that `file_copy` is not working and throws an exception in error log that that

```
File http://yoursite.com/sites/default/files/tmpprofiles/anewimage.png could not be copied because it does not exist.

```

**But it does exist!!!!**

I don't why it is saying that. I guess it means that all the code is working except the last two lines. Those are the lines which will attach the image to the node and therefore would show this image as an uploaded image in the node admin.

Please discard my meh code if you've a better way of doing this.

## Code

```
  $path = './sites/default/files/animage.png';
  $filetitle = 'newimage';
  $filename = 'anewimage.png';

  $file_temp = file_get_contents($path);

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

  $tmp_file_path = 'public://tmpprofiles/' . $filename;

  $file_path = file_create_url($tmp_file_path);

  $file = (object) array(
    'uid' => 1,
    'uri' => $file_path,
    'filemime' => file_get_mimetype($file_path),
    'status' => 1,
  );

  //These two lines don't work.

  $file = file_copy($file, 'public://another');
  $new_moment_node->field_profile_photo[$new_moment_node->language][0] = (array) $file;

```

# Answer
> 0 votes
In Drupal 7 you can use **system\_retrieve\_file()**

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

Can you try this Save image from URL to a field from a custom module

---
Tags: forms, files
---


title: Disable locale module breaks site

text:
# Question
Title: Disable locale module breaks site
We want to disable the locale module in Drupal site. Because some content was saved as language 'en' previously, disabling locale does not reset content and field database tables language field to 'und' or LANGUAGE\_NONE. After disabling the module any nodes or fields that have been saved as 'en' are not displayed.

to fix this I created a module to update the entire database.

```
    $schema = drupal_get_schema();

    foreach($schema as $table =>$structure){

     if(isset($structure['fields']) && isset($structure['fields']['language'])){

           set_time_limit(0);

          db_update($table)
            ->fields(array('language' => 'und'))
            ->condition('language','en')
            ->execute();
   }
}

```

This code does not update the language field and i'm not sure why. Is it because the language field is an index?

also this should be incorporated into the locale module uninstall function to avoid other sites breaking in future.

Any help is appreciated

Origional post -- https://drupal.org/node/2106247

# Answer
> 1 votes
Here is what I did to solve this problem:

1. Learn how to run scripts with Drush http://www.oliverdavies.uk/blog/dont-bootstrap-drupal-use-drush/
2. Write this script:

```
<?php

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')->addMetaData('account', user_load(1));
$result = $query->execute();
$nids = array_keys($result['node']);
$n = count($nids);

foreach($nids as $i => $nid) { // go through ALL nodes
  $node = node_load($nid); // load the node
  $type = $node->type; // get the content type
  $field_langs = field_language('node', $node); // get the language of each field
  foreach($field_langs as $field => $lang) { // go through ALL field of this node
    if ($lang != LANGUAGE_NONE) { // if the field is in the wrong language
      $items = field_get_items('node',$node,$field,$lang); // get all field values
      if (!empty($items)) {
        $node->{$field}[LANGUAGE_NONE] = $items; // put it under language neutral
        unset($node->{$field}[$lang]); // remove the old language
      }
    }
  }
  $node->language = LANGUAGE_NONE; // set the node language to neutral
  node_save($node); // commit changes
  echo ("$i/$n\tnid=$nid\t$type\n"); // progress report
}

```
3. Run it to translate every node on the site back to language neutral

I cannot guarantee that this works for nodes with fields that have values in more than one language at a time. Feel free to use and improve this code. I have tested this on my development site, and all seems fine after disabling & uninstalling locale. Let me know in the comments if this works for you, too!

---
Tags: 7
---


# Question
Title: Nodes appearing but when clicked "page not found"
I recently migrated a site and some nodes don't appear in the content list but they do appear in Views I've created. When they're clicked however (example.com/node/123) it just returns a Page not found.

The node is in the database, both in the node table and the node\_revisions as well as the relevent CCK tables.

What could possibly be causing this?

# Answer
> 2 votes
I had this problem, it only affected certain nodes. When investigated in db all values corresponded between node and node revisions tables so I initially assumed it wasn't related to values in those tables. Checked url\_alias table and all seemed well there too, site is multilingual so checked the variables table for discrepancies between multilingual paths auto values for custom content types and all was also well. Rebuilding the menu router didn't help either. I already tried resetting all node access permissions as suggested here. Honestly I was just about out of ideas, then thankfully I came across this post :D The problem had come from where i had imported some node content from a custom module i wrote to ingest nodes from xml (which worked fine) but since the import was done the user account which had done the import had been removed. This meant all the multilingual imported nodes were still linked to that, now non-existent user account's uid. A simple sql query in phpmyadmin set all my nodes to be owned by admin (uid:1)

UPDATE node set uid = 1; UPDATE node\_revisions set uid = 1;

This fixed my perplexing issue. I propose a patch so that if a user account is removed Drupal optionally checks all nodes belonging to that user and updates them to uid: 1 so nodes added by a deleted user account aren't suddenly inaccessible to the rest of the site including uid 1 (admin). This was frustrating as a sensible sort would naturally assume that uid 1 will always have view/edit access to any node content on the site regardless of if it is, disabled, enabled or added by some mugwump. I wish you good Drupaling!

# Answer
> 1 votes
In most of the cases this is a conflict with permissions, so go to `admin/content/node-settings/rebuild` and rebuild the permissions.

This happens when you test some access modules and they're not correctly uninstalled, also take notice that views not always uses the same permissions this is why you can see your node in views but not in `node/123`.

Also if you don't have any access module installed and the rebuild doesn't work, have a look in your database and execute the following queries:

```
TRUNCATE TABLE node_access;
INSERT INTO node_access VALUES (0, 0, 'all', 1, 0, 0);

```

This should also fix it.

You can try to install Devel and use the Devel Node Access module shiped with it on the node to analyze the problem.

# Answer
> 1 votes
It could be the database doesn't contain anymore the information about the account used to create the node.

# Answer
> 0 votes
What you need to do is go to www.yourdomain.tld/admin/structure/pages ensure that these are all disabled and then the problem should be resolved unless you've deleted critical system files that Drupal requires in that case go and re-download the distribution of Drupal and then upload to your host and extract files then move them to overwrite the current ones that are there.

---
Tags: 6, migrations
---


title: Combine hook_search_execute

text:
# Question
Title: Combine hook_search_execute
I have hook for *user\_search\_execute* and *node\_search\_execute* for both user and nodes but i want to merge both into *mymoduel\_search\_execute* but only *node\_search\_execute* uses index not *user\_search\_execute* like below :-

```

    /* node search execute */

    function node_search_execute($keys = NULL, $conditions = NULL) {
        // Build matching conditions
        $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
        $query->join('node', 'n', 'n.nid = i.sid');
        $query
            ->condition('n.status', 1)
            ->addTag('node_access')
            ->searchExpression($keys, 'node');

        // Insert special keywords.
        $query->setOption('type', 'n.type');
        $query->setOption('language', 'n.language');
        if ($query->setOption('term', 'ti.tid')) {
            $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
        }
        // Only continue if the first pass query matches.
        if (!$query->executeFirstPass()) {
            return array();
        }

        // Add the ranking expressions.
        _node_rankings($query);

        // Load results.
        $find = $query
            ->limit(10)
            ->execute();
        $results = array();
        foreach ($find as $item) {
            // Render the node.
            $node = node_load($item->sid);
            $build = node_view($node, 'search_result');
            unset($build['#theme']);
            $node->rendered = drupal_render($build);

            // Fetch comments for snippet.
            $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);

            $extra = module_invoke_all('node_search_result', $node);

            $uri = entity_uri('node', $node);
            $results[] = array(
                'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
                'type' => check_plain(node_type_get_name($node)),
                'title' => $node->title,
                'user' => theme('username', array('account' => $node)),
                'date' => $node->changed,
                'node' => $node,
                'extra' => $extra,
                'score' => $item->calculated_score,
                'snippet' => search_excerpt($keys, $node->rendered),
                'language' => entity_language('node', $node),
            );
        }
        return $results;
    }

```

i want to combine both queries into one even search url anything else.

please help..

# Answer
Check our the module Search combine, it gives you exactly that.

Here's how I have the admin search configured:

Also related: How to have a combined search view that shows both users and content on search terms?
> 0 votes

---
Tags: 7, search
---


# Question
Title: How to target the "site name" within a css file
How does one target the site name (the one that appears immediately below the site logo) within a css file? I would like to both change the color of the site name text in addition to centering the site name (for some reason it's by default confined to about a third of the header space on the left). Essentially, how can I style the space above the menu region if it is not part of the header region?

Any help would be much appreciated. If you find what I've written to be vague I can certainly try to clarify.

# Answer
> 2 votes
It depends on the theme that you're using.

As Patrick Ryan said " You should look into using firebug in firefox or inspect in chrome or developer tools in IE. These will all easily show you what css class you need to target to make these and any other changes."

I personally use Chrome so in order to do that, just right click on the site name. Here's a preview in chrome.

you can use `#site-name` or `#name-and-slogan` in this theme. But this will change per theme. The same process can be done if you want to align the text or make it wider.

The great thing about using these development tools is that they allow you to add CSS right on the browser. you'll see that on the right side. Just double click.

If you're using a subtheme of Zen, for example, check the templates in the zen folder to see the page.tpl.php file for the template of the page.

I touch on using templates in Zen subthemes in my slides here (slide 44 onwards): http://www.slideshare.net/japodomingo/theming-with-zen

If you know how to use templates, you can manipulate the display any way you want. :) Here's a brief overview of the templates. https://drupal.org/node/190815

I hope this helps.

---
Tags: theming
---


# Question
Title: Taxonomy term not found using tid from term reference
The users in my webapplication have a `term reference` **suppliers**.

I also have a `content type` **transaction** where I have the same `term reference`. Now I would like to hide the select list and **set the default value** programmatically. This is what I do now:

```
$form['field_supplier']['#type'] = 'hidden';
$user_suppliers = array();

foreach($user_selling->field_suppliers['und'] as $supplier)
{
    $user_suppliers[] = $supplier['tid'];
}

$firstsupplier = reset($user_suppliers);

$first_supplier = taxonomy_term_load($firstsupplier);

```

As you can see I loop through the **tid's** and save them in array. Afterwards I pick the **first** one (there's a reason I don't pick the first instead of looping through).

The `$firstsupplier` variable results **7** so what's not abnormal for a **tid**. But when I want to load the taxonomy term I get a response false... (he can't find it) .

I recently resetted my `taxonomy vocabulary` to **alphabetical**, could that be the reason? (I think not, because I tried it after saving them in a random order)

# Answer
First, don't use 'und', you should be using LANGUAGE\_NONE instead.

Your code works, so you might have a data inconsistency on your database, are you sure that the term id 7 really exists?

You can use entity api metadata wrappers to access easier to the field information, or if you're not using Entity API module, the function field\_get\_items is a better way to access the information.

```
$user_suppliers = array();
$items = field_get_items('node', $user_selling, 'field_suppliers');

foreach($items as $item) {
    $user_suppliers[] = $item['tid'];
}

$firstsupplier = reset($user_suppliers);
$first_supplier = taxonomy_term_load($firstsupplier);

```
> 1 votes

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


# Question
Title: title of view posted link is not showing
I have created a view with display format Unformatted List of titles (linked) and it works fine as it shows the list of linked title but the problem is now when I click the link to view the article it shows full post without title.

So am I doing something wrong? How to show the title there?

# Answer
It looks to me that the problem is with the node display itself and not the view.

When you click the title you're led to the node page.

Check your content type display settings in **Structure-\>Content Type-\>(your content)-\>Manage Display**
> 1 votes

---
Tags: 7
---


title: Using Contextual Filters and Panels

text:
# Question
Title: Using Contextual Filters and Panels
Hi Drupalites I need some help.

1.I was using relationship to output authors personal info associated with a piece of content which i did successfully. so i was trying something else but i didnt succeed.

I created a content type called State-Capital which has a list of of States and their respective capitals and I created another Content type called Misc Project which had different project details like Cost,Project Approve and State.Now i was trying to link the state field to output the capital associated with the respective state in Misc Project content type but i cudnt.The field name for States in both content type are same.Pls help.

1. I am trying to learn panels so wanted to know if there is any link or material for the same

# Answer
Ranjan is correct, you should add a node reference field to the **Project** content type so it can reference a **State-Capital**

In order to display any info about the state on the Project page you can use the Views 3 and Reference modules.

For this example let's say the node reference is labeled **"Project Location"**, and the State Capital is **Austin, Texas**.

Here are some steps you can follow:

**1) Create a View**

-- Create a new view block that displays State-Capital type nodes.

**2) Add a Relationship to the view**

-- Add a Relationship: **Content: Project Location**. This will allow you access to the fields of the Projects that reference **Austin, Texas**.

-- Give the relationship an identifier. Let's say `related_project`.

-- Save the relationship.

**3) Add a Contextual Filter to the view**

-- Add a Contextual Filter: **Content: Nid**.

-- Edit the contextual filter.

-- Set the Relationship in the contextual filter to related\_project.

-- Look for WHEN THE FILTER VALUE IS NOT IN THE URL.

-- Set it to Provide default value -\> Content ID from URL. This will get the nid of your Project.

-- Save the Contextual Filter.

-- Add in your fields. (Title at least)

**4) Test it**

To test in the preview, input the nid of your Project example as a contextual filter in *Preview with contextual filters:*

Save your view!

**5) Enable the block in your node pages**

After the view is complete, configure the new block to display in content type Projects.

I hope this helps.

Updated: 2014/06/18
> 0 votes

---
Tags: views
---


# Question
Title: How to show pager in terms of views of tags?
I've lists of tags suppose **good** and **bad**, now when I click to good tag it lists all good posts ( full posts ). But I wanted to show good posts only upto 5 items then all other should be there while I navigate.

So, how can I show the pager for the clicked tags. I tried it with views module, but nowhere I could see it to do this.

I've setup my views like this:

# Answer
Create a view of content ( as a page with pager ) and add a contextual filter named `Content: Has taxonomy term ID`. Refer the images below.

Once you have configured this then you can acces this view using a url like `mysite.com/view-path/tag-name`.
> 1 votes

# Answer
Views module provides a view for Taxonomy terms to cater to the requirement of displaying articles related to a tag.

Under Structure -\> Views look for the view "Taxonomy term" and enable it in case it is disabled. You do not need to create a view for this purpose.

The taxonomy page by default has the pager configured with 10 items per page.You may edit it by clicking on the edit option of the view and editing the pager option as shown in the screenshot here.
> 0 votes

---
Tags: 7
---


# Question
Title: Create block programmatically based on node content
In Views we can create a block that the content depends on the content of a node using contextual filters. So we can pass variables and check the visibility of the Views-Block.

Let’s say in our content type we have a field that has a text-field. In Views-\>Contextual-\>Our field-\>Provide default value-\> content ID from URL can grab this.

But creating a block programmatically

```
hook_block_view($delta = '') {
…
$block['content'] = theme('item_list', array(
         'items' => ???,
          'type' => 'ul',
        ));
…
}

```

How we can grab these values form the node-field?

And if there are no values how we will hide the block?

# Answer
You can use `menu_get_object()` to get the current node. Refer `menu_get_object`

> `menu_get_object()` provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling `menu_get_object()` will return that.

If you want to hide the block (not only the content) warp the `return $block;` in `if`.

```
if (isset(menu_get_object()->some_field) {
  ...
  return block;
}

```
> 0 votes

# Answer
Found a few modules depending on your need:

Node field block

> An easy way to create blocks with a collection of node fields. Focused on letting customers manage most of the content on a page in just one node. You can create multiple blocks for a node with one or a combination of fields and move them in different regions.

Field as block

> Field as Block provides an easy way to display one or more fields of the current node in a block.

There's a custom way also if you want. You can use below function for this purpose.

```
render(field_view_field('node', $node, 'field_myfield'));

```
> 0 votes

---
Tags: views, blocks
---


title: Strip HTML tags from autocomplete field

text:
# Question
Title: Strip HTML tags from autocomplete field
I have altered #autocomplate\_path for node queue autocomplete node suggestions to show image field along with title and nid, which is working fine. The code which is returns the image with title and nid is.

```
$matches[$node->nid] = theme('image_style', array('style_name' => $get_image_field_style, 'path' => $image_field_uri, 'attributes' => array('class' => array('nodequeue-runsheets-images'))))
              . check_plain($node->title)
              . " [nid: $id]";

```

This is how I see the results with the above working code: -

The problem comes when drupal autocomplete pull the selected suggestions and populate it to autocomplete textfield. I see the html tags as . How can I override this to show only node title and mid.

The problem:

# Answer
The solution in following post worked for me http://www.derreklemar.net/tutorial/drupal-autocomplete-overriding-default-select-event-behavior
> 2 votes

---
Tags: ajax
---


title: How to migrate date fields correctly?

text:
# Question
Title: How to migrate date fields correctly?
I want to migrate taxonomy terms from a legacy database to my drupal 7 installation. This is working almost as desired. What I do is basicly define a mapping as described in any migration example, e.g.:

```
$this->addFieldMapping('name', 'legacy_name');

```

But when I try to migrate dates I totally fail. This does not work:

```
$this->addFieldMapping('field_date', 'valid_from');

```

After some digging I found out I had to enable the `Date Migration` module, allright. But still, this does not work at all. I discovered some date migration example code and found out I have to reformat the date field in the `prepareRow()` function. But that feature is very much undocumented. The linked example doesn't work at all.

My current code looks like that:

```
abstract class MyBasicMigration extends Migration {
  public function __construct() {
    parent::__construct();
  }
}

class MyMigration extends MyBasicMigration {
  public function __construct() {
    parent::__construct();

    #[...]

    $this->destination = new MigrateDestinationTerm('mystuff');
    # this works:
    $this->addFieldMapping('name', 'legacy_name');
    # this does not:
    $this->addFieldMapping('field_date', 'valid_from');
  }

  public function prepareRow($current_row) {
    # checks for malformed date strings in DB and converts to datetime type
    if (($current_row->valid_from = strtotime($current_row->valid_from)) === false) {
      $current_row->valid_from = strtotime('1970-02-01');
    }
    if (($current_row->valid_to = strtotime($current_row->valid_to)) === false) {
      $current_row->valid_to = strtotime('2037-12-31');
    }
    # converts the date to YYYY-mm-dd format
    $format = 'Y-m-d';
    $current_row->valid_from = date($format, $current_row->valid_from);
    $current_row->valid_to = date($format, $current_row->valid_to);
    # creates a date field for the valid_from/to migration mapping
    $current_row->valid_from = array(
      'value' => (string) $current_row->valid_from,
      'value2' => (string) $current_row->valid_to,
      'timezone' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
      'timezone_db' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
      'date_type' => 'datetime',
    );
    $current_row->valid_from = drupal_json_encode($current_row->valid_from);
    # debug result output
    watchdog("PW_TEST", $current_row->valid_from, $variables = NULL, WATCHDOG_DEBUG, $link = NULL);
  }

```

The date format in database is a string formated like this `2013-12-31`.

The `prepareRow()` function seems to work at all and the `watchdog()` output looks very good:

```
{"value":"1970-02-01","value2":"2013-12-31","timezone":{"timezone":"Europe\/Berlin","timezone_db":"UTC","rrule":null,"language":null},"timezone_db":{"timezone":"Europe\/Berlin","timezone_db":"UTC","rrule":null,"language":null},"date_type":"datetime"}

```

As you can see the returned JSON string includes the correct dates. But at some point now the migration mapping fails at the fields `valid_from` and `valid_to`.

If I do a `print_r()` on a migrated taxonomy term, I get something like that:

```
[field_date] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] =>
                        [value2] =>
                        [timezone] => Europe/Berlin
                        [timezone_db] => Europe/Berlin
                        [date_type] => datetime
                    )
            )
    )

```

The JSON object got mapped correctly, `date_type` and `timezone` just displays properly. But where the hell are my dates gone? Any ideas?

I've been working on this all day now and I can not see any issues with my code. Thanks for any hints!

# Answer
> 4 votes
This is plain awfull and totally undocumented. But I found out:

```
# creates a date field for the valid_from/to migration mapping
$current_row->valid_from = array(
  'from' => (string) $current_row->valid_from,
  'to' => (string) $current_row->valid_to,
  //'timezone' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
  //'timezone_db' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
  //'date_type' => 'datetime',
);

```

Two issues with the code above are solved:

1. The array containing the dates **has to contain** the fiels `from` and `to`. Otherwise it does not understand the date range. I've seen this in the date migration example but never thought the field names are important for the mapping. (I rather used the target names `value` and `value2`.)
2. The array **should not contain** information about timezone and date types. The `DateMigrateFieldHandler::prepare()` will do that for you.

The working code above yields:

```
[field_date] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => 1970-02-01 00:00:00
                        [value2] => 2013-12-31 00:00:00
                        [timezone] => Europe/Berlin
                        [timezone_db] => Europe/Berlin
                        [date_type] => datetime
                    )
            )
    )

```

Fixed. :)

# Answer
> 2 votes
This is still poorly documented, yet I keep stumbling on this issue...

The solution given is almost correct, however, the final array must be passed through the *drupal\_json\_encode()* function to work:

```
# creates a date field for the valid_from/to migration mapping
$current_row->valid_from = drupal_json_encode(
  array(
    'from' => (string) $current_row->valid_from,
    'to' => (string) $current_row->valid_to,
    //'timezone' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
    //'timezone_db' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
    //'date_type' => 'datetime',
 ));

```

---
Tags: entities, migrations, datetime
---


# Question
Title: Drupal Gardens: is it possible to install a new theme?
I need to create a site into Drupal Gardens, but my client needs a custom responsive theme. I have searched in the FAQ and internal page of Drupal Gardens, but I have not found anything about this possibility.

Is there a way to install a theme for my site into Drupal Gardens?
Can I install some modules from drupal.org?

# Answer
Drupal Gardens is really limited and you cannot install a theme from drupal.org but what you can do is to customize the possible "layouts" that Gardens give to you.

If you click on the layout button on the panel you will see different layouts (columns and sidebars) and from this basic structure you can start applying custom CSS. Check more here http://www.drupalgardens.com/documentation/themebuilder/layout-tab and http://www.drupalgardens.com/documentation/themebuilder/advanced-tab
> 0 votes

---
Tags: 7
---


# Question
Title: how to store images into file_managed table from android to drupal
I have tried calling Drupal file service from android and it is storing images in `application/octet` format and not in `image/jpeg` format in `file_managed` table.

```
$data['file'] ='encodedimage';
$fid = file_save_data($data);

```

So I thought I will call `file_save_data($data)` to store images where I pass the image as encoded string. But it is still storing in application/octet format and not in image/jpeg.

Can somebody help me to store as image/jpeg format into file\_managed table?

# Answer
> 0 votes
The Services module provide an easy to use web services enpoint to create file which do all the heavy PHP work for you.

In `file_save_data()`, the mime type of the file is derived automatically, likely from its filename. You can set the filename of the saved file by using the `$destination` argument.

---
Tags: media
---


# Question
Title: Different fields in user profile for different user roles
I have created user roles parent, teacher and student. I want to relate parents with a student by creating a `Field` **Related student** for only parents. I tried using **User References**. But that makes the field common for all user roles. I also tried **Profile2** module. But that doesnot exactly fit what I want. Is there any other way to achieve that ? Any suggestions please. Thank you.

# Answer
> 5 votes
Field Permissions will let you assign different permissions to a field based on role.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> ### Features
>
> * Enable field permissions on any entity, not just nodes
> * Role-based field permissions allowing different viewing patterned based on what access the user has
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed

# Answer
> 0 votes
Use Profile2, and you can have whole sets of fields only used by the role chosen. If not, see below.

This is the best option and I'll explain:

If you have fields, and use field permissions. Say you have employee # and customer number and both are required. Field permissions allows administrators to edit all values on these fields. /sarcasm Well sorry, you can't create your user because you haven't filled in all required fields /sarcasm. So you either have to enter a phony employee number or a phony customer number depending on who you are creating.

Other option: don't have required fields, instead use complete\_profile to simulate required fields.

---
Tags: entities, users
---


# Question
Title: How to get node content in an sql query?
I see that in D6 the node table has only the title of the node. How to query database to get the body (content) of a particular node?

Update: I figured out the content bodies are stored in node\_revisions table.

# Answer
**Drupal 7**

In Drupal 7 body content is saved in `field_data_body` and `field_revision_body` tables.

So example query to fetch title and body would be:

```
SELECT title, r.body_value, n.changed FROM node n LEFT JOIN field_data_body r ON n.nid = r.entity_id AND n.vid = r.revision_id

```

To query via drush, run `drush sqlq` following by above query.
> 5 votes

# Answer
For education purposes, this is the sql that D6 Views produces (according to its sql preview):

This particular node would be the one having node id 1:

```
SELECT node_revisions.body AS node_revisions_body,
       node_revisions.format AS node_revisions_format
FROM node node
LEFT JOIN node_revisions node_revisions
ON node.vid = node_revisions.vid
WHERE node.nid = 1

```

In a module, however, you should use proper methods such as db\_query() for maintainability and security.
> 3 votes

---
Tags: nodes, database
---


# Question
Title: In Drupal 7 how do I add an anchor tag to a path alias menu link
I created a node in drupal 7 and given it a url path alias of 'testing'. When I try to create a menu item that links to the path alias with an anchor, it throws an error

If I do `node/1#this` it works, but again not with a url path alias.

Is there a work around?

# Answer
> 4 votes
You can add the full url with the anchor tag. Not the best for deployment but a work around.

# Answer
> 1 votes
I found adding the page path without it's alias would validate the form.

For example: "node/1#top"

Although, I now have an .active-trail and .active class issue on the menu item/link.

# Answer
> 1 votes
This works for me:

```
function phptemplate_url_outbound_alter(&$path, &$options, $original_path) {
    $alias = drupal_get_path_alias($original_path);
    $url = parse_url($alias);

    if (isset($url['fragment'])){
        //set path without the fragment
        $path = $url['path'];

        //prevent URL from re-aliasing
        $options['alias'] = TRUE;

        //set fragment
        $options['fragment'] = $url['fragment'];
    }
}

```

# Answer
> 0 votes
In search for an answer for my colleague I found a gist.

You guys can try it out.

https://gist.github.com/932595

I have not worked on this.

---
Tags: 7, routes, path-aliases, navigation
---


# Question
Title: Printer: Is it possible to show print PDF and ePub url link for each node on Views?
I have Printer module installed on Drupal 7. Let's say I have a view that lists all the articles in table format. I would like to have the PDF and ePub url link next to each article as a field. Is it possible?

# Answer
Yes, add a global text field and under **Rewrite Results** select **output this field as link** and give the path eg. for PDF it should be **printpdf/\[nid\]**.

similarly you can create one more field for EPUB using **printepub/\[nid\]**.

Note **\[nid\]** is a replacement pattern, you should add nid before these fields and exclude it from display.
> 2 votes

---
Tags: views, files
---


# Question
Title: problem with Views module (installation)
I had a `views` page created on my site and it seemed to work well. Then I started to update some of the modules that updates wre available for and then all of a sudden, my `views` module didn't seem to be installed anymore. So what I did, went back to reinstall it, now the link to my views page on the site is back (http://www.quaaoutlodge.com/special-events) but when I click on it, I get this error: `Fatal error: require_once() [function.require]: Failed opening required '/home/content/q/u/a/quaa7882/html/sites/all/modules/commerce_kickstart/modules/contrib/views/includes/view.inc' (include_path='.:/usr/local/php5/lib/php') in /home/content/q/u/a/quaa7882/html/includes/bootstrap.inc on line 3047`
`commerce_kickstart` is a module I have removed in the meantime and am no using it anymore nor is it in my modules `directory`. Why is something still referring to it? How can I fix this?

Thank you, Ron

# Answer
The views module was installed as a part of commerce\_kickstart in sites/all/modules/commerce\_kickstart/modules/contrib. You removed that distribution, which is a good idea because it was installed in the wrong directory (should be in /profiles). Most probably you then downloaded and reinstalled a fresh views in sites/all/modules.

If you move a module you should clear the cache or (in some cases) rebuild the registry.

The easiest way to clear the cache when you cannot reach the admin of the site is to go to /update.php and run the update process (take a backup first). Other options are the Registry Rebuild module or Drush (drush cc all).
> 1 votes

# Answer
commerce\_kickstart is not a module, is an install profile, and it shouldn't go in your modules directory nor be installed as a module.

If you've installed the site using the commerce kickstart profile and you've removed it, you might have more problems similar to this one, one thing you need to do to fix this is to set the profile back to standard:

```
UPDATE variable SET value = 'standard' WHERE name = 'install_profile';
TRUNCATE cache;

```

Check out: http://davehall.com.au/blog/dave/2012/09/12/switching-installation-profiles-existing-drupal-sites

Other things that you'll probably want to do is to make sure that commerce kickstart is not in the system table in database and clearing cache and registry rebuild are a couple of extra things that won't harm.
> 0 votes

---
Tags: views, 7, commerce
---


title: SEARCH API + VIEW to search members

text:
# Question
Title: SEARCH API + VIEW to search members
I have a website in Drupal version 7.28. I have page where i want to search members by using Search option created from VIEW. It goes like this after submission:

https://domain.com/search-members?search\_api\_views\_fulltext=anything

This page and functionalty was working fine few days back but not now. Page is blank without any error. There is result in database.

I can understand above info might not be sufficient to help but my only question is:

What can cause a blank page without an error? Possible problems?

Here is the updated ERROR MSG:

PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'aeeee01\_drpl21.search\_api\_db\_user\_index\_field\_business\_phone' doesn't exist: SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM (SELECT t.* FROM {search\_api\_db\_user\_index\_field\_business\_phone} t WHERE (word = :db\_condition\_placeholder\_0) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_city} t WHERE (word = :db\_condition\_placeholder\_1) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_country} t WHERE (word = :db\_condition\_placeholder\_2) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_department} t WHERE (word = :db\_condition\_placeholder\_3) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_first\_name\_} t WHERE (word = :db\_condition\_placeholder\_4) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_job\_institution} t WHERE (word = :db\_condition\_placeholder\_5) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_job\_title} t WHERE (word = :db\_condition\_placeholder\_6) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_last\_name} t WHERE (word = :db\_condition\_placeholder\_7) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_member\_advisor} t WHERE (word = :db\_condition\_placeholder\_8) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_specialization} t WHERE (word = :db\_condition\_placeholder\_9) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_state} t WHERE (word = :db\_condition\_placeholder\_10) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_field\_zip\_code} t WHERE (word = :db\_condition\_placeholder\_11) UNION ALL SELECT t.\* FROM {search\_api\_db\_user\_index\_name} t WHERE (word = :db\_condition\_placeholder\_12) ) t GROUP BY t.item\_id) subquery; Array ( \[:db\_condition\_placeholder\_0\] =\> mlang \[:db\_condition\_placeholder\_1\] =\> mlang \[:db\_condition\_placeholder\_2\] =\> mlang \[:db\_condition\_placeholder\_3\] =\> mlang \[:db\_condition\_placeholder\_4\] =\> mlang \[:db\_condition\_placeholder\_5\] =\> mlang \[:db\_condition\_placeholder\_6\] =\> mlang \[:db\_condition\_placeholder\_7\] =\> mlang \[:db\_condition\_placeholder\_8\] =\> mlang \[:db\_condition\_placeholder\_9\] =\> mlang \[:db\_condition\_placeholder\_10\] =\> mlang \[:db\_condition\_placeholder\_11\] =\> mlang \[:db\_condition\_placeholder\_12\] =\> mlang ) in SearchApiDbService-\>search() (line 928 of /home1/aeeee01/public\_html/sites/all/modules/search\_api\_db/service.inc).

# Answer
> 0 votes
You can look into this : https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_query/7#comment-7019

https://api.drupal.org/comment/51338#comment-51338

https://api.drupal.org/comment/16974#comment-16974

And check if you made change in your taxonomy vocabulary, deleting any fields that the search would index in the views.

You can also re-index your user.

# Answer
> 0 votes
When there is an error Drupal will often show a WSOD (white screen of death), so it hides the error for security reasons.

I would recommend to rebuild the index or delete and remake the index. Also check in the fields tab of search api if all needed fields to index are checked.

If you change any fields you should always reindex.

---
Tags: search
---


# Question
Title: Using forms API - sending submitted data as an XML attachment to an email address
I need to have a request form on a D7 site which does a few different things with the form data:

* Writes to database table (standard);
* Emails a copy of the form data to a site administrator on a pre-defined email address;
* Creates a XML file attachment in a prescribed format (not valid XML, so possibly best being a template with placeholder values being replaced by form data) which is also attached to the email to administrator.

The generation of the XML is currently working fine in a bespoke PHP system and I'm thinking for ease re-using the functionality would make good sense.

However, is there a simple way to hook this into the submit process for the Drupal form? I believe using the Forms API may be the best approach?

# Answer
Just implement the hook\_form\_alter or hook\_form\_FORM\_ID\_alter and add your custom submit handler.

See this article for an intro into hooking into forms: http://websmiths.co/blog/very-introduction-drupals-hookformalter
> 1 votes

---
Tags: forms
---


title: Field permissions per content type?

text:
# Question
Title: Field permissions per content type?
I have a video field that should be visible only to authenticated users on one content type (bundle), but unrestricted on another content type.

What's a clean way to hide this field on one content type only, for anonymous users?

Notes:

1. I have the module field permissions installed, but it doesn't support per bundle field permissions.
2. I'm using Display Suite, so I'd rather not use a custom template unless that's the cleanest way to handle this one field.
3. I could create a new view mode that hides this field and and use HOOK\_entity\_view\_mode\_alter to switch to that view mode for anonymous users, but there are quite a lot fields to display so having 2 big view modes that are 95% the same seems kind of silly.

Edit: This is the code I used based on @wolverine's answer below:

```
function HOOK_utility_field_access($op, $field, $entity_type, $entity, $account) {

  //Check video field only when attached to 'lesson'.
  if ($field['field_name'] == 'field_video' && $entity_type == 'node' && $op == 'view' && $entity->type == 'lesson') {

    //Grant access only if user is logged in.
    if ($account->uid > 0) {
      return TRUE;
    }
    return FALSE;
  }
}

```

# Answer
> 1 votes
Since you want to do it for few fields, I would suggest to do it using custom code rather than any module.

You can implement hook\_field\_access($op, $field, $entity\_type, $entity, $account) and check for the "field name, content type, user, operation" and then deny or allow access.

---
Tags: entities, users
---


# Question
Title: Some content is not displaying on one of my Drupal 7 pages
I inherited a development theme and I am a Drupal newbie. I don't seem to be able to print out any new fields that I add to my content types. I put this code in node.tpl.php:

```
<?php echo render($content['field_my_text']);?>

```

I have the corresponding name in my content type. Any ideas on what could be going wrong?

Thanks!

# Answer
I figured it out. The new field was initially set to hidden inside the manage display tab of the "full content" (instead of the default).
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: Display taxonomy term description when mouse hovers
I created a taxonomy and added vocabulary with terms(each term has a description). Included the vocabulary to an auto-complete field. It all works good.

In the auto-complete field, terms appear in a drop-down menu as a list without any description.

Here, I want to add a feature for the field in such a way that when the user hovers through the terms in the drop-down menu it should display its corresponding description.

And, Also have an idea of implementing the `stackexchange Tags drop-down feature`. I like the SE approach of displaying the tags (as buttons) and its corresponding description (below the button). I'm loving it.

Either way is ok, displaying the description when mouse hovers and SE drop-down feature.

# Answer
You could try using beautytips and views. There is an old Drupal 6 video explaining how to do it for feeds, showing a part of the body when hovering the title in a list: http://www.veoh.com/watch/v200239557fzYsENz. It is still pretty much accurate on the conception of it.
> 0 votes

---
Tags: views, entities, taxonomy-terms, ajax
---


# Question
Title: How to manually delete a node from the database knowing its id
Well, look my problem is weird, I have a view that lists content of a desired type, it is listing all the content of a type, I have deleted from the drupal admin UI a node of that type, but the view is still listing the node I have deleted. If I try to access to that node from the view, I get an entityMetadataWrapperException

Now I cannot see the node in the drupal content admin UI.

I know the nid of this node (its 22) I need to delete it manually from the database, how to achieve this, is necesary a custom module or something?

Thank you very much for your help.

# Answer
You should use `node_delete`:

```
<?php
$nid='22'; // $node id , which you want to delete;
node_delete($nid);
?>

```

This function from the API does the necessary cleaning up when a node is deleted.

You can stick this in a custom module, or enable the PHP filter and just have it a node where you allow PHP code.

If you use the PHP Filter method, remember to disable it when done. You don't want it permanently enabled on a production site.

You may also want to repair your database, just to make sure. The screenshot below shows how to use phpMyAdmin to repair the `{sessions}` table. You can also use to repair the `{node}` table
> 5 votes

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


title: Regions are gone

text:
# Question
Title: Regions are gone
I work with the Omegatheme, but whenever I try to edit my regions, they are completely empty...

As you can see on the image, there are no regions available, although there is content placed inside them and on the frontend, it all looks fine.

I've flushed the cash and ran cron multiple times, but with no luck...

# Answer
> 0 votes
If you are working with a sub-theme, the regions of the parent theme are not inherited. Check out Creating a Sub-theme if this is the case.

# Answer
> 0 votes
The question is old, but maybe somebody humbles over it here from google, like me:

This can have many reasons. Without any knowledge about your setup I would assume it is a jquery issue not showing your regions. Many contrib modules want to use newer jquery versions, while Drupal core stucks on older versions. Often it is even best to have two different versions running. One for frontpage, and one for admin area. Did you try already to install jquery\_update module and play around with loaded jquery versions? In most cases that has fixed my admin area issues if some forms etc. were not showing correctly ... just my two (late) cents ...

---
Tags: 7, theming
---


title: Upload images in ckeditor for free

text:
# Question
Title: Upload images in ckeditor for free
After following instructions given here: https://drupal.org/project/ocupload#install-swfupload I got an upload button. Further it is possible to upload images within the backend. After saving the page there are visible as well.

But if I call the page in frontend there's text only.

Is there a way to solve my problem for free?

ubuntu 12.04, drupal 7.28, ckeditor 4.4.1, firefox and chromium newest release

# Answer
> 1 votes
This problem is probably related to the text format used when the page containing the image is rendered.

If the text format used is "Filtered HTML", you should try to change the format for the node to "Full HTML". If this change makes the missing images re-appear, the problem is the text format.

If *only* trusted users are allowed to insert images in nodes, you can fix the problem by changing the default text format from "Filtered HTML" to "Full HTML". However, it is not recommended to allow untrusted users use this text format, as it allows XSS attacks.

For a secure configuration where untrusted users can insert images, you need to use a better filter module that the default "Filtered HTML". You can do this by installing the WYSIWYG Filter module as is decribed here.

# Answer
> 0 votes
I use elfinder with CKEditor, and it provides a great image upload interface. It also allows you to manage files at the content overview, which is helpful.

# Answer
> 0 votes
If your image is showing up in your backend, and you are using Filtered HTML, then all you need to do is allow the tag in your Filtered HTML format. Just navigate to

```
/admin/config/content/formats/filtered_html

```

and add that tag to the "Limit allowed HTML tags" at the bottom of the form.

---
Tags: 7, wysiwyg, media
---


# Question
Title: Reset Password Form does not let user enter their new password
1. An regular registered user reset a password
2. An email with one-time link will sent to the user
3. Clicking the link will lead the user to the change password form
4. Now, the drupal site warn the user the link has been used. The user need to get another one-time link.
5. Cannot enter the reset form

# Answer
> 1 votes
Solved it by installed the Simple Password Reset module:

> Without this module enabled, core Drupal prompts the user to log in via a one-time login form. After clicking "Log in", the user is brought to their profile edit form where at long last they can change their password.
>
> With this module enabled, the user skips the one-time login form. Instead the password reset link brings them right to the profile edit form where they can immediately change their password and log in. So what core Drupal does in two steps, this module does in one.

---
Tags: 7, users
---


title: Change in core module security risk

text:
# Question
Title: Change in core module security risk
As interim solution to an issue in JavaScript, I changed the User module code, to disallow single quotation mark. I changed the following line.

```
if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {

```

After my edit, it becomes as follows.

```
if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.-]/i', $name)) {

```

One of our senior Drupal developers said that this is not an acceptable solution because it could open up the site to serious security risks and it could potentially lead to a security flaw around form injection.

I do not understand why that could happen. Can anyone explain me why?

PS. I understand that this will get overwritten on Drupal update. This was to temporarily prevent serious bug that is blocking the whole page from functioning.

# Answer
So it turns out the regexp is not for avoiding apostrophes but to allow them, you can track down the origin to this issue to 6 years ago: https://drupal.org/node/266488

> I've added apostrophe support(+test) and a small change in check\_plain() as proposed in http://drupal.org/node/165226 in the new version of the patch.

So it would be not due a security flaw but to have names with apostrophes correctly handled as you can see in the issue above:

> One of my friends is fortunate, or unfortunate, enough to have an apostrophe in his last name. Many first and last names have this, for example: O’Reilly.
>
> The crazy thing is: Drupal completely ignores this, and O'Reilly becomes OReily

The reason why this is crashing your site is hard to foresee, I stand that you might be fixing the symptoms here and not the cause by changing the regexp. Check the username databse you've got for strange chars.

If you want to have a way to modify this validation pattern, you can check this module Custom username validation.
> 0 votes

---
Tags: 7, users, security
---


# Question
Title: Setting node title as view argument/path
I'm creating a feed view that generates a specially-formatted file when nodes of a specific content type have /tsv appended to the path (generated by path\_auto)

I.e.,

**How do I do this?** I have node/%/tsv as the feed path, Node: Nid as argument (with "Node ID from URL" as the "Action to take if argument not present").

I feel there must be something really obvious I'm missing... Apologies if this has been covered before, I really did look for a solution before posting.

Thanks!

# Answer
> 2 votes
The Sub-path URL Aliases module should do what you're looking for (I use it successfully with Views arguments)...

From the module page:

> For example, if `node/1` is aliased to `content/alias`, this module rewrites the link to the node edit page `node/1/edit` to use the aliased URL `content/alias/edit` instead. This also includes Views URLs taking a node as argument (`node/%/yourview`), in short, every URL that is based on, or extends, an existing alias.

# Answer
> 2 votes
I'm not sure if I understood you question but I think the answer is:

**In Arguments set Node: Nid as argument. Then set Provide Default argument and choose NODE ID from URL.**

Here are all the steps.

You have 2 different views to your node.

1. Normal view. URL-\> mydomain.com/node/%nid/ shows your node content
2. Feed view. URL -\> mydomain.com/node/%nid/tsv shows your feed.

But when you navigate to mydomain.com/node/%nid/tsv it does not work right? So what you're asking is how you "create" this URL in order to show the feed... is that it?

If that's the case, in VIEWS2:

1. Create a new PAGE display.
2. In Page settings (bottom left corner) there's an option called PATH. Set this to node/%/tsv.
3. Still in Page Settings theres an option called menu. Set this to Menu Tab if you wish to show a tab linking to your view. | view | TSV |
4. In Arguments set Node: Nid as argument. Then set Provide Default argument and choose NODE ID from URL.
5. Validation set Basic Validation (or Node Type if the Feed is only available to certain node types)
6. In fields, select the fields you wish to show.
7. Add a filter to node published (to show only if the node is published) and a filter user role (to limit access to certain users)

And that's it... when you navigate to mydomain.com/node/%nid/tsv it shows the fields you selected.

# Answer
> 0 votes
Building on Tivie's answer and updating for views3, without using the subpath module...

I suggest using the path node/%/%/tsv instead of node/%/tsv. To do this, start by changing the replacement pattern in PathAuto for your content type to

```
node/[node:nid]/[node:title]

```

Remember to delete all aliases then do a bulk update for your content.

Note, you can use whatever path you like instead of "node" in the first position in the path. e.g. questions/\[node:nid\]/\[node:title\], cats/\[node:nid\]/\[node:title\], fish/\[node:nid\]/\[node:title\].

Your view path is now node/%/%/tsv instead of node/%/tsv. This allows Contextual Filter in Views (arguments for Views2) to work off the nid but retains the SEO friendly node title. i.e. exactly as stackexchange does in this question.

The next part creates a View that shows a single node for a content type when you visit the path node/%/%/tsv.

1. Structure \> Views \> Add new Views
2. Add a view name
3. Show Content of type your-content-type
4. In Path, set this to node/%/%/tsv. (note, "node" could be "questions", "fish", "cats", nothing, or whatever
5. Press Continue and Edit
6. On the next page, set up the format and fields as you want them to be displayed when the user visits the page. I use display suite view modes to provide different ways of presenting the content type - useful if I clone views and have several paths. e.g. node/%/%/tsv, node/%/%/images/, node/%/%/friends.
7. In Advanced, Contextual Filter, select Add, and add Node: Nid from the list.
8. In the field group "When the filter value is NOT in the URL", select Provide Default Value \> Content ID from URL
9. In the field group "When the filter value IS in the URL or a default is provided" select Specify Validation Criteria \> Content and choose the Content Type for the node
10. The Filter Value format shoud be Node ID and the action to take Show "Page Not Found"

When you navigate to mydomain.com/node/%/tsv it shows the fields you selected in the arrangement you chose with display suite modes.

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


# Question
Title: How can I send myself an email whenever a user views a Panels page?
I have a page that users rarely visit but I would like to send myself an e-mail to the effect of "UID 555 visited the special page."

My site has several hundred pages but I only want to send an e-mail for this specific page.

I thought of using rules (event: when content is viewed), but

1. this event has to be evaluated on every page hit
2. it doesn't seem to trigger when the page is embedded within a panel

So, I was wondering if there is some way to easily send myself an email with the UID whenever a user visits a specific panel page.

# Answer
> 1 votes
Add the code below to any of your module. I assumed the name of the module to be my\_module.

```
define('MY_SPECIFIC_NODE_NID', 3); // define the nid for which you want to send email

function my_module_panels_post_render($panels_display, $renderer) {
  $content = $panels_display->content;
  foreach ( $content as $key => $value) {
    if($content[$key]->type == 'node' && $content[$key]->configuration['nid'] == MY_SPECIFIC_NODE_NID){
      dpm('This is my node. I will send email here!');
      // Uncomment the line below to actually send email - remember to substitute variables appropriately
      // drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE);
    }
  }
}

```

It should work for your scenario.

---
Tags: panels, emails
---


title: Display Block only on users profile2

text:
# Question
Title: Display Block only on users profile2
I am using vies3, profile2 and context to display the users created content on their profile2 page. Using context i can allow the block to be display on the users drupal profile, how can i extend this to only show the block on the users profile2 profile?

# Answer
> 0 votes
You want to display a unique block for each user that can be publicly seen right?

Use Display Suite to put a block into a field instead of using Context.

Or, use Contextual filters in views to use the users UID, but that's more complicated and I'm not sure how to do that since I used Display suite. I found something that might help here Views and contextual filter as user id from url

# Answer
> 0 votes
We've found ourselves in the need of exactly that and we've created a Profile2 context module, it's in github but I'll post it shortly in drupal.org

https://github.com/Ymbra/profile2\_context

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


# Question
Title: EntityFieldQuery with "NOT IN" FieldCondition and "=" FieldCondition on the same multi-value field is only processing one FieldCondition
The EFQ is:

```
$query->entityCondition('entity_type', 'node')
    ->fieldCondition('field_terms_wb_access', 'tid', array_keys($children), 'NOT IN')
    ->fieldCondition('field_terms_wb_access', 'tid', $tid, '=')
    ->propertyOrderBy('title');

```

and the query being generated is

```
SELECT DISTINCT
  field_data_field_terms_wb_access0.entity_type AS entity_type,
  field_data_field_terms_wb_access0.entity_id AS entity_id,
  field_data_field_terms_wb_access0.revision_id AS revision_id,
  field_data_field_terms_wb_access0.bundle AS bundle
FROM {field_data_field_terms_wb_access}
  field_data_field_terms_wb_access0
INNER JOIN {field_data_field_terms_wb_access}
  field_data_field_terms_wb_access1
  ON field_data_field_terms_wb_access1.entity_type = field_data_field_terms_wb_access0.entity_type
  AND field_data_field_terms_wb_access1.entity_id = field_data_field_terms_wb_access0.entity_id
INNER JOIN {node} node
  ON node.nid = field_data_field_terms_wb_access0.entity_id
  WHERE  (
    field_data_field_terms_wb_access0.field_terms_wb_access_tid
    NOT IN  (
      :db_condition_placeholder_0,
      :db_condition_placeholder_1,
      :db_condition_placeholder_2,
      [...]
      :db_condition_placeholder_22
    )
  )
  AND (
    field_data_field_terms_wb_access1.field_terms_wb_access_tid = :db_condition_placeholder_23
  )
  AND (
    field_data_field_terms_wb_access0.deleted = :db_condition_placeholder_24
  )
  AND (
    field_data_field_terms_wb_access0.entity_type = :db_condition_placeholder_25
  )
  ORDER BY node.title ASC

```

However, why I include both `fieldCondition('field_terms_wb_access', 'tid', $tid, '=')` AND `fieldCondition('field_terms_wb_access', 'tid', array_keys($children), 'NOT IN')` clauses, it seems to only honor the first one and ignore the second. If I comment out the first one, however, then the second one is honored. I get no errors in the php error log or on the screen.

# Answer
This happens because EntityFieldQuery::addFieldCondition() is written like so:

```
protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  // The '!=' operator is deprecated in favour of the '<>' operator since the
  // latter is ANSI SQL compatible.
  if ($operator == '!=') {
    $operator = '<>';
  }
  if (is_scalar($field)) {
    $field_definition = field_info_field($field);
    if (empty($field_definition)) {
      throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
    }
    $field = $field_definition;
  }
  // Ensure the same index is used for field conditions as for fields.
  $index = count($this->fields);
  $this->fields[$index] = $field;
  if (isset($column)) {
    $conditions[$index] = array(
      'field' => $field,
      'column' => $column,
      'value' => $value,
      'operator' => $operator,
      'delta_group' => $delta_group,
      'language_group' => $language_group,
    );
  }
  return $this;
}

```

Note that a field condition is stored as an array in the $conditions variable, indexed by a a value that represents the field. When you add a new fieldCondition on the same field, it just overwrites the array.

I don't know if this was intentionally designed this way, or if it's a bug... but the behaviour you are seeing is exactly what the code says it should do!
> 1 votes

---
Tags: database
---


title: Add items to router but not links

text:
# Question
Title: Add items to router but not links
According to the last paragraph:

https://api.drupal.org/api/drupal/includes%21menu.inc/group/menu/7

> Everything described so far is stored in the menu\_router table. The menu\_links table holds the visible menu links. By default these are derived from the same hook\_menu definitions, however you are free to add more with menu\_link\_save()

I need to do the reverse of that, which API do I use? I need to add a record to the routing table but not couple that to an visible menu link...

The only way I can think (short of manually INSERT'ing) is to initialize a *hook\_menu* call somehow with the various paths I want and call menu\_rebuild()??? This appears to be how Panels does it...

Suggestions, opinions, etc???

***EDIT | Why isn't this code working...resulting in "The requested page "/test" could not be found."***

```
function test() {
  return 'Do something';
}

function pagegrid_menu_hook() {
  $items = array();

  $items['test'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'TEST',

    'page callback' => 'test',
    'access arguments' => array('access content')
  );

  return $items;
}

```

# Answer
Menu links are only created by default because the default `type` for a router item is `MENU_NORMAL_ITEM`:

> Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.

What you need is a `MENU_CALLBACK`:

> Menu type -- A hidden, internal callback, typically used for API calls.

e.g.

```
$items['example/feed'] = array(
  'title' => 'Example RSS feed',
  'page callback' => 'example_feed',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

```

That will create you an accessible path with no menu links, unless of course you add them manually through code or the UI.
> 0 votes

---
Tags: routes
---


# Question
Title: is there hierarchical user level structure in drupal
Is there any hierachical structure of user in Drupal?
I just see user role in drupal, but can we define some level of user?
As example:

```
user1
--user2
---user3
--user4
---user5
---user6

```

# Answer
> 3 votes
Check out Subuser module to see if it fits your needs.

If you want "just" the roles to be hierarchical, Role delegation might be useful

Related: https://stackoverflow.com/questions/1281964/drupal-for-users-creating-sub-users

# Answer
> 1 votes
For handling hierarchies, I prefer to use organic groups and sometimes og\_subgroups. This gives you hierarchies of groups rather than hierarchies of users, but I have used this, for example, to make a hierarchy of "officers", and other group members are the officer's assistants. The other advantage of hierarchy of groups over a hierarchy of users is that it is possible for one user to appear at multiple places in the hierarchy, if necessary.

---
Tags: users
---


title: Scope of constants in drupal

text:
# Question
Title: Scope of constants in drupal
I am connecting to a third party library to connect to authorize.net. In order to begin making any calls to the library, you must first define some constants, such as:

```
define("AUTHORIZENET_API_LOGIN_ID", "[LOGIN ID HERE]");
define("AUTHORIZENET_TRANSACTION_KEY", "[TRANSACTION KEY HERE]");

```

My issue is this: I have two separate Authorize.net accounts which need to be updated, both happening as the drupal user saves his account. Currently I have one custom submit handler added to the user\_update\_form form but I can't use this to make both calls. Should I be able to simply make a separate submit handler for each account, or will the constant be constant though both files?

# Answer
> 1 votes
This is more a PHP question than a Drupal one...

Global constants cannot be re-declared within the same request (well, short of using an extension: https://stackoverflow.com/questions/8465155/redefine-constants-in-php).

Since everything in Drupal 7 and below is in the global scope, you can't redeclare those variables within the same request.

If it's hard-coded and causing you a problem, a patch to the module in question to allow contextually different API credentials would be the best thing to do IMO.

---
Tags: forms
---


# Question
Title: To show custom user fields in a view does not work for user with uid 1
I have a view that shows some custom user fields as block on the users profile page. The permission of that view is set to »Access: Permission | View published content«. That means the view should be visible for any visitor. This works fine on any user profile but not on the profile of the administrator with the uid 1. On his profile page the view is empty. Is this a bug or a wanted behaviour? How to solve this?

UPDATE: I tried to solve this by changing the view's access permissions but even if I set them to »none« or »Roles | All« it does not work.

# Answer
> 0 votes
Try using "Access: Role" rather than "Access: Permission" and select all user roles (that you'd like to be able to see the view ...

---
Tags: views, users
---


title: debuging drush with xdebug

text:
# Question
Title: debuging drush with xdebug
I'm trying to debug a segmentation fault (11) from drush. I have xdebug installed. The command it's giving the error is the pm-disable.

$ drush dis "module" --debug --verbose: ...

Calling hook drush\_pm\_disable \[11.17 sec, 84.08 MB\] \[debug\] Segmentation fault: 11

I think the issue is when it is calculating the dependencies, as I was also getting this on features/create, but disabling the dependencies checkbox in the features settings makes the features/create work well.

# Answer
> 2 votes
If the question is how to debug drush, you could use your IDE in the commands file you've got the command in pm.inc most probably, and use xdebug with the idkey, i.e.

```
xdebug.idekey="PHPSTORM";

```

See debuging drush with xdebug for more information

Also related: Can Xdebug be triggered by Drush commands?

---
Tags: drush
---


# Question
Title: Error with drush clear-cache: Base table or view not found
There are similar questions out there, but I think this warrants a new thread.

I am getting the following error when running drush clear-cache all

PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'dbname.cache\_rules' doesn't exist: TRUNCATE {cache\_rules} ;"

However, when I run the show tables command on the database, it clearly lists the cache\_rules table.

Any ideas what is going on here and what I can do to fix it?

# Answer
> 3 votes
Here is how to reset your cache\_rules table, using a stable Drupal installation.

# Get cache\_rules structure from clean database

You can get SQL text to drop/add the cache\_rules table via the following steps:

1. Log in to phpMyAdmin on a functional Drupal site.
2. Click on the **columns** section under the **cache\_rules table**
3. Click the **Export** button
4. Click '**Custom**' to show all options
5. Under 'Output' click '**view output as text**'
6. Under 'Format-specific options' choose '**structure**'
7. Under 'Object creation options' check '**Add DROP TABLE / TRIGGER statement**'
8. Copy the text displayed, or see below (sorry for the formatting)

Here is the SQL code to drop and add the table (thanks duckx!).

```
DROP TABLE cache_rules ;
CREATE TABLE IF NOT EXISTS `cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';

```

# Drop/add the cache\_rules table

Now navigate to the other database, using phpMyAdmin.

1. Make a full backup of the database
2. After the backup has been saved, click the **SQL** tab
3. Paste the text into the text box (removing any existing text)
4. Click '**Go**'

# Answer
> 1 votes
Here's the code to run where it drops and adds the table back:

**REPLACE XX WITH YOUR OWN TABLE NAME....**

```
DROP TABLE XX_cache_rules ;
CREATE TABLE IF NOT EXISTS `XX_cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';

```

# Answer
> 0 votes
Based on the two comments above, I ran mysqlcheck and confirmed the table was missing, even though the "show columns" command displayed it.

Then I went into /var/lib/mysql and removed all references to the table.

Logged into mysql and ran the drop table command for good measure.

And finally recreated the table. I referenced a working database to correctly model the table.

---
Tags: 7, drush
---