title: D7-import View break blocks PDOExeption

text:
# Question
Title: D7-import View break blocks PDOExeption
I accidentally deleted a view in my D7 website. Good for me I had backup from yesterday, so I put that on my local drupal and exported the view.

The View is getting added successfully but when i visit a node where the view should appear it doesn't and the block panel of the website returns this:

```
Notice: Undefined index: kontakt-block_1 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
Notice: Undefined index: kontakt-block_2 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
Notice: Undefined index: kontakt-block_4 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
Notice: Undefined index: kontakt-block_6 in _block_rehash() (Zeile 420 von /var/www/drupal-7.19/modules/block/block.module).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'rubel_zf-views-Kontakt-block_1' for key 'tmd': INSERT INTO {block} (module, delta, theme, status, weight, region, pages, cache) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => views [:db_insert_placeholder_1] => Kontakt-block_1 [:db_insert_placeholder_2] => rubel_zf [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => -1 [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => -1 ) in drupal_write_record() (Zeile 7194 von /var/www/drupal-7.19/includes/common.inc).

```

If I delete the View again the blocks panel opens without a error.

any idea how I can fix this? A lot of work was done in the meantime and the bad thing not only by me. Other employees did add content. All that well be gone ;(

# Answer
First back up the live site in its current state.

On your local site running your backup database enable the database administration module

And use that to export the tables labeled 'views\_views' and 'views\_display' in format 'mysqldump'

On your live site, import your sql files

Then run:

```
mysql -u root -p drupaldb < views-views.sql
mysql -u root -p drupaldb < views-display.sql

```

I used this issue thread for reference.

It's worth noting that because your errors also seem to be coming from blocks (and assuming no one else has worked on them in the meantime) you might also want to do the same as above with your 'block' 'block\_current\_search' 'block\_custom' 'block\_node\_type' 'block\_role' tables.
> 0 votes

---
Tags: 7, views, blocks, importing-exporting
---


# Question
Title: Is it possible to create sub-node that can assign on a node?
The idea is to create a chapter(sub-node) that can assign on a book(node:page). I know this can be done with taxonomy, but I dont wanna have 1000+ of taxonomy on my site. Is it possible, if so, how?

# Answer
> 1 votes
Do you mean you want a Book that has chapters and you want them linked like a book? There is a module for that in Core called book. https://drupal.org/documentation/modules/book

---
Tags: nodes, 7
---


# Question
Title: How to display an image field next to the title on the profile pages?
My users have an image field, called 'Avatar', that's displayed as an icon. I can easily add it to the users' profile page in the content section, but now I'd like to show it next to the title (the default one prints the username).

As I didn't try to do this before, I surfed around the internet for a while. It seems that lots of similar requests were solved by a template file. Therefore, my plan was to add a `user-profile.tpl.php`, copy all the code from `page.tpl.php` to it and add

```
<?php
print render($user_profile['field_avatar']);
?>

```

before the title.

I'm not sure whether this might work. Is this a good approach?

# Answer
> 0 votes
Greatly thanks to @Michiel, I've been able to get this working with the following code:

```
function MYMODULE_process_page(&$vars, $hook) {
 if(arg(0) == 'user'){
  $user = user_load(arg(1));
  $image = array(
   '#theme'  => 'image',
   '#path'   => file_create_url($user->field_avatar['und'][0]['uri']),
   '#attributes' => array('class' => 'avatar_title'),
  );

  $vars['title'] = render($image) . $vars['title'];
 }
}

```

It's important not to use `global $user` instead of `user_load(arg(1))`, because the custom user fields aren't loaded in the first case (see: http://davidsonj.com/blog/global-user-vs-userload). Therefore, you'll get the error that `field_avatar` is undefined.

Thanks to the `avatar_title` CSS class, you can theme the image any further to your needs.

# Answer
> 2 votes
The use of the template is solid guess. However, you're using the wrong template. The template you suggesting isn't based on the `page.tpl.php` page. The output of the `user-profile.tpl.php` page, will end up in the `$content` section of your page template. You should try to use a different approach.

How about a preprocess function? It will intercept the rendering of the variables and by so, you can alter them. If you want to change the title of your user-profile page, I'ld go with something like this:

```
/**
 * Implements hook_process_page().
 */
function mymodule_process_page(&$vars, $hook) {
  // Load the global user object
  global $user;

  // Check if it's the userpage and the current user, depending on URL
  if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] .= ' ' . $user->avatar[LANGUAGE_NONE][0]['value'];
  }
}

```

Above preprocess function should be placed in your preprocess folder of your theme or the `template.php`.
It will extend the existing title with your extra fieldvalue.

There is only one drawback on this implementation. If you have a page with a path like `/user/overview`, the title will change too. Every URL with `user` as first argument and a UID as second, will be altered...

Goodluck!

***EDIT:*** Try this please and let me know how it went:

```
/**
  * Implements hook_process_page().
  */
function mymodule_process_page(&$vars, $hook) {
    // Load the global user object
    global $user;

    $image = array(
      '#theme'  => 'image',
      '#path'   => file_create_url($user->field_avatar[LANGUAGE_NONE][0]['uri']),
      '#width'  => 20,
      '#height' => 20,
    );

    if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] = render($image) . $vars['title'];
    }
}

```

# Answer
> -1 votes
I'm pretty sure the file to copy is modules/user/user-profile.tpl.php and put it in your theme folder https://api.drupal.org/api/drupal/modules%21user%21user-profile.tpl.php/7 and make the changes in that.

---
Tags: 7, theming, users
---


# Question
Title: How to use a view block in a dropdown menu item?
I'd like to create a menu item that generates a dropdown menu with unread messages. I've already used Nice Menus for flyout menus, but I don't think that module supports what I'm looking for: the dropdown should be a view block and should appear when the user hoovers the 'block' in the menu bar.

Is there a module that makes this possible?

# Answer
> 4 votes
Try out for following modules

Menu Views

> Allows menu items to render views instead of links. This is useful for creating "mega-menus".

Menu Attach Block

> Menu Attach Block allows you to attach blocks to standard core Drupal menu items. This is especially useful for creating complex dropdown menus and mega menus.
>
> Any block can be used, including blocks generated by other modules. Blocks generated by Views are particularly good candidates for embedding.

# Answer
> 1 votes
I recently had to put blocks, views block, lists and videos into a menu, and used tb\_megamenu. It was great. And there's a clear tutorial on all its features on youtube, and quick guide here.

---
Tags: 7, views, routes, blocks, navigation
---


# Question
Title: Corrupted mysql cache_rules table - dropped the table and now I cannot create it anymore!? Stuck
I'm not sure how this happens, but the cache\_rules table is corrupted and it prevents me from doing a drush cache clear all. I dropped the table successfully, but now I can't create it. Throws this error:

```
ERROR 1005 (HY000): Can't create table 'cache_rules' (errno: -1)

```

Luckily i have my db backed up and don't have to lose too much data. Now I tried to drop my entire database and that's not working neither. It does in fact drop all the tables, but it prevents the database from getting dropped entirely.

# Answer
> 0 votes
I tried dropping the database multiple ways. via command line and phpmyadmin. none of that worked.

What did work was going into the database files directory and deleting it manually. These mysql database tables are just regular files you can delete. Mine were located here: **/var/lib/mysql/**

here's what i did:

After that I was able to recreate the table via mysql command line. just copy and paste this to recreate the table with the schema:

```
CREATE TABLE `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.';

```

---
Tags: rules, database, caching
---


# Question
Title: Creating default object from empty value
I am having issues with a template - in the template.php there is code causing a warning:

Warning: Creating default object from empty value in theme545\_preprocess\_html() (line 31 of /home/noramtow/public\_html/sites/all/themes/theme545/template.php).

The line in questions is this:

```
$vars['rdf']->version = 'version="HTML+RDFa 1.1"';

```

The whole section of code looks like this:

```
function theme545_preprocess_html(&$vars) {
if (module_exists('rdf')) {
$vars['doctype'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">' . "\n";
$vars['rdf']->version = 'version="HTML+RDFa 1.1"';
$vars['rdf']->namespaces = $vars['rdf_namespaces'];
$vars['rdf']->profile = ' profile="' . $vars['grddl_profile'] . '"';
} else {
$vars['doctype'] = '<!DOCTYPE html>' . "\n";
$vars['rdf']->version = '';
$vars['rdf']->namespaces = '';
$vars['rdf']->profile = '';
}
$vars['classes_array'][] = 'body';

```

I'm not great with PHP - anyone have any idea how to fix this or what's causing it?? Thanks for any help you can give!! Candace

# Answer
It sounds like your system wants to make sure $vars\['rdf'\] is a valid object before assigning properties to it.

Try adding:

```
if (empty($variables['rdf']) || !is_object($variables['rdf'])) {
  $vars['rdf'] = new stdClass();
}

```

Just above your line 31.

For safety's sake, add it above

```
if (module_exists('rdf')) {

```

That way the object will get initialized regardless of whether the RDF module is enabled or not.
> 0 votes

---
Tags: theming
---


# Question
Title: Services Views and combine different field values into one?
I got a site with a profile2 type and a content type that uses the same field containting coordinates (field\_coordinates).

I'm using Services Views to show these coordinates in JSON but this is where I ran into some problem. I want only one field set of these coordinates visible, but I have to chose the relationship of the field: either no releatinship shows the node coordinates, or the relationship with the profile shows the profiles coordinates.

There will never be two sets of coordinates per output node (in one case the are requested from the node, and the other case from the profile). The JSON output cant show two fields with the same label so I have to have two different names: one for profile coordinates and one for node coordinates.

**The issue is that I want only one coordinate field, and therefore added a global text field, where I put both of the place holders from the other coordinates. But this global text field output wont show in my Services view. Why is that?**

# Answer
Try taking one field and hiding it with views then if the next field is empty pull that one in there?
> 0 votes

---
Tags: views, services
---


# Question
Title: Add additional fields to the postal address
How can I add additional fields to the *Address Field* module's *Postal address* field? I would like to add a field for the county.

The default fields for the United States are the following.

>

# Answer
I'm pretty sure there is a configuration in the field settings. If not in there I'd look at the module's config screen.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to create a custom 'fluid' layout in Display Suite
I created a Display suite custom layout following this tutorial: https://drupal.org/node/1098068

It works fine, but I need this custom layout to be Fluid.

> In Display Suite, the "fluid" refers to the templates ability to expand the column width if one (or more) columns are empty.

How can I do this? I guess I need to add some php code which will add some extras css classes. But I don't know how and where to add this code.

# Answer
Just select the custom layout in the *Manage Display* page:

And add the required CSS in your theme. See the examples included in Display Suite:
> 1 votes

---
Tags: display-suite
---


# Question
Title: How to print a CCK image field alt text in a node template?
I'm trying to add the alt text from a cck image field in a Drupal 7 node template. Getting the image style url is done, but I can't figure out how to just get the alt text. This is what I have

```
<img src="<?php print image_style_url('160x160', $node->field_image['und'][0]['uri']); ?>" alt="????" class="thumbnail" />

```

How does one just output the alt text?

# Answer
> 1 votes
If you install the Devel module, you'll be able to use:

```
<?php dpm($node); ?>

```

It will provide all available fields that you could use. Another method might be to use `theme('image')` to help clean up your image theming.

# Answer
> 0 votes
A print\_r will give you idea. In your case it will be

```
$node->field_image['und'][0]['alt']

```

ie: `<img src="<?php print image_style_url('160x160', $node->field_image['und'][0]['uri']); ?>" alt="<?php echo $node->field_image['und'][0]['alt']; ?>" class="thumbnail" />`

---
Tags: nodes, theming, entities, media
---


title: Theme a node form

text:
# Question
Title: Theme a node form
I'm attempting to theme a node add form for my new slide show content type in D8 using an example for D7 that I found here, but I'm not having much luck.

I've made and enabled a module named modulename, and have this in modulename.module:

```
function modulename_theme($existing, $type, $theme, $path) {
  return array(
    'slide_show_node_form' => array(
      'render element' => 'form',
      'template' => 'slide-show-node-form'
    ),
  );
}

```

and in `modulename/templates/slide-show-node-form.html.twig` I have this:

```
test
<div class="layout-node-form clearfix">
  <div class="layout-region layout-region-node-main">
    {{ form|without('advanced', 'actions') }}
  </div>
  <div class="layout-region layout-region-node-secondary">
    {{ form.advanced }}
  </div>
  <div class="layout-region layout-region-node-footer">
    {{ form.actions }}
  </div>
</div>

```

But, no luck on getting `test` to print out on the node add page. Any ideas on what I'm missing?

# Answer
> 0 votes
Try this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(array &$form, array &$form_state, $form_id) {
  $form['#theme'] = 'slide_show_node_form';
}

```

# Answer
> -1 votes
Try adding something like the following to the top of your `modulename/templates/slide-show-node-form.html.twig`

```
{#
/**
 * @file
 * Override for Slide Show Node Form 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}

```

(based on the default located at `/core/modules/system/templates/form.html.twig`) and the suggestions for Drupal Twig conversion instructions

---
Tags: nodes, forms, theming, 8
---


# Question
Title: Include Entity Reference values to term page Solr results
I would like to index the value/s from EntityReference, to be included in Solr results.

Example, My entityreference field has nodes "Foo" and "Bar" in "Lorem Ipsum" taxonomy term.

I'm using Solr to render my Taxonomy page.

Is there a chance to include "Foo" and "Bar" to my "Lorem Ipsum" Solr results and sorted properly (in order)?

So it is like merging Entity Reference values and Solr results.

# Answer
> 0 votes
Here's what I did to merge entity reference nodes to Solr results (Solr-generated taxonomy terms)

I did a \_term\_load()\_ on \_theme\_preprocess\_search\_results()\_ to pull all the entities from *entity reference* field and load them using \_entity\_load()\_ and get the renderable array by using \_entity\_view()\_ and render it by *render()*.

After assigning those referenced nodes into a variable, I printed the variable in *search-results.tpl.php* above the \_$search\_results\_.

It should display the referenced nodes into Solr page, above the actual Solr results.

*To prevent displaying the node twice*, I filtered all nodes from entity reference field not to show in current Solr page.

```
foreach ($term->field_article_reference[LANGUAGE_NONE] as $key => $val) {
  // Exlclude items that is already in term's entity reference field.
  $excluded_ids[] = $val['target_id'];
}
foreach ($excluded_ids as $excluded_id) {
  $query->addFilter('entity_id', $excluded_id, TRUE);
}

```

To maintain the total number of rows, here's what I did.

```
// To get rows variable subract 11 from the total number of reference
// items, first page should start with first item 0.
// Start variable should be the product of $rows and the page number, if
// page number exists. And it should always shows 11 total rows.
$total_rows = 11;
$param = drupal_get_query_parameters();
if (empty($param['page'])) {
  $rows = $total_rows - count($term->field_hero_stories[LANGUAGE_NONE]);
  $start = 0;
  $query->addParam('start', $start);
  $query->addParam('rows', $rows);
}
else {
  $rows = $total_rows - count($term->field_hero_stories[LANGUAGE_NONE]);
  $start = $rows * $param['page'];
  $query->addParam('start', $start);
  $query->addParam('rows', $total_rows);
}

```

Note: Maximum items from reference field *should not be equal nor more than to the total number of rows*.

---
Tags: entities, search
---


# Question
Title: Create field collection item in drupal 7
I am trying to dynamically create a field collection for a node.

Field collection item (field\_markers) is used to create a point or a polygon for a map content type.

During debugging I found that my code create an entry for all the member elements of field collection but it does not create or update a record for field collection itself.

I have referred to https://stackoverflow.com/questions/6242018/dynamically-add-a-field-collection-in-drupal-7-by-script but was not able to resolve my problem.

Following is my code so far.

```
//Create field collection
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_markers'));

//Create fields related to field collection
$field_collection_item->field_title['und'][0]['value'] = "Brian 22";
$field_collection_item->field_summary['und'][0]['value'] = "Test entity creation.";
$field_collection_item->field_summary['und'][0]['format'] = "filtered_html";

$lat = -35.3241665257384;
$lon = 139.8046875;

$field_collection_item->field_coordinates['und'][0]['wkt'] = 'POINT ('.$lon.' '.$lat.')';
$field_collection_item->field_coordinates['und'][0]['geo_type'] = 'point';
$field_collection_item->field_coordinates['und'][0]['lat'] = $lat;
$field_collection_item->field_coordinates['und'][0]['lon'] = $lon;
$field_collection_item->field_coordinates['und'][0]['left'] = $lon;
$field_collection_item->field_coordinates['und'][0]['top'] = $lat;

$field_collection_item->field_coordinates['und'][0]['right'] = $lon;
$field_collection_item->field_coordinates['und'][0]['bottom'] = $lat;

//attach field collection to map content type
$field_collection_item->setHostEntity('map', $node);
// Save the entity.
$field_collection_item->save(TRUE);

```

# Answer
I found the problem, it was related to the workflow of content publishing (specific to my site ). Field collection item is created after a user with required permissions approve the content.

The code in question works and could be helpful for anyone else trying to create a field collection item containing a geofield.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: how to hide the adminblog link in the teaser
how to remove admin\`s blog in footer of teasers i can remove the add comment link with this code :

```
function  mytheme_node_view_alter(&$build){
if ($build['#view_mode'] == 'teaser')
{
    // remove "add comment" link from node teaser mode display
    unset($build['links']['comment']['#links']['comment-add']);

    // and if logged out this will cause another list item to appear, so let's get rid of that
    unset($build['links']['comment']['#links']['comment_forbidden']);
}

```

but i can`t remove admin`s blog what can i do ?!

# Answer
> 5 votes
Try to use something like the below code to hide admin's blog from teaser's view in your theme's template.php, hope it will work for you:

```
function THEME_preprocess_node(&$variables) {
      if ($variables['view_mode'] == 'teaser') {
        if ($variables['type'] == 'blog' && (arg(0) != 'blog' || arg(1) != $variables['uid'])) {
          unset($variables['content']['links']['blog']['#links']['blog_usernames_blog']);
          unset($variables['content']['links']['node']['#links']['node-readmore']);
        }
      }
    }

```

# Answer
> -1 votes
Check out the module Tab Tamer

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.

---
Tags: theming, users, nodes
---


# Question
Title: Is there any method (function) in drupal which gets called after nodes being created.
I am creating a custom module for Drupal 7. I wanted to post the node that gets created of type "Article" to facebook wall so that user doesn't have to manually create a wall post.

For that I need to get a method (function) in drupal which gets called as soon as the nodes gets created, where I can put my Facebook API codes.

# Answer
> 2 votes
You are looking for `hook_node_insert()`

This is from API page:

> Respond to creation of a new node.
>
> This hook is invoked from node\_save() after the database query that will insert the node into the node table is scheduled for execution, after the type-specific hook\_insert() is invoked, and after field\_attach\_insert() is called.

```
function MyModule_node_insert($node) {

  if($node->type == 'article') {
    //your code here
    custom_func();
  }
}

function custom_func() {
  //your code goes here
}

```

# Answer
> 0 votes
Another way to achieve this goal is http://twitterfeed.com. It allows you to export RSS (generated by views) to several social networks, including Facebook.

# Answer
> 0 votes
In most cases

```
 hook_node_insert();

```

does the job. The hook\_node\_insert() is called before actual database write query so you cannot retrieve nid from that node. Another hook called *after* saving node is:

```
hook_node_postinsert();

```

Available after installing module

https://drupal.org/project/hook\_post\_action

---
Tags: 7, social-network
---


# Question
Title: how to get the translated taxonomy term programmatically?
I have tried this

```
$term = taxonomy_term_load($tid);

```

and this:

```
$term = i18n_taxonomy_localize_terms(taxonomy_term_load($tid));

```

Both return the default language (English) term

I am using D7.

# Answer
> 8 votes
Try

```
$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_term_get_translation($term, $langcode);

```

Also, a good place to look for more information: /sites/all/modules/i18n/i18n\_taxonomy/i18n\_taxonomy.module

# Answer
> 2 votes
1. Create translation sets (taxonomy example)

To translate a string, you should use two functions, depending on which i18n mode you use:

Localize mode: i18n\_string\_translation\_update()

```
<?php
  $result_translation = i18n_string_translation_update(
    array('taxonomy', 'term', $tid, 'name'), // Path where to store source and translation.
    $translated_string,
    $language,
    $source_string
  );
?>

```

Translate mode: i18n\_translation\_set\_create()

```
<?php
  // 1. Load or create a translation set.
  $translation_set = ($source_term->i18n_tsid) ?
    i18n_translation_set_load($source_term->i18n_tsid) :
    i18n_translation_set_create('taxonomy_term', $vocabulary->machine_name);

      // 2. Add the full source term in this set.
  $translation_set->add_item($source_term, $source_term->language);

      // 3. Add the full translated term in this set.
  $translation_set->add_item($translated_term, $translated_term->language);
  $translation_set->save(TRUE);
?>

```

Strings for other contents and modules

When a module defines its own strings, it must use some additional functions to allow these string to be tracked and updated.

Define the textgroup by implementing `hook_i18n_string_info()`. This is how it looks (i18n\_taxonomy module)

```
<?php
/**
 * Implements hook_i18n_string_info()
 */
function i18n_taxonomy_i18n_string_info() {
  $groups['taxonomy'] = array(
    'title' => t('Taxonomy'),
    'description' => t('Vocabulary titles and term names for localizable vocabularies.'),
    'format' => FALSE, // This group doesn't have strings with format
    'list' => FALSE, // This group cannot list all strings
    'refresh callback' => 'i18n_taxonomy_i18n_string_refresh',
  );
  return $groups;
}
?>

```

Read more at: Using the i18n API from other modules

Related:

How to associate programatically the translation of new term to the original existing term?

# Answer
> 0 votes
i18n\_taxonomy\_localize\_terms works on getting site language

please check Home » Administration » Configuration » Regional and language » Languages to ensure the site language detection is working as you wanted

i got this done when site languages change on user language preference

# Answer
> 0 votes
Here is how to rewrite the Finder menue display with localized tayonomy terms:

```
<?php
$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('name', $display)
->propertyCondition('vid', 3) // Change this to Your ID!!
->execute();

$found_tid = array_shift($result['taxonomy_term'])->tid;
// print $found_tid;

$tid = $found_tid;
$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_localize_terms($term);
print $translated_term->name;
?>

```

---
Tags: taxonomy-terms, i18n-l10n
---


title: How to show view item by trimming?

text:
# Question
Title: How to show view item by trimming?
I'm trying to show articles by trimming. So, first I tried it by managing the display of body field to trimmed from content type. After fail to get desired results I tried it with views module by adding a contextual filter **Content: Body** setting character limit to 200 but did nothing.

I would like to hear the answer from this module as I also have the contextual filter: **Content: Has taxonomy term ID** already in this view.

---

> **Update:**

**I want to add a view of taxonomy terms where I have created a view with contextual filter previously to which taxonomy term name is linked in this view:**

In which taxonomy term is there:

And I tried with `Trim this field to a maximum length` too but couldn't success.

# Answer
> 0 votes
You wont get anywhere triiming in a contextual filter, you need to click on the field and use the rewrite results fieldset in your fields settings.

Simply enter a maximum length, and choose extras like an ellipsis "..." to text that is cut off.

You may also need to change the format to plain text. Or choose a trimmed format.

# Answer
> 0 votes
You can use either of option here for trimming the body.

If you use **option 2** and dispaly body as default text Formatter then better to enable `Field can contain HTML` option that ensure tags are properly closed after trimming.

For term field in taxonomy term view:

---
Tags: 7
---


# Question
Title: Custom editable, translatable email templates
I need to send many different emails to drupal users. How can i add custom editable & translatable email templates? Something like user emails?

I have tried "Mail Editor" module, but i don't know how to add custom emails. Perhaps this is not the right solution?

thanks in advance

# Answer
> 0 votes
Using Mail Editor you can add custom emails by going to admin/config/system/mail-edit

Did you try doing that?

Regarding translation at - /admin/config/regional/language/configure there is a 'Follow the user's language preference.' option.

---
Tags: users, emails
---


# Question
Title: hook_form_alter #attributes and #disabled
I'm using Drupal 7 and Advanced forum.

The users when will create a new topic will be able to select the forum container and forums, but if they select a container, an error will be showed. I want to avoid this by altering that taxonomy options with adding an #attribute or #disabled to specific forum container.

As I inspect the elements, this is the option that I want to change:

`$form['taxonomy_forums']['und']['#options'][334];`

First of all I've tried to test by adding a class for that option like this:

```
$form['taxonomy_forums']['und']['#options'][334]['#attributes'] = array('class' => array('test-class'));

```

but that didn't worked, it simply erases the title of that option.

With #disabled it didn't work too.

From https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#attributes

I can see a good example, but also a note:

> Note: If you are altering an existing form via hook\_form\_alter() or a similar means, be careful with this property! You will probably want to add to the existing array rather than writing over it, so don't follow this usage example exactly.

It's kind a confusing, so how can I add an #attribute or #disabled to option with hook\_form\_alter?

EDIT: This is a part from my code:

```
<?php
function custom_alter_form_alter (&$form, &$form_state, $form_id) {
   switch ($form_id) {

        case 'forum_node_form';

        $form['taxonomy_forums']['und']['#process'][] = 'custom_alter_process_checkboxes';
        krumo ($form);
        break;
    }

}

function custom_alter_process_checkboxes($element) {
  $element[334]['#attributes']['class'][] = 'test-class';
  $element[334]['#disabled'] = TRUE;
  return $element;
  krumo ($element);
}

```

# Answer
Checkboxes are converted to their individual form elements in `form_process_checkboxes ()`, so you'll need a process function:

```
// In the form alter...
$form['taxonomy_forums']['und']['#process'][] = 'MYMODULE_process_checkboxes';

function MYMODULE_process_checkboxes($element) {
  $element[334]['#attributes']['class'][] = 'test-class';
  $element[334]['#disabled'] = TRUE;
  return $element;
}

```
> 0 votes

---
Tags: taxonomy-terms, forms, hooks
---


# Question
Title: Using views to display content comparing users id
First of all, sorry for my bad english.

I'm using Drupal 7

Here is my problem :

I have a views in wich I would like to display a list of custom content type **only** for the users that I selected with a custom field "entity ID" in this custom content type. This users share the same role, but they can't see the node of others users (of the same role or another role as well).

I taught the simplest method would be to add some PHP code thanks to the PHP views module, but if you have a better solution I'll love to hear that.

So this is what I made so far:

I added a global PHP in the filters criteria section of the view with this code:

```
global $user;
$current_user = $user->uid;
$destiny_user = $data->field_field_uttilisateur[0][raw][entity]->uid;

if ($current_user == $destiny_user) {
   return false;
} else {
   return true;
}

```

Basicaly I'm comparing the current user ID with the ID I filled in the content type. If this "function" returns true, then the current row is not displayed.

I don't have to worry to know if the user is authentified because I already do that in Page settings (Access)

But it seems like $destiny\_user is always empty. I don't get it because when I add an global php field in the fields section all seems ok (I can see the ID of the user I whant to display the row)

I'm using this method $data-\>field\_field\_uttilisateur\[0\]\[raw\]\[entity\]-\>uid; because the $rows-\>field\_uttilisateur; is not working. (It display the nid Oo) After some research I found this solution that seems to work... at least more than the other one.

I'm having a really bad time with this, do you have some ideas how I can get this to work?

Thank you in advance !

# Answer
This can be achieved using contextual filters in views. Here are the steps:

1. In the views edit page click on Advanced section.
2. Click on the Add button corresponding to "Contextual Filters"
3. Search for your custom field in your custom content type and add it.
4. In the configure contextual filter which appears make the following changes. Under "When the filter value is not in the url" section, select the option "Provide default value". In the type select list, select the option "User ID from logged in user".
5. Save the changes.
> 0 votes

---
Tags: users, views
---


# Question
Title: Copy taxonomy term name to another field
I need coordinates for each term in a cities taxonomy I got one a site for one of my clients. I found Geofield, which I use on nodes on that very same site, and it works as it should. However in my city taxonomy Geofield has a bug that makes it unable to get coordinates based on a title, which the term name is.

So I figured that I might copy the value of the title into another field for a term - like Title Copy field, and then base Geofield coordinates by that. Now, I don't know how..

I've found Computed Field which I find to complex for this, Tokens I don't get to work, Reference auto fill needs yet another source field so it goes away.

Any ideas for a simple solution that will work with terms created from both the taxonomy UI AND when nodes add new terms from a Autocomplete field?

# Answer
I am assuming you have a content type with a field "Title" of type "Term Reference"... and you want to pass an address from this existing field to a hidden field for Geo coding or whatever else for that specific page.

I would suggest using views and entity reference to do this. This method is useful for passing multiple fields, but can be used to grab just one...

Once you have the Entity Reference module enabled and installed create a view. For the view's display options (that + sign) add 'Entity Reference'.

Add a field to this view of type: "Content: All taxonomy terms"

In the next options screen you can limit the options here to your specific 'Cities' vocabulary.

You now need to add a contextual filter 'Content:NID' to get this view to only display the city term reference for the page that it's on.

Now go back to your content type and add a field of type 'Entity Reference'. Configure it like this:

* Target Type - Node
* Mode - Views (filter by an entity reference view)
* View used to select the entities - 'my entity reference view'

Now add your Geofield and configure it to 'Geocode from another field' - i.e. your entity reference field (which you can hide in the display options)

In the event that a city name alone is insufficient to geocode from consider adding other fields to your content type and passing them to your entity reference view.
> 1 votes

# Answer
What I did was to use Rules.

1. Create a text field to be used for the copied value from name/title of the term (aka "copy field" for now).
2. Create a geofield that bases the coordinates from the copy field.
3. Create a rule that will be run before a taxonomy term is saved.
4. Set an action that copies the value of name/title field to your copy field.
5. Create a action to run some PHP code and add: taxonomy\_term\_save($term);
6. Save the rule.
7. Save a taxonomy and it will copy the name/title to the copy field and get the coordinates from that field.
> 0 votes

---
Tags: entities
---


# Question
Title: How to create a new table in drupal without uninstall/installing the custom module
In my requirement i want to create new table without uninstalling and installing the module.. is there any way to do it...?

# Answer
> 2 votes
The proper way to do this is to simply implement `hook_update_N()` and manually add the table that you've added to `hook_schema()`:

```
/**
 * Add the foo table.
 */
function MYMODULE_update_7100() {
  $table_name = 'table_name';
  $schema = drupal_get_schema_unprocessed('MYMODULE', $table_name);
  db_create_table($table_name, $schema);

  return $table_name . ' table created.';
}

```

That goes in your module's .install file along with the schema hook, and you'll need to run `drush updb` (or run through the UI at /update.php) for the changes to take effect.

# Answer
> 0 votes
You can create any table you want in any database with your favourite database management tool such as *phpMyAdmin*. How you do it is explained on this page, but to summarize:

After you've logged in on *phpMyAdmin*, on the left hand side you will see "phpMyAdmin" logo, some small icons, and below them you will see your database name. Click on the name of the Drupal database (you can find its name in `settings.php` if you don't know what name it has). On the right hand side any tables you may have in your database will be displayed, as well as a box labeled "Create new table on database"

Click this and create the table you want. You can then proceed to populate the table with the fields you need.

Or just create the table by way of the command line interface to the datebase.

---
Tags: installation
---


# Question
Title: File to import not found or unreadable [omega 4] Windows OS
I have installed **omega 4** theme successfully with the help of this link on **Windows 7** machine. Working with the theme is awesome, however when I enabled the sub theme ohm, there I am getting issues. I have made a change to the following line in **ohm/sass/layouts/hero/hero.layout.scss**

```
.l-constrained {
  width: 95%;

```

to

```
.l-constrained {
  width: $desk;

```

`$desk is a variable declared in sass/variables/_grid.scss file.`

Afterwards I am getting following error.

> sass/layouts/hero/hero.layout.scss (Line 1 of sass/variables/\**/\*: File to import not found or unreadable: ../../variables/\_colors.scss

I can see there is slolution mentioned here, buit don't know how to implement it in omega 4 config.rb file.

**Edit:**

This is the problem of gem sass-globbing on Windows. If you are using it on Windows version having this issue, than try following solution sass-globbing does not support Windows 7. If it does not work, try the following alternative (not the best solution but it works). Add following line in **ohm/sass/layouts/hero/hero.layout.scss**

```
// Globbing from within sub-folders only works with relative paths.
@import "../../variables/colors";
@import "../../variables/grid";
@import "../../variables/legacy";
@import "../../variables/typography";

```

# Answer
You can fix this by editing your Gemfile and changing: gem 'sass-globbing' to gem 'sass-globbing', '1.1.0'

Then go back to terminal and type: bundle

All should be fixed
> 6 votes

---
Tags: theming
---


# Question
Title: How to fully localize popup calendar field
Strangely my popup calendar is localized, showing day names and so on in correct language, but not the date in the textfield neither in the description, **which remained Y-m-d formatted**.

.

**This should be french format : d-m-Y** . And I also need to change default value from today to next week. So, as per this answer :

> (For date popup) Branch 7.x-2 : Implementing `hook_date_popup_process_alter()` you could remove the description...

I tried these diff snippets :

```
function vts_commerce_date_popup_process_alter(&$element, &$form_state, $context) {
  $element['#date_format'] = 'd-m-Y';//no effect
  $element['date']['#date_format'] = 'd-m-Y';//no effect
  $element['#default_value'] = date('d-m-Y', strtotime('+1 week'));//no effect
  unset($element['date']['#description']);//works but I need to display it with correct date format instead
  dsm($element);
  return $element;
}

```

From which snippets 4 changes the form element. Instead, snippets 1, 2, 3 changed $element into `dsm()` returned values, but change nothing in the form. So my questions are:

* **How to display date into the textfield and in its description in french format ?** how to change the default value that will be shown on page loading ?
* What is the difference here between `$element['#foo']` and `$element['date']['#foo']` ?

Many thanks for your replies.

# Answer
> 1 votes
Well I'm a bit ashamed :( No need to do such complicated things. In the edit field page, there are some advanced settings and values I had never paid attention to :

* **Date entry options** : control the order and format of the options users see.

* **Default date** : Relative default value (*Describe a time by reference to the current day, like '+90 days' (90 days from the day the field is created) or '+1 Saturday' (the next Saturday). See strtotime for more details*.

---
Tags: datetime
---


# Question
Title: How to split Views exposed filters into separate blocks
I would like more flexibility of my exposed filters so styling and organization can be better.

I will be using 3-5 exposed filters and rather that oranizing them by CSS only i thought it would be nice to have each one in separate blocks.

My reason for this is to display filtering options the way most are use to, Ascednig/descending and small to large(or cheap to expensive) up top fairly small

and on the left side a detailed selection of sub category options (size, brand etc...)

If there is a better solution im all ears.

Im using: \- Drupal 7 \- Views 7.x-3.8 \- better exposed filters

# Answer
The MEFIBS - More exposed forms in blocks module provides this functionality.
> 2 votes

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


# Question
Title: How to check for entity type in Views when using hook_field_access?
I have some code that checks user access to a certain field using hook\_field\_access below.

The code runs fine when viewing nodes normally, but throws an error when viewing a node of type 'lesson' through a View:

*Notice: Trying to get property of non-object*

The error comes from the check for entity type: $entity-\>type == 'lesson'

If I debug with:

```
dpm($entity->type);

```

I get the right value ('lesson'), so the check seems to work.

How can I resolve this error?

```
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
Based on @clive's comment above, I adjusted the code to check that $entity is actually present. I'm not sure if this is a problem unique to my install or not. I only saw the error when viewing a node of type 'lesson' through a paged view that depends on some custom relationship code, so entirely possible the error is mine somewhere in a custom module.

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

      //Check to make sure we have an entity. Abort if not.
      if (is_object($entity)) {

        //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;
        }
      }
    }

```
> 2 votes

# Answer
I think your conditional statement won't work as it is. You are checking for $entity\_type to be 'node' and $entity-\>type to be 'lesson' and I feel that's a bit conflicted.

Also, if I understand the API correctly, `$entity` is optional, so it's probably better to check $entity\_type:

`if ($field['field_name'] == 'field_video' && $entity_type == 'lesson' && $op == 'view')`

or maybe check that $entity is an object before you check the value.
> 1 votes

---
Tags: views, entities, users
---


# Question
Title: Create 2 or more exposed filters for the same view
I would like to ask how can I create 2 or more exposed filter for the same view,which can be placed in different places of a site. E.g. one exposed filter will have 3 fields,the second one will have 7 fields. thanks

# Answer
I finally found how to do this: I first create the view with the first exposed filter. Then I clone the view and change the fields of the exposed filter,so as I have a second exposed filter.

Then I can place the first view in which page I want and same thing for the first and second exposed filter.Then I just redirect the exposed filters to the page where the first view exists . (The second view is placed nowhere,it is just used to give us the second exposed filter).

Finally,when I submist an exposed filter,they redirect to the page where the view leaves and the view is filtered from the URL parameters that the exposed filters are sending. I hope this make sense :)
> 4 votes

# Answer
One way is that you can expose the fitler block by configuring (**EXPOSED FORM** option in views) the "Exposed form in block" to "Yes" for as I have done below:

This way you will have the exposed filter available as a block at "/admin/structure/block".

Now as you want to create expose filter with 3 fields and 7 fields for the same view so than you do the following for that:

* Create view of block type and add the required fields (if you want it to be of fields type).
* Add the fields in "FILTER CRITERIA" section and this will be your expose filter fields. (Right now add the 3 fields).
* Add another block for the same view, and now the view be same and you have all the fields available you have added in the previous block.
* In the new block, add only new expose filter fields (just make sure you select "This page (Override)" while adding the fields for second block.

Hope this will work as you want.
> 4 votes

# Answer
When you say "placed in different places of a site" I am assuming you mean "different places on the page".

The Better Exposed Filter module will get you part of the way there. This module will allow you to assign your exposed filters to a block and display them on some other part of the page. This module will also allow you to define certain filters as "secondary filters", which will appear only after the primary filters have been used.

However, all of the filters have to be in the same place; either in a block, or with the results themselves.
> 1 votes

# Answer
The MEFIBS - More exposed forms in blocks allows exposed filters to be split up into different blocks. Combined with panels, context, or core block visibility settings you could have a different set on each page.
> 0 votes

---
Tags: views
---


# Question
Title: Is it correct to directly modify a supplied Drupal theme?
I downloaded and installed the Bootstrap theme for a new Drupal 7.28 site.

Is it correct to simply modify this theme directly to build my site, or should I create a custom theme and somehow "base" it on this theme?

Put another way, is theming analogous to downloading the Bootstrap CSS and overriding selectors, or directly modifying the CSS itself?

# Answer
> 1 votes
No, it's not correct to directly modify a contrib theme (or Drupal core, or a contrib module). Once you start doing that, you cannot easily update the theme anymore. It a few months, you, or another, developers may forget the theme was modified, do what should be a easy update and break everything.

You have two options to change and existing theme. You can rename the theme before making any other change (ie. fork the theme to a custom theme). You can also create a sub-theme of your chosen theme. The sub-theme can override template and theme functions, and adds ins own process and pre-process functions. But it will inherit all non-overridden templates and theme functions and all process and pre-process functions.

---
Tags: theming
---


# Question
Title: Listing content inside an OG based on a tag name provided in the URL
I have a site divided in 4 organic groups:

* Product
* Corporate
* Data
* Users

Users belonging to a group are able to post content in that group as well as read it. Every group has its page accessible through the following URLs

* example.com/product
* example.com/corporate
* example.com/data
* example.com/users

in which an overview of the latest content published in that group is shown inside a set of panels.

Every group has an specific vocabulary of 4 terms in order to subdivide content classification a little bit more.

THE GOAL IS:

I want to build some pages with page manager so that when a visitor types an URL like example.com/product/foo a page with the same design as the others is shown but filtering the contents inside that group to those tagged as "foo".

To achieve this I've started creating a page variant that would deal with requests in the form /product/%tag with the condition that %tag is a term in the "product" group vocabulary.

Up to this point, this works. When a user browses to example.com/product/foo the page shows as it should, and when it browses to example.com/product/bar (bar is not in the vocabulary) a "page not found" message is displayed.

Inside the views manager I also created a content pane view with the contextual filter based on term ID that:

* When the filter is not available displays all results.
* When the filter is available

+ Specify validation criteria
    + Validator: Taxonomy term
    + Vocabularies: corporate, data, product, users
    + Filter value type: Term name converted to term ID
    + Transform dashes in URL to spaces...
    + Action to take if filter doe not validate: Display content of "no result found"

THE PROBLEM:

The preview works well in the view admin page when providing the contextual filters but when I try it on the actual page, the "no results" found content is show.

Is there something I have to do with the "Argument input" option inside the views admin page? Am I trying to solve this issue twice by using page manager and contextual filters (should I use only one approach)?

# Answer
Ok, answer to my question is that when the filter is not available, I should provide a default value -\> raw value from URL -\> path component = 2

And check "use path alias" option to avoid using regular paths.

And also argument input = from panel argument (first).
> 0 votes

---
Tags: panels, views, chaos-tool-suite
---


# Question
Title: Setting up remote drush aliases for aegir
I have an aegir platform and I need to set up a drush alias file for all of the sites for our developers. I can't seem to figure out the best practice to do this. Normally we would set our 'remote-user' and that user would have access to drush but on aegir, drush is limited to the aegir user. I've follow these instructions http://community.aegirproject.org/node/427 to make is so certain users can also use aegir but I keep getting 'drush needs a higher bootstrap' error.

I have considered just setting the 'remote-user' user to aegir and then useing passwd to set a password for the aegir user but I'm not sure what secondary effects that could have. Presently we just su as the aegir user when we need drush.

Am I approaching this the correct way or is there a better way to approach this problem?

# Answer
> 1 votes
In BOA you can create sub-accounts (clients) with access limited to only associated sites, plus SSH and Drush available both locally and over SSH, with Drush aliases for all associated sites automatically created and updated for you.

# Answer
> 0 votes
The easiest way is to add the ssh public keys of the developers to the .ssh/authorized\_keys file of the aegir user. This however grants access to all sites.

The https://drupal.org/project/provisionacl module could help to get separate unix accounts access to selected sites.

---
Tags: users, aegir
---


title: user flag count in rules

text:
# Question
Title: user flag count in rules
Is it possible to add a condition - user flag count? Meaning to count every flag that user gave. I could find only - user is flagged and user has flagging count.

# Answer
You should be able to run the action "Fetch entity flag count" against the entity you're dealing with. In Rules you can have variables to store that and compare later.
> 0 votes

---
Tags: 7, flags
---


title: Add class to page content output

text:
# Question
Title: Add class to page content output
I have the following snippet in a theme's page.tpl.php:

```
<div id="content-wrap" class="row">
          <?php print render($title_prefix); ?>
          <?php if ($title): ?><h1 class="page-title"><?php print $title; ?></h1><?php endif; ?>
          <?php print render($title_suffix); ?>
          <?php if (!empty($tabs['#primary'])): ?><div class="tabs-wrapper clearfix"><?php print render($tabs); ?></div><?php endif; ?>
          <?php print render($page['help']); ?>
          <?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?>
          <?php print "**59**". render($page['content'])."**88**"; ?>
        </div>

```

The starred numbers in the last line for debugging. The output of `render($page['content'])` is something like the follwoing:

```
<div class="region region-content">
  <div id="block-system-main" class="block block-system">
.....

```

What I need to perform is programmatically change or add class name to `<div class="region region-content">`

# Answer
You can do that in a module/theme by adding a region preprocess hook:

```
function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'content') {
    $vars['classes_array'][] = 'foo';
  }
}

```
> 1 votes

---
Tags: theming, 7
---


# Question
Title: broken blocks after Drupal 7 Windows to Linux migration
I'm in the process of migrating a Drupal 7 site from a development Windows box to a soon to be production Linux box.

The Linux box has all the required dependencies and is running the same version of PHP/mySql/Apache/Tomcat/Solr.

I've copied all of the files over and exported/imported the database.

The first time I went to the page, it loaded fine. I get my superfish menu and my rotating banner. However, after I goto a different (any) page, my superfish menu and rotating banner disappear.

I dropped the database and re-imported it, and got the same exact behavior. First load is fine, subsequent visits the page is broken.

I thought it might be something to do with caching, so I cleared the cache and got the message:

```
The block Superfish 1 (Superfish) was assigned to the invalid region superfish and has been disabled.
The block View: Rotating Banner was assigned to the invalid region nivoslider and has been disabled.

```

I tried to export/import the database using the "Backup and Migrate" plugin... no change.

Is there anyway to fix this? Anyplace I could start looking to see where it's falling apart?

# Answer
> 0 votes
Have you checked your block regions? Sometimes when I migrate a site (though for me it's between servers running different OSs), blocks disappear from the site. However, it's just a matter of them getting thrown out of their regions, and the solution is to just go to Structure -\> Blocks and put them back into their appropriate regions.

---
Tags: migrations
---


# Question
Title: Trying to enable clean URLs: The clean URL test failed
I am trying to follow this document to enable clean urls on a fresh Drupal installation. When I run the test, I get:

```
The clean URL test failed.

```

My host provider confirms that `mod_rewrite` is enabled. I am using a shared server.

In my Drupal installation folder, I see a hidden `.htaccess.txt` file. Apparently, it has been installed by Drupal itself.

But, I cannot find information in the document mentioned above explaining to solve this issue. What is missing to make Clean URLs work? Thanks.

# Answer
The file name should just be `.htaccess`, without the `.txt` extension.
> 7 votes

# Answer
Follow the link.Am guessing that you are using drupal 7.Check the reply by doncheks. http://drupal.org/node/1572984#comment-6751806
> 3 votes

# Answer
setting the correct RewriteBase inside files/default/setting.php fixes it for my virtual host (=typical with reseller hosting accounts):

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
RewriteBase /~planet/v3

```
> 2 votes

# Answer
I believe I had a similar problem as you when I set up my first Drupal site. If you scroll down on this page, I believe it was the same fix as the user 'alessandro oliviero' mentions. I had to change one line of the .htaccess file and I do believe it was the line with "RewriteRule" on it.
> 1 votes

---
Tags: 7, uri
---


# Question
Title: Profile2, "access denied" for users profiles
Profile2 7.x-1.3 Address Field 7.x-1.0-beta5 Domain Access 7.x-3.11

Hello, I am attempting to use Profile2 module to create a separate user profile for my users. As soon as I add the new profile to a user, that user will always give an "access denied" when viewing that user's profile (except by user 1 and the user who's profile it is).

I have seen this question asked a couple times here but with no comments or answers. I believe that this is because it's almost impossible to tell what is really causing this error. That is why I installed the module "Access Denied Backtrace", which gave me a backtrace of the access denied error.

Please help me determine what in the backtrace is causing my problem..Thanks!

Here is the permissions relevant to the Profile2 module

Here is the "Deny Access Backtrace" UI for the report on the "deny access" incident.
Note that "There are no explicit access denied for this user.", which means that it was not the user trying to view the other user's profile which caused the access denied.

Here is part (only the very beginnng and the very end) of the backtrace report (it was too long to paste the whole thing) The full backtrace can be found here: Full Backtrace Report

```
Array
(
    [18: drupal_deliver_page()] => Array
        (
            [file] => includes\common.inc:2563
            [args] => Array
                (
                    [0] => 3
                )

        )

    [17: drupal_access_denied()] => Array
        (
            [file] => includes\common.inc:745
            [args] => Array
                (
                )

        )

    [16: profile2_privacy_profile2_view()] => Array
        (
            [file] => sites\all\modules\profile2_privacy\profile2_privacy.module:167
            [args] => Array
                (
                    [0] => Profile Object
                        (
                            [pid] => 14
                            [type] => organization
                            [label] => Organization
                            [uid] => 83
                            [created] => 1403027279
                            [changed] => 1403027279
                            [entityType:protected] => profile2
                            [entityInfo:protected] => Array
                                (
                                    [label] => Profile
                                    [plural label] => Profiles
                                    [description] => Profile2 user profiles.
                                    [entity class] => Profile
                                    [controller class] => EntityAPIController
                                    [base table] => profile
                                    [fieldable] => 1
                                    [view modes] => Array
                                        (
                                            [account] => Array
                                                (
                                                    [label] => User account
                                                    [custom settings] =>
                                                )

                                        )

                                    [entity keys] => Array
                                        (
                                            [id] => pid
                                            [bundle] => type
                                            [label] => label
                                            [revision] =>
                                            [translations] => translations
                                        )

                                    [bundles] => Array
                                        (
                                            [organization] => Array
                                                (
                                                    [label] => Organization
                                                    [admin] => Array
                                                        (
                                                            [path] => admin/structure/profiles/manage/%profile2_type
                                                            [real path] => admin/structure/profiles/manage/organization
                                                            [bundle argument] => 4
                                                            [access arguments] => Array
                                                                (
                                                                    [0] => administer profiles
                                                                )

                                                        )

                                                    [rdf_mapping] => Array
                                                        (
                                                        )

                                                )

                                        )

                                    [bundle keys] => Array
                                        (
                                            [bundle] => type
                                        )

                                    [label callback] => entity_class_label
                                    [uri callback] => entity_class_uri
                                    [access callback] => profile2_access
                                    [module] => profile2
                                    [metadata controller class] => Profile2MetadataController
                                    [static cache] => 1
                                    [field cache] => 1
                                    [load hook] => profile2_load
                                    [translation] => Array
                                        (
                                            [entity_translation] => Array
                                                (
                                                    [class] => EntityTranslationDefaultHandler
                                                )

                                        )

                                    [schema_fields_sql] => Array
                                        (
                                            [base table] => Array
                                                (
                                                    [0] => pid
                                                    [1] => type
                                                    [2] => uid
                                                    [3] => label
                                                    [4] => created
                                                    [5] => changed
                                                )

                                        )

                                    [configuration] =>
                                )

                            [idKey:protected] => pid
                            [nameKey:protected] => pid
                            [statusKey:protected] => status
                            [defaultLabel:protected] =>
                            [field_address] => Array
                                (
                                    [en] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [country] => US
                                                    [administrative_area] => OR
                                                    [sub_administrative_area] =>
                                                    [locality] => Gold Hill
                                                    [dependent_locality] =>
                                                    [postal_code] => 97525
                                                    [thoroughfare] => 583 6th avenue
                                                    [premise] =>
                                                    [sub_premise] =>
                                                    [organisation_name] =>
                                                    [name_line] =>
                                                    [first_name] =>
                                                    [last_name] =>
                                                    [data] =>
                                                )

                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                )

.....
.....
.....
EXTRA BACKTRACE DETAILS  (SEE backtrace.txt file for full report)
.....
.....

```

\***************UPDATE TO POSTING\*********************** All of this update is in regards to me taking a deeper look at the backtrace and trying to step through the module code where it says the problem resides.\**

In the Profile2\_Privacy module we have the function:

```
function profile2_privacy_field_access($op, $field, $entity_type, $entity, $account) {......}

```

Which is where my backtrace says the error came from. I added a bunch of prints and var\_dumps to find out where the problem lies....My analysis is below.

All of the below is in regards to the internal logic of the function profile2\_privacy\_field\_access in the module Profile2\_Privacy module.

```
$privacy_fields = array_keys(field_read_fields(array('type' => 'profile2_privacy')));

```

Initially the $privacy\_fields was returning empty. I had to go to my new profile and add a new field called "profile2\_privacy" to the profile2 profile After which $privacy\_fields was returning

```
array (size=1)
  0 => string 'field_privacy' (length=13)

```

Which is looped over to try and collect the roles

```
foreach ($privacy_fields as $privacy_field) {
      if (isset($entity->{$privacy_field})) {
        $pplid = isset($entity->{$privacy_field}[LANGUAGE_NONE][0]['pplid'])? $entity->{$privacy_field}[LANGUAGE_NONE][0]['pplid'] : 0;
        $roles += profile2_privacy_get_field_roles($pplid, $field_instance['id']);
      }
    }

```

Which are then checked against the $account-\>roles.

```
$allowed_roles = array_intersect($roles, array_keys($account->roles));

```

The problem is that in that looping above, we get our id to find it is always zero,

```
$pplid = isset($entity->{$privacy_field}[LANGUAGE_NONE][0]['pplid'])? $entity->{$privacy_field}[LANGUAGE_NONE][0]['pplid'] : 0;

```

So $pplid is always returning zero, so when fed into this function, it is not returning a role

```
  function profile2_privacy_get_field_roles($pplid, $fiid) {
  return db_select('profile2_privacy_fields', 'ppf')
    ->fields('ppf', array('rid'))
    ->condition('pplid', $pplid)
    ->condition('fiid', $fiid)
    ->execute()
    ->fetchCol();
}

```

So when we check our empty roles array vs ones for the account

```
 $allowed_roles = array_intersect($roles, array_keys($account->roles));

```

The allowed\_roles count is zero, which makes the whole function returns false for the function. This then causes our Deny Access error.

I am stumped as to how to proceed from here.....Can anyone make any sense of this?

Here is the entity (profile) object which we check against in the function

```
 $pplid = isset($entity->{$privacy_field}[LANGUAGE_NONE][0]['pplid'])? $entity->{$privacy_field}[LANGUAGE_NONE][0]['pplid'] : 0;

```

Note that the entity(profile) object has a "field\_privacy" array, but it is empty and it cannot be empty unless you want an access denied error. I am not sure why the profile privacy module thinks there should be a "field\_privacy" array, or why the profile privacy module is expecting a "profile\_privacy" field to exist somewhere. I just added the field to my new profile, but was that correct? Is there some other place I am supposed to add that field?

```
object(Profile)[189]
  public 'pid' => string '14' (length=2)
  public 'type' => string 'organization' (length=12)
  public 'label' => string 'Organization' (length=12)
  public 'uid' => string '83' (length=2)
  public 'created' => string '1403027279' (length=10)
  public 'changed' => string '1403037588' (length=10)
  protected 'entityType' => string 'profile2' (length=8)
  protected 'entityInfo' =>
    array (size=22)
      'label' => string 'Profile' (length=7)
      'plural label' => string 'Profiles' (length=8)
      'description' => string 'Profile2 user profiles.' (length=23)
      'entity class' => string 'Profile' (length=7)
      'controller class' => string 'EntityAPIController' (length=19)
      'base table' => string 'profile' (length=7)
      'fieldable' => boolean true
      'view modes' =>
        array (size=1)
          'account' =>
            array (size=2)
              ...
      'entity keys' =>
        array (size=5)
          'id' => string 'pid' (length=3)
          'bundle' => string 'type' (length=4)
          'label' => string 'label' (length=5)
          'revision' => string '' (length=0)
          'translations' => string 'translations' (length=12)
      'bundles' =>
        array (size=1)
          'organization' =>
            array (size=3)
              ...
      'bundle keys' =>
        array (size=1)
          'bundle' => string 'type' (length=4)
      'label callback' => string 'entity_class_label' (length=18)
      'uri callback' => string 'entity_class_uri' (length=16)
      'access callback' => string 'profile2_access' (length=15)
      'module' => string 'profile2' (length=8)
      'metadata controller class' => string 'Profile2MetadataController' (length=26)
      'static cache' => boolean true
      'field cache' => boolean true
      'load hook' => string 'profile2_load' (length=13)
      'translation' =>
        array (size=1)
          'entity_translation' =>
            array (size=1)
              ...
      'schema_fields_sql' =>
        array (size=1)
          'base table' =>
            array (size=6)
              ...
      'configuration' => boolean false
  protected 'idKey' => string 'pid' (length=3)
  protected 'nameKey' => string 'pid' (length=3)
  protected 'statusKey' => string 'status' (length=6)
  protected 'defaultLabel' => boolean false
  public 'field_address' =>
    array (size=1)
      'en' =>
        array (size=1)
          0 =>
            array (size=14)
              ...
  public 'field_privacy' =>
    array (size=0)
      empty
  public 'rdf_mapping' =>
    array (size=0)
      empty
  public 'entity_view_prepared' => boolean true
  public 'content' =>
    array (size=5)
      '#view_mode' => string 'account' (length=7)
      'field_address' =>
        array (size=16)
          '#theme' => string 'field' (length=5)
          '#weight' => int 0
          '#title' => string 'Address' (length=7)
          '#access' => boolean false
          '#label_display' => string 'above' (length=5)
          '#view_mode' => string 'account' (length=7)
          '#language' => string 'en' (length=2)
          '#field_name' => string 'field_address' (length=13)
          '#field_type' => string 'addressfield' (length=12)
          '#field_translatable' => string '1' (length=1)
          '#entity_type' => string 'profile2' (length=8)
          '#bundle' => string 'organization' (length=12)
          '#object' =>
            &object(Profile)[189]
          '#items' =>
            array (size=1)
              ...
          '#formatter' => string 'addressfield_default' (length=20)
          0 =>
            array (size=6)
              ...
      '#pre_render' =>
        array (size=1)
          0 => string '_field_extra_fields_pre_render' (length=30)
      '#entity_type' => string 'profile2' (length=8)
      '#bundle' => string 'organization' (length=12)

```

# Answer
I fixed this problem. You have to be very careful what steps you take when enabling/configuring this module (as it says in the documentation for Profile2 Privacy).

My problem came from the fact that I went through this order in configuring the module

1)add profile2 and profile2 privacy modules/enable 2)I added a new profile 3)I added the a new profile to one of my users 4)I added the roles for profile2.

WRONG ORDER The order should be:

1)add profile2 and profile2 privacy modules/enable 2)I added a new profile 3)I added the roles for profile2. 4)I added the a new profile to one of my users

The module works fine now
> 0 votes

---
Tags: 7, users, domain-access
---


title: Views options in UI not working

text:
# Question
Title: Views options in UI not working
Options aren't working in my views UI. JavaScript is enabled. Example, if in views, if I want to re-write output, and I click the checkbox, I don't get more options.

# Answer
Mystery solved. It looks like a conflict with what version of jQuery I'm using. On the site that isn't working, I have jQuery update set to 1.7 (which the slider depends on). The site that works didn't have jQuery updater, and seems to be running v1.4. So, I dropped the version of jQuery from 1.7 to 1.5, and views is back to normal (but, of course, the slider doesn't work).
> 4 votes

# Answer
I just had a similar issue (June 2014) with Views UI. The ajax interactions on the 'style settings' simply stopped working so click on 'customize field HTML' and nothing happened. Hence finding this post/tip. I went to the Modules/JQuery configurations screen (http://website.co.uk/#overlay=admin/config/development/jquery\_update) and instructed the Admin Pages to use JQuery v 1.5 (instead of the current 1.10). All View UI interactions then worked fine again.

Adding this extra note for anyone that might find that handy. Thanks to Vintorg and other repliers for the solution.

Q.
> 23 votes

---
Tags: 7, views
---


# Question
Title: Where are display settings for nodes stored in the DB?
I need to manually update the display settings for my content types. I have a lot of content types and I don't want to have to do it one-by-one using the UI. Where can I show/hide fields for Default and teaser displays for content types directly in the DB?

# Answer
Backup your database then ...

The tables that you want to deal with are:

**field\_config**

* The main field configuration

**field\_config\_instance**

* The field configuration on a particular entity bundle.

You can use database administration navigate to the table 'field\_config' to see that there is a column titled 'deleted' and a value of '0' for active and '1' for deleted fields (they should stay in your database because you've not burrowed down to the field specific tables)

Using Mysql run:

```
UPDATE field_config SET deleted = 1 where field_name = 'field_my_unwanted_field_1','field_my_unwanted_field_2';
TRUNCATE TABLE cache_field;

```

In the event that you also need to fiddle the 'field\_config\_instance' table

```
UPDATE field_config_instance SET deleted = 1 where field_name = 'field_my_unwanted_field_1','field_my_unwanted_field_2';
TRUNCATE TABLE cache_field;

```
> 0 votes

# Answer
With basic Drupal, the db table is field\_config\_instance, all in the "data" column.

With Display suite, you should also look at ds\_fields, ds\_field\_settings, ds\_layout\_settings.

(Use drush sqlc for a mysql commandline, and then "describe ds\_field\_settings;" etc.)

This being said, you really want to look for API functions. Look at:
> 2 votes

# Answer
A different approach would be to use Features module and export your content types as features, edit the exported file with find/replace or whatever, then import the feature.

Another possibility would be to use https://drupal.org/project/configuration
> 0 votes

---
Tags: database
---


title: How to link a view row to a node?

text:
# Question
Title: How to link a view row to a node?
I'm using the Message module to notify users when someone reacted on their nodes. I'm now trying to theme the messages, which are displayed in a view, called 'Message'.

I'd like to link a message to the content that's commented on. In other words: when a user clicks a message, he/she should be linked to the corresponding node's page. I don't simply want the message text to be a link, but the whole message (i.e. also including the other fields) should function as some kind of 'button'.

I think the easiest way to do this is to create a `views-view-unformatted--message.tpl.php` file and use

```
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
   <a href="<?php print url('$url'); ?>">
    <?php print $row; ?>
   </a>
  </div>
<?php endforeach; ?>

```

The problem is that I don't know how to define `$url`. I can store the needed `nid` in the message and add it hidden to the view, but I can't find a way to grab that information.

How can I do that?

# Answer
I stored the `nid` from the node that's commented on in a message field and used the information in a `views-view-unformatted--message.tpl.php` file.

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php $message = message_load($view->result[$id]->mid); ?>
  <div <?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
   <a href="<?php if (isset ($message->field_nid['und'][0]['value'])) {
                      print url('node/'.$message->field_nid['und'][0]['value']);} ?>">
    <?php print $row; ?>
   </a>
  </div>
<?php endforeach; ?>

```
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: How to setup module install (sub-folder) paths from the *very beginning* (contrib, custom, features etc) - i.e. not move them after the install
I've seen plenty of guides saying why it's a good thing to organise modules in different folders... (and I'd agree) e.g.:

...and how to move the modules to the new place(s) *after* installation

... but these haven't worked for me, perhaps I need to try again. My site broke, even after trying the registry rebuild and clear cache many times.

So my question is this: How can I run the installation of Drupal to set up the modules to be installed in different folders (e.g. like in examples http://befused.com/drupal/module-directory-structure )?

There doesn't seem to be anything out there if you want your module paths (sub-folders) structured in a certain way, right from the beginning. NOT after the fact.

I want the folders to be set up *in the first place*, right from the beginning. So example, whenever I use drush to download a contrib module, the module is placed in the contrib sub-folder: sites/all/modules/contrib for example.

Some other references:

# Answer
> 1 votes
Actually it seems like all you need to do is just create a folder called `contrib` in `/sites/all/modules`

when I issued drush dl views (at the docroot/install top level root of my site), drush put the views module in the contrib folder

as for features - you specify where you want the module to go when you (re)create the Feature (in the Feature section of the Drupal config)

as for custom - I'm hoping that Drupal will discover custom modules here - but is discovering, rather than a setting determining the path, a good thing?

Thought I'd still ask the question even after I'd found an answer, didn't want to waste the effort in making the question - hope someone else finds it useful.

Please provide your own answer or comment to enhance what I found.

---
Tags: 7, installation, uri
---


# Question
Title: Is there a way to restore a field (in views) which has been removed using 'this block (override)'
I am working with a view that has several sub-views and several fields which are common to all sub-views. I removes a common field from one of the sub views by selecting it, setting the designation drop-down to 'this block (override)', and clicking the remove button. This removed the field from the sub view without effecting any of the other sub-views (or the main view.) I realized the I made a mistake when I removed that field and I would like to restore it. Is there a way to revert an override on a view field that is no longer available on a sub view? I would like to avoid re-adding a common filed to a sub-view (which will only be used for that sub view.)

# Answer
You can basically revert the fields on the sub-view back to the master settings and list by:

-- clicking on the down arrow on the top right of the FIELDS section.

-- In the popup, change the **For** dropdown value to **Revert to Default**. This should effectively bring back the master list of fields, assuming that's where your missing field is.

-- any customisation for this specific view's fields must be re-done.

This same process can be done on any of the panes on the view's edit page - `/admin/structure/views/view/my-view` \- if you want to revert anything.
> 1 votes

---
Tags: views, entities
---


# Question
Title: Create two nodes from webform submission
I have webform with many fields.
And I need to create two nodes after webform submission.
First node would have some values from the webform.
And second node would have other values from the same webform.

How can I do this? (rules? hooks?)

Would be using Webform Default Fields or Webform report the right solution?

# Answer
I would recommend Rules.

Here's a link. Using webform rules to create node after webform submission

Hope that helps.
> 1 votes

---
Tags: nodes, webforms
---


# Question
Title: How to control path alias in custom node form #validate function?
To change form values in code, I understand that the right way is to add a validate function with `hook_form_alter`, to append the function's name to the `#validate` array then use form\_set\_value.

When I inspect the form array at this point though, I cannot see a way to reliably determine the parents of the path value.

e.g. I have

```
$form_state['groups']['additional_settings'][4]['alias']

```

And I can only assume that the `4` index is not always going to be `4`; that it might be a different number if more modules are installed etc.

So how can I set the alias? (I also need to un-set pathauto's checkbox so it does not auto-generate a new path.) Am I doing it in the right place?

Thanks.

# Answer
> 1 votes
You will find the values submitted by the user in `$form_state['values]`. So you can just fetch the ones submitted alter them and them send them back to the form. And the path settings are located at `$form['path']`. `$form_state['groups']` is just a way of grouping form elements together.

```
/**
 * Implements hook_node_form_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Add our validate function to all node forms.
  $form['#validate'][] = 'MYMODULE_alter_node_path';
}

/**
 * Custom form validate function.
 */
function MYMODULE_alter_node_path($form, &$form_state) {
  // Fetch the path values submitted.
  $value = $form_state['values']['path'];
  // Do your changes to the path and unset pathauto checkbox.
  $value['alias'] = 'new-alias';
  $value['pathauto'] = FALSE;
  // Set the values in the form.
  form_set_value($form['path'], $value, $form_state);
}

```

---
Tags: 7, forms, path-aliases
---


title: Preserve &nbsp in title

text:
# Question
Title: Preserve &nbsp in title
I'm currently working on a French website. French formatting requires a space before question marks. For some of my titles, this results in the question mark appearing on a line by itself.

> Why does it do this
>
> ?

It looks like trash. How can I preserve the ` ` in the title to have the question mark on the same line?

# Answer
You can use these two modules:

Title

> Do as follow: In content type field management, use replace button to turn title core into a text field; set up the field to be in a full html text format; In content type display management, show new title field; In file node.tpl do not print the core $title;

HTML Title

> It let you insert some sort of BBcode into the title. I've never used it and I don't know if there is a BBtag for
> 1 votes

---
Tags: 7
---


# Question
Title: sites/drupal folder not pushed to git repository
My .gitignore in the drupal root is as follows:

```
# Ignore configuration files that may contain sensitive information.
sites/*/*settings*.php

# Ignore paths that contain generated content.
files/
sites/*/files
sites/*/private

```

When I pushed it to a repository on github, the sites/default folder did not get pushed.

How to solve the issue?

# Answer
I would add a README file under `sites/default/files` then force the file to be added to the repository by executing `git add -f sites/default/files/README` and push your files.

The `-f` flag will allow the file to be added by overriding your `.gitignore` file. The next time you clone the repository on a new location the folder `sites/default` and `sites/default/files` will be created by git.

When downloading Drupal the sites/default folder contains a file called default.settings.php. And one solution here would have been to add that file. But since your .gitignore excludes `sites/*/*settings*.php` `default.settings.php` file wont be added and Git will not add empty folders to the repository.
> 0 votes

---
Tags: version-control
---


# Question
Title: Facing trouble in insertion of data in to table after creating table by using hook_update_N function
I have created a table by using hook\_update\_N() function. After creation, if i am trying to insert data into table but it is not storing. Is there any thing else is there to do after creating table by using hook\_update\_N()..?

# Answer
If you're using `drupal_write_record`, be aware of this warning in the documentation

> Do not use `drupal_write_record()` within `hook_update_N()` functions, since the database schema cannot be relied upon when a user is running a series of updates. Instead, use `db_insert()` or `db_update()` to save the record.

You should be using `db_insert` or `db_update` instead.
> 0 votes

# Answer
You can not use `node_save()` inside the `hook_update_N()` function. You must first *create* the schema for your new table by running the update script. After having run the update script, use a DB manager such as *phpMyAdmin* to check that it has been created in the database.

Then, to *use* the schema, the `node_save()` function must to be called from your custom module, not from inside `hook_update_N()`.
> 0 votes

---
Tags: database
---


# Question
Title: Approach to create a custom search form for an apache solr search
I am creating a search similar to the example shown below:

I am looking for the best approach to do this. My current approach is to alter the drupal default search form and add the additional elements, and then use a custom submit handler to pass the search query on to the appropriate solr search path, i.e: /search/courses/funky%20widgets.

An alternative approach would be to create the form from scratch with Form API, which may give me more flexibility, but at this stage I don't know.

It would be great to hear how others would approach this, or if there is a best practice method.

Thanks

# Answer
> 2 votes
I usually use Search API and Search API Solr. And for setting up the site layout I use Panels and Panels everywhere, so my answer will be using those modules. I'm not that familiar with Apache Solr Search but maybe it's doable with that module also. It would be interesting to hear other solutions :)

The fields you want to filter by could be built using Facet API. One thing that's pretty awesome is that the facets are shown depending on the search result. So the facet will only show filters that have results.

The tricky bit is that a facet can only be shown (as far as I know) by a query that has been run. To do this I would create a Search API view that uses you Search API index. Setup a views content pane that shows your search result. Then create a display of the type context in Views.

In your site template (setup using Panels everywhere) Insert the view by adding a pane where you want the search result to be shown. Add your views context as a context to the panel under Contexts. Then add your facets to the region you want them to show.

Then you probably want some caching on the views context so that it doesn't fire off a query on each page load :)

Another approach as you mention would be building a custom form and redirect the user to the search page `/search?q=filter` or to the search page and "prefill" the facet on the search page with the filter value (ie `/search?facet-argument=X`).

The options in the filter list could be fetched with an entity field query so that you fetch all values for the field you want to filter by. Then cache the result of that for X min/hours so that it doesn't load your site.

---
Tags: forms, search
---


# Question
Title: Overriding hook_preprocess_html page contents set by a module
I want to override/remove some HTML added to page\_bottom by a Drupal module, using a second Drupal module.

I tried to use hook\_page\_alter but this appears to be run before hook\_preprocess\_html as I can't see the content that the first Drupal module inserts in the page variable at that point.

The only solution I've found at the moment is to use hook\_process\_html and remove the unwanted HTML from page\_bottom using regex - at this point all page\_bottom additions are merged into a single array value so I can't just unset the unwanted value. This seems very messy.

Edited to add, here's the preprocess hook from the original module:

```
function module_one_preprocess_html(&$variables) {
  $theme_variables = array(
    'var1' => $var1,
    'var2' => $var2,
  );

  $variables['page']['page_bottom']['module_one'] = array(
    '#markup' => theme('module_one', $theme_variables),
  );
}

```

# Answer
> 0 votes
Check out John Albin's graph for the different preprocess functions you can use http://john.albin.net/sites/default/files/theme-system.png (from http://john.albin.net/drupal/arrays-of-doom) for a "complete" reference of what could be happening.

Without looking to the code to see if you've got another alternative (such as field\_attach or another render option), I'd go for hook\_process, that's always going to go after preprocess. If it's a theme function, you can use hook\_theme\_registry\_alter and override the theme callback.

Now an answer after seeing the code.

If you want, you can stick with hook\_process\_html, but as you said, the content is already rendered and is way harder to remove.

One thing you can do is to increase the weight of your second module in comparison with the one that has the preprocess that you want to override, that way, you could do a preprocess\_html and it always will come after the other one.

A couple of ways of doing this, one is on hook\_install as you can see in this doc page: https://www.drupal.org/node/110238

```
  $weight = db_select('system', 's')
              ->fields('s', array('weight'))
              ->condition('name', '[the_other_module_name]', '=')
              ->execute()
              ->fetchField();
  db_update('system')
    ->fields(array('weight' => $weight +1))
    ->condition('name', '[your_module_name]', '=')
    ->execute();

```

If you can't or don't want to do this, there are a couple of modules that can help you: Modules weight and Util

---
Tags: 7, theming
---


# Question
Title: How to give Permissions to User based on taxonomy selected while creating a content?
I have a taxonomy called Projects and it has terms like `Project1, Project2` etc. I have added a user called `ProjectUser1`, and assigned a new role called `ProjectRole` with it. Now I want to give Permissions to `ProjectRole` so that when ProjectUser1 logins, he can only see the content that has `Project1` taxonomy and he can Publish, Unpublish, Edit or Delete only those content. He shouldn't be able to see the contents which doesn't have `Project1` taxonomy.

Can anyone help?

# Answer
> 2 votes
I think you are looking for Taxonomy Access Control

```
Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Three node access permission types: View, Update, Delete.

```

# Answer
> 1 votes
Instead of using taxonomy and roles, you should use the Organic Group Module. \- Turn a new content type, for instance ProjectGroup, into a private group \- Make content type Project a group content \- Assign Projects and Users into their ProjectGroups

In order to give non-admin users the permission to publish and unpublish content, you can use the Publish module

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


title: how to add menu item from tags?

text:
# Question
Title: how to add menu item from tags?
I am new in Drupal, and I am creating a library the library has subject, each subject select from a list that referenced to a taxonomy.

> I want each subject become an item in my menu and when click on it show that tag result.

# Answer
> 1 votes
I'll post my comment here as an answer also so this question can be closed.

If you want a taxonomy vocabulary and it's terms to be represented in a menu you can use the module Taxonomy menu. It synchronizes changes in your taxonomy tree to a menu of your choice.

> Transforms your taxonomy vocabularies into menus with ease!

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


# Question
Title: How can I change page title in search results page?
When user search Drupal 7 site, output page's title becomes: "Search | example.com"

But i want to make page title as: "Search: keyword1 keyword2 .. | example.com"

I installed "Page Title" module but i couldn't change it by it. Is there a module to convert page title regarding to this?

Thank you very much

# Answer
1. Install and enablde Page manager and Panels.
2. Go to admin/structure/pages, on the line "search-node", click enable, then edit.
3. Add new variant -\> Create variant -\> Choose any suitable layout -\> Continue twice.
4. On the final page in the Wizard, expand "Substitutions". You should see two keywords in there, copy "%keywords:raw" to the empty "Title" field above
5. Below the keywords, click a cog in any suitable region, in the popup click Widgets, and select "Search form".
6. Repeat step 6 for "Search results".
7. Click "Create variant", followed by "Update and save".

Take variations for choosen layout into account, and your configuration should now look something like this
> 4 votes

# Answer
The module "pageTitle" can infact be used for the just named purpose.

After installing and enabling the module you go to the pageTitle configuration page. Here you can define default patterns, but you can also check the box "show field" for the desired content type, taxonomy or whatever. If a basic page is what you have chosen to show this field on, you just go to a node of that type. Added to the vertical tabs at the bottom of the page can now a new tab be found called "Page title setting". This is where you can set the pageTitle that appears in the browser tab and search results.
> 1 votes

# Answer
In Drupal 7, you can do this in your theme's template.php :

```
function MYTHEME_process_page(&$variables) {

    if (arg(0) == 'search' ) {
        $keys = arg(2);
        if (!$keys) $keys = $_REQUEST['keys'];
        if ($keys) $variables['title'] = 'Search for "'.$keys.'"';
    }

}

```

I dont know where your " Search | example.com" title comes from .. but this will probably remove that.

2$c, \*-pike
> 1 votes

# Answer
In Drupal 7, you can do this in your theme's template.php :

```
function hook_preprocess_search_result(&$variables) {
  $node_title = $variables ['title'] ;
  .
  .
  .
  $variables['title'] = $title;
}

```
> 1 votes

---
Tags: search, 7
---