title: Using OR in conditional fields

text:
# Question
Title: Using OR in conditional fields
I have several select fields in content type, which is more like Q/A & most of the answers are YES/NO. It's like tree flow, all question are dependent upon answer of previous question.

I am using condition fields & field conditional state module for this purpose. OR can be implemented by help of FIELD CONDITIONAL STATE as module description says --

```
Module supports AND/OR functionality for control fields which means:

    AND - all choices must be selected to control the filed
      (example: field A will be visible when in field B option 1 and option 2 is selected)
    OR - any choice will control field
      (example: field A will be visible when in field B option 1 or option 2 is selected).

```

But I have some fields(e.g. Field C) which should be appear on selection of YES of Field A or NO of Field B.

Is it possible to achieve it by this module or some other way by any contributed module. I am not looking for making my own form by FORM API as I have around 60 question in content type & it will become so messy to manage in code.

**Edited --**

I have searched & got option such as using OR in conditional field in this manner-

```
field_atleast_50_capital is visible when field_property_deriving has value "No".
OR
field_atleast_50_capital is visible when field_arrangements_90_subsidiary has value "Yes".

```

But it doesn't work..

# Answer
just an observation from looking at the module documentation:

there is a note under *interaction with other dependencies* on the *Edit dependency* page which says this:

**When this dependent has more than one dependee, how should this condition be evaluated against the others?** Note that sets will be grouped this way: `ANDs` AND `ORs` AND `XORs`

with a selection for `AND`, `OR` and `XOR`

This would indicate that you

* define your dependency of field C on A,
* define your dependency of field C on B
* and select *OR* as your interaction with other dependencies
> 1 votes

---
Tags: 7, entities
---


title: Drupal6 how to hide primary navigation

text:
# Question
Title: Drupal6 how to hide primary navigation
Is there any function like is\_page(like in word press) in Drupal 6

so that I can hide primary navigation menu which is (printed using echo statement) in `page.tpl.php`.

My requirement is to hide navigation menu in certain pages (custom theme).

# Answer
There is drupal\_is\_front\_page

`Check if the current page is the front page`.

**Return value**

Boolean value: TRUE if the current page is the front page; FALSE if otherwise.
> 0 votes

# Answer
Since you want to decide to show or not to show your menu on a theme level you can use

* `$is_front` in your `page.tpl.php` to decide whether it's your front page or not

```
<?php if ($is_front && isset($primary_links)): ?>
  <?php print theme('links', $primary_links, array('class' =>'links', 'id' => 'navlist')) ?>
<?php endif; ?>

```
* `$node` if your page is build by rendering a node (Simple page for instance)

```
<?php if (($node && !in_array($node->nid, array(1,2,3))) && isset($primary_links)): ?>
  <?php print theme('links', $primary_links, array('class' =>'links', 'id' => 'navlist')) ?>
<?php endif; ?>

```

In the above example the primary links are not rendered if you're viewing a node page where the node id is one of 1, 2 or 3. Comapare your path (`node/2`) or the path to edit the page/node if you are using the *path* module to get the *id*
* If that didn't do the trick for you you should dig deeper into some preprocess possibilities using hook\_preprocess but for that you need to provide further information.
> 0 votes

---
Tags: theming
---


# Question
Title: dropdown menu doesn't always show up in corporateclean
I customized a theme from corporateclean and now, adding a drop down menu, the drop down doesn't show up on the rest of the page. The link is http://athleticedgefitness.com/contact where it shows the Links drop down; if you go to any other page, you see that the drop down doesn't show up. Why not? How can I fix this?

I am using Drupal 7.

Clearing the cache didn't do it!

# Answer
> 1 votes
I see, where the problem is. In the parent menu you also have to select "show as expanded" option to display the child menu in drop down or whatever configuration you have.

Steps (if you may need):

1. Goto Structure-\>Menus
2. Select the Menu and click list links
3. Find the parent menu and edit it
4. Inside that you will have option to choose "show as expanded", Check that
5. Clear the cache and you are good to go.

---
Tags: routes, theming, navigation
---


title: Multi-domain user login access control

text:
# Question
Title: Multi-domain user login access control
E.g. My site has two subdomains : domain\_a and domain\_b.

And My site has three roles: role\_a, role\_b, role\_c.

I hope:

User with role\_a can login domain\_a, can't login domain\_b. (When user visit domain\_b user status is not logined and not lost domain\_a logined status)

User with role\_b can login domain\_b, can't login domain\_a.

User with role\_c can login domain\_a and domain\_b.

Does anyone have any solution?

# Answer
You have two options:

## Domain Access has it figured out

Domain Access module excerpt:

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:
>
> * example.com
> * one.example.com
> * two.example.com
> * my.example.com
> * thisexample.com \<-- can use any domain string
> * example.com:3000 \<-- treats non-standard ports as unique

Then, you need Domain Roles:

> Allows you to save user roles per domain. Allows a certain user to be just authenticated on one domain and admin on another etc.

You can't totally prevent cross-logins, but you can make user logged in with no permissions at all, except to log out.

## If you prefer Multisite approach

You can change the settings for the access to the database that are contained in the settings.php file used by your Drupal site to something similar to the following one (replace the values between brackets with the correct values for your site):

```
$databases['default']['default'] = array(
  'driver' => '[Your database engine]',
  'database' => '[Your database name]',
  'username' => '[Your username for the access to the database engine]',
  'password' => '[The password for the access to the database]',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'main_',
    'users'     => 'shared_',
    'sessions'  => 'shared_',
    'role'      => 'shared_',
    'authmap'   => 'shared_',
  ),
  'collation' => 'utf8_general_ci',
);

```

Taken from this answer.

Then, in hook\_user\_login(&$edit, $account) test if user has a role he needs to access given page, and if not, logout him with proper message.
> 2 votes

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


# Question
Title: How to change the "vid" in a field content_taxonomy
I would change the vid in this code, I tried to replace it but not to change how do you make it?

```
 $fields[] = array(
    'field_name' => 'field_galerie_type',
    'type_name' => 'rf_galerie',
    'display_settings' => array(
      'weight' => '2',
      'parent' => 'group_galerie_donnees',
      'label' => array(
        'format' => 'above',
      ),
      'teaser' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
      'full' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
      '4' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
      'token' => array(
        'format' => 'default',
        'exclude' => 0,
      ),
    ),
    'widget_active' => '1',
    'type' => 'content_taxonomy',
    'required' => '0',
    'multiple' => '0',
    'module' => 'content_taxonomy',
    'active' => '1',
    'save_term_node' => 1,
    'vid' => '60',
    'parent' => '0',
    'parent_php_code' => '',
    'depth' => '',
    'widget' => array(
      'group_parent' => '0',
      'show_depth' => 1,
      'default_value' => array(
        '0' => array(
          'value' => '',
        ),
      ),
      'default_value_php' => NULL,
      'label' => 'Type',
      'weight' => '2',
      'description' => '',
      'type' => 'content_taxonomy_select',
      'module' => 'content_taxonomy_options',
    ),
  );

```

# Answer
> 0 votes
In fact, it is quite simple.

First, change in the type of content vocabulary.

Then you need is to add features and the fields in the **.info** module configuration managing content type.

Then just make a pretty:

```
drush fu my_feature

```

and then we have a taxonomy fields changed continuously integration.

---
Tags: taxonomy-terms, entities
---


title: Grouping of vocabularies

text:
# Question
Title: Grouping of vocabularies
I have several vocabularies some of which are related to the same concept. Ex:
\- Car
\- Bicycle
\- Boat
\- Tags
\- Countries

In the above example, Car, Bicycle & Wheel could all relate to "Vehicles". I would like to group these vocabularies in order to pull out all vocabularies related to Vehicles...

Is there any way I can add this relation ?

# Answer
> 6 votes
Assuming D7, you can add a field to the vocabulary entity to group the vocabularies together.

For example, you could add another vocabulary "Group" that contains your vocabulary group terms. You could then add it either as a select or free-tagging style term reference field on your other vocabularies and link them that way.

*Admin \> Structure \> Taxonomy \> Edit Vocabulary \> Manage Fields*

You may also want to consider using a single hierarchical vocabulary where the terms are nested under a parent term, e.g 'Vehicle' (recommended)

---
Tags: taxonomy-terms
---


# Question
Title: Add a single image field to a view (not its nodes, the view itself)
I would like to know if it is possible to have an image field in the setup of a view, that I could then display in front-end, on top of the view via the views-view template.

So far, I can only find topics about how to add an image field to nodes of the view. I want this image field to be related to the view, just like the "view title" field.

# Answer
> 1 votes
Views are all about rows of data. To achieve what you want, you have two options:

1. Create `.tpl` file for your view, put `<img>` tag in it
2. Attach view to a node using, for example, Viewfield module. In that node create image field you want.

First option is faster, second one allows easier image changes.

# Answer
> 1 votes
you might want to use the views header, like so:

Header: click Add

Select Entity: Rendered Entity

select entity type, and entity ID

then give the relevant users access to that entity / node

# Answer
> 0 votes
Fields are attached to entities, and views are not entities.

All you can do is to relate a view with any entity type that provides such a field (beans sounds more appropiate than nodes). It can be done by several means, some of them outlined in the other answers here.

AFAIK there's no module that eases/automates this task. I think it would be a very handy module.

---
Tags: views, entities, theming, media
---


# Question
Title: Module for username suggestions on registration
Is there any Drupal module which checks the username in the database, if its present then it should display some suggestions to be selected just like the yahoo or gmail gives on registration?

# Answer
> 1 votes
There is no module that does that. The closest you will find is the one that just checks if the username is available while registering. An example of such module is username check. To achieve the username suggestion bit, you may have to write a custom module for that.

> This very simple module allows visitors to check username originality quickly using AJAX request during registration (completing registration form). This makes registration process more convenient as you don't need to submit your registration form to find out whether this username is already taken or not. This module is sensible to standard Drupal username validation as well as Access Rules validation.

or friendly register

> Friendly Register module allows users to see if a username or email address has already been used during registration before they submit the form. This module checks the database and returns an error if the username is already in use. In addition to checking the username the module checks if there is already an account using that email address, if there is, a message is displayed with links to the login or reset password pages.

# Answer
> -2 votes
If your searching a module that "checks the username in the database", I propose you to look at /modules/user. In 'user.module'.

---
Tags: 7, users
---


title: Taxonomy on each field value

text:
# Question
Title: Taxonomy on each field value
What is the best way to **add taxonomy terms to each field value** (uploaded with plupload or multiupload at once) of a imagefield (should look like http://www.binaerschmiede.at/test/imagefield-tags.jpg)?

Of course I want to access this terms in views afterwards for creating media overviews.

Is there already a extension/module I've missed so far while searching because I suppose I'm not the first one with that kind of request, am I?

Example:

1. I create a content where I upload 3 pictures to a multiple plupload image field. Entering title, alt text and the tag the first 2 images with "Nature, Animals", the 3rd on with "Nature, Landscape".
2. I create another content with 2 images tagged as with "Zoo, Animals".
3. In a View I want all to get all images tagged with "Animals", on another view all images tagged with "Nature", ... and so on.

Thanks.

# Answer
Create a multi-value Field Group, with one taxonomy term reference (tag), and one image. Field group values can be used in views via Field group views module.

Alternatively you can do the same using Field collection module - younger, without 6.x roots, written to utilize entity api (and it means native views integration).

For bulk uploading, there is Field Collection Bulkupload, it seems to work, if with issues (as to be expected for alpha module). If you need bulk upload capabilities and equivalent of collections, joining efforts with it's team should be your best bet.
> 4 votes

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


title: drupal 7 module for nodes with views

text:
# Question
Title: drupal 7 module for nodes with views
I have a problem to find a right module in drupal to do something that should be simple.

I need my web content out into two columns. Entering a node should have title and description in the center column, and then a right column with related documents. It should be the same type of content.

In a previous work had solved with "views", the result: http://www.imasmallorca.net/ca/unprograma/335

The problem to do with "views" it was not working the bread crumbs, nor the search. Neither the menu worked properly (not marked as an asset corresponding point)

Now, I'm working with "panels" to avoid this problem. It allows me to create columns, and embed a view with eg documents. The problem is that if I use a "panel page" does not appear in the search, and if I create a "panel node" I can pass arguments to the view in the right pane.

The question is: Is this right module? Should look for another module? is there another proper way to do this in Drupal?

Excuse my language, I'm Spanish :)

Thank you very much for your help, in another post I have been very useful.

# Answer
Panels is the right module to control this kind of layout. You should be using the `node/%node` panel in Page Manager and be overriding that. http://example.com/admin/structure/pages/nojs/operation/node\_view/handlers/node\_view\_panel\_context/content

The documents should be uploaded to the Node during editing. If you are missing a field for Documents create a Documents field in the node *Content Type* of *Field Type* **file**. Allow it to have infinite values.

Return to Page Manager \> Content. Add content into the right hand panel (using the gear icon). Choose Node and locate your **Field: Documents**. Add that.

Add your other content into the centre panel. Your left hand panel can be a block (for example a **Menus** block).
> 0 votes

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


# Question
Title: How to iterate over all the nodes from a content type
I want to recover some info from a field of all the nodes of a specific content type. I know how to do it using a `db_query` and getting all the node ID then iterate over them. What I would like to know is if there's is another way around this using drupal functions.

# Answer
You can query that information directly through `node_load_multiple()`

```
$nodes = node_load_multiple(array(), array('type' => 'my_type'));

```

You can add as many property conditions to the `$conditions` array (second argument) as you like, so status, created, etc are fair game too.

`$conditions` is technically deprecated (I imagine in favour of `EntityFieldQuery`) but the chances of that functionality ever being removed from Drupal 7 are basically none. It would break too much.
> 32 votes

# Answer
Drupal core provides a class called `EntityFieldQuery()`. There is also a handy document page for using it, that has lots of examples. In its simplest form:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'page')
  ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    // do something awesome
  }
}

```

This will load all published nodes of type "page". You periodically need to adjust this to

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'page')
  ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);

 foreach ($nids as $nid) {
    $node = node_load($nid, NULL, TRUE);
    // do something awesome
  }
}

```

to avoid loading too much at once, which can cause memory issues.
> 37 votes

---
Tags: 7, nodes
---


# Question
Title: Trying to leverage drupal_add_html_head to add an ie10 class
Since IE10 does not understand conditional comments, I can't use the typical methods to single out that browser. However, I found a nice function that works well and if I add this to html.tpl.php in my theme:

```
<script>if (Function('/*@cc_on return document.documentMode===10@*/')()){
    document.documentElement.className+=' ie10';
  }
 </script>

```

... it works for IE10 and adds an HTML class of `ie10`.

But for best practices, I really want to use a preprocess function. So I looked at drupal\_add\_html\_head and that seems to be the ticket. But when I formulate my code as such:

```
function MYTHEME_add_html_head($element, $inline_script) {

  $inline_script = <<<EOL
  <script>if (Function('/*@cc_on return document.documentMode===10@*/')()){
    document.documentElement.className+=' ie10';
  }
  </script>
EOL;
$element = array(
'#type' => 'markup',
'#markup' => $inline_script,
);
drupal_add_html_head($element, 'system_ie_browser');
}

```

... it does not work. There does not seem to be a lot of documentation around this and I could not really find anyone else doing exactly what I need so I'm a bit lost here. I replaced MYTHEME with the actual theme machine name and cleared cache too.

What I'm not sure about is if this part...

```
drupal_add_html_head($element, 'system_ie_browser');

```

... is significant in terms of Drupal understanding it and where to put it. I don't know if there are specific variables that go there. I just sort of made `system_ie_browser` up.

# Answer
Well it turns out this simply needed to be in a `hook_preprocess_html` function so the API probably needs some clarification. I also added `$element, 'javascript'` to the actual `drupal_add_html_head` call. I guess this is an example of a function being within another function. So this works flawlessly:

```
    /**
     * Implements hook_preprocess_html().
     */
    function MYTHEME_preprocess_html(&$vars) {

      $inline_script = <<<EOL
    <script>if (Function('/*@cc_on return document.documentMode===10@*/') ()) {
    document.documentElement.className+=' ie10';
    }</script>
    EOL;
    $element = array(
    '#type' => 'markup',
    '#markup' => $inline_script,
    );
    drupal_add_html_head($element, 'javascript');
}

```
> 0 votes

# Answer
Hope this will help you,

Use Browser class module.

> This small module helps theme-developers to deal with cross-browser compatibility. It makes easier to handle different types of non-widespread browsers just as much as it helps with using different versions of Internet Explorer. The module extends the $body\_classes variable in page.tpl.php based on the enduser's browser, and platform.
>
> The module also makes a $browser\_classes variable available in page.tpl.php, which stores the data in an array, this way the developer can make use of it as needed, if he does not wish to use the $body\_classes variable.
> 3 votes

# Answer
If you're going to be checking with javascript, you might as well use:

e.g, in *script.js*

```
if ($.browser.msie && $.browser.version == 10) {
  $('body').addClass('ie10');
}

```

You can then go, for example

```
body.ie10 .container{
  margin:2px;
}

```

Edit: Alternatively, you could try something server side like:

```
if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10') !== FALSE) {
  // Add ie10 body class
  $variables['classes_array'][] = 'ie10';
}

```

However, that won't play nicely with cached pages, hence the client-side solution above.

Overall, it would be nice if IE10 continued to support conditional comments as per previous versions of IE, that would make the whole thing easier!
> 1 votes

# Answer
If you want to add Javascript to every page (or even write conditions on which pages to add it to) the Drupal way would be **drupal\_add\_js**. https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_js/7

```
    /**
     * Implements hook_preprocess_html().
     */
    function MYTHEME_preprocess_html(&$vars) {
      $inline_script = "
        if (Function('/*@cc_on return document.documentMode===10@*/') ()) {
          document.documentElement.className+=' ie10';
        }
      ";
      drupal_add_js($inline_script, 'inline');
    }

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do you create a custom Panels layout in an Omega sub-theme?
I'd like to create a new custom Panels layout based on one of the Omega Panels layouts and put it in my Omega sub-theme, but I can't seem to find a way to do this.

So far I've added the following to my sub-theme `.info` file:

```
; PLUGINS
plugins[panels][layouts] = panels/layouts

```

I have then taken the layout I want to work from (`omega_12_twocol_6_6_bricks`) and renamed and copied this to `sites/all/themes/mycustom/panels/layouts/omega_12/mycustom_12_twocol_6_6_bricks`. I then renamed all the files within the `mycustom_12_twocol_6_6_bricks` directory replacing 'omega' with 'mycustom'. Then, within my `mycustom_12_twocol_6_6_bricks.inc` file I changed:

```
function omega_omega_12_twocol_6_6_bricks_panels_layouts() {
  $items['omega_12_twocol_6_6_bricks'] = array(
    'title' => t('Two Column 6-6 bricks'),
    'category' => t('Omega: 12 Column Grid'),
    'icon' => 'omega_12_twocol_6_6_bricks.png',
    'theme' => 'omega_12_twocol_6_6_bricks',
    'admin css' => '../omega_panels_admin_12.css',
    'regions' => array(
      'top' => t('Top'),
      'left_above' => t('Left above'),
      'right_above' => t('Right above'),
      'middle' => t('Middle'),
      'left_below' => t('Left below'),
      'right_below' => t('Right below'),
      'bottom' => t('Bottom'),
    ),
  );

  return $items;
}

```

to

```
function mycustom_omega_12_twocol_6_6_bricks_panels_layouts() {
  $items['mycustom_12_twocol_6_6_bricks'] = array(
    'title' => t('My Custom Two Column 6-6 bricks'),
    'category' => t('Omega: 12 Column Grid'),
    'icon' => 'mycustom_12_twocol_6_6_bricks.png',
    'theme' => 'mycustom_12_twocol_6_6_bricks',
    'admin css' => '../omega_panels_admin_12.css',
    'regions' => array(
      'top' => t('Top'),
      'left_above' => t('Left above'),
      'right_above' => t('Right above'),
      'middle' => t('Middle'),
      'left_below' => t('Left below'),
      'right_below' => t('Right below'),
      'bottom' => t('Bottom'),
    ),
  );

  return $items;
}

```

I also copied the admin css file into the relative directory as stated in the .inc file, cleared all cache and ran update.php, but I can't see my new layout when adding a new Panel.

The module versions I'm using are:

* Drupal 7.22
* Panels 3.3
* Omega 3.1

Any help here appreciated.

Many thanks

# Answer
> 7 votes
The basic process is:

Edit the MYTHEME.info file:

```
; PLUGINS
plugins[panels][layouts] = panels/layouts

```

Create a directory in panels/layouts/mypanel

Create your include panels/layouts/mypanel/mypanel.inc

```
/**
 * Implements hook_panels_layouts().
 */
function mytheme_mypanel_panels_layouts() {
  $items['mypanel'] = array(
    'title' => t('My Panel'),
    'category' => t('My Site'),
    'icon' => 'mypanel.png',
    'theme' => 'mypanel',
    'regions' => array(
      'top' => t('Top'),
      'left' => t('Left column'),
      'right' => t('Right column')
    ),
  );

  return $items;
}

```

Create your 50x75 mypanel.png, and place it as panels/layouts/mypanel/mypanel.png

Create the template file as panels/layouts/mypanel/mypanel.tpl.php

```
<div class="panel-display mypanel" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>>
    <div class="panel-panel mypanel-top grid-16 alpha omega">
        <div class="inside"><?php print $content['top']; ?></div>
    </div>

    <div class="panel-panel mypanel-left prefix-1 grid-4 alpha">
        <div class="inside"><?php print $content['left']; ?></div>
    </div>

    <div class="panel-panel mypanel-right grid-9 suffix-1 omega">
        <div class="inside"><?php print $content['right']; ?></div>
    </div>
</div>

```

Upload, clear cache, and see if you can make a panel page. Nine times out of ten, the problem with Panels picking up custom panel layouts has to do with a misnamed include or template file, which I suspect is your problem.

# Answer
> 4 votes
Copy one of the existing layout's folder to your site's theme directory to use as our template or outline which we will then rename, twocol for example. If you theme was named mytheme, the twocol folder would be copied to /sites/all/themes/mytheme/layouts/twocol.

This folder contains four files. These files are:

1. twocol.png, a screenshot of the layout.
2. twocol.css, a stylesheet for the layout.
3. twocol.inc, contains only an implementation of hook\_panels\_layouts().
4. panels-twocol.tpl.php, the template file for the layout.

We need to rename the files. We will be creating a simple layout with one row and two columns below, called onerowtwocols. Replace all the twocols names in the filenames with onerowtwocols, except for panels-twocol.tpl.php, which must be renamed to onerowtwocols.tpl.php (i.e. also remove panels- from the name). Don’t forget to also rename the folder to onerowtwocols.

Now, we need to change our theme's info file, which in this example would exist in our root theme folder at /sites/all/themes/mytheme, called mytheme.info. We need to tell Drupal where the folder with the custom panel layouts for this theme will be located, by adding the following line to the bottom of the file:

```
; Panels layouts. You can place multiple layouts under the "layouts" folder.
plugins[panels][layouts] = layouts

```

The title will be displayed in Drupal, it is wrapped in the t() function which makes it translatable. We will use 'title' =\> t('One row, two columns'),.

The screenshot of the layout is next, it will be 'icon' =\> 'onerowtwocols.png',. The theme will be the name of the template file without the .tpl.php extension, like this: 'theme' =\> 'onerowtwocols',.

The CSS: 'css' =\> 'onerowtwocols.css',.

In the panels array we will define the regions in which content can be placed once our layout is finished, just add a new item for each area, we will end up with this:

```
'panels' => array(
    'top' => t('Top'),
    'left' => t('Left side'),
    'right' => t('Right side')
),

```

you will find a plugins array (in the .inc file) like this:

```
$plugin = array(
  'title' => t('One row two columns'),
  'category' => t('onerowtwocols'),
  'icon' => 'onerowtwocols.png',
  'theme' => 'onerowtwocols',
  'css' => 'onerowtwocols.css',
  'regions' => array(
    'top' => t('Top'),
    'right' => t('Right side'),
    'left' => t('Left side')
  ),
);

```

...so you just edit that array, more or less using instructions above (it is pretty obvious). Edit the screenshot the way you want to best represent your layout, make sure you keep the filesize (in pixels) of the original png file so it will look nice and clean in the Panels user interface.

Now let’s start the actual layout part. Open onerowtwocols.tpl.php and take a moment to see how the two columns layout was set up. The little PHP snippets like print $content\['left'\]; are used to define the area where content can be added. We will partly use the existing HTML and change some of our own. We will start at the outside and work our way in. The outer div will almost stay the same, we will only change one class to our own:

```
<div class="panel-display panel-1row2cols clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>>
    <!-- Our content goes here -->
</div>

```

The PHP snippet inside the div makes it possible to use CSS from the Panels user interface. We will leave it in, but it is better to only use CSS through a stylesheet to separate style from our PHP. Next we will create two rows:

```
<div class="panel-display panel-1row2cols clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>>
    <div class="panel-1row2cols-row clearfix"><!-- Our content goes here --></div>
    <div class="panel-1row2cols-row clearfix"><!-- Our content goes here --></div>
</div>

```

Because we will not set a fixed width and height we can give both rows the same class. Now we will create the two columns in the bottom row:

```
<div class="panel-display panel-1row2cols clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>>
    <div class="panel-1row2cols-row clearfix"><!-- Our content goes here --></div>
    <div class="panel-1row2cols-row clearfix">
        <div class="panel-1row2cols-left"><!-- Our content goes here --></div>
        <div class="panel-1row2cols-right"><!-- Our content goes here --></div>
    </div>
</div>

```

Finally we will add our areas, using the names we used in the onerowtwocols.inc file:

```
<div class="panel-display panel-1row2cols clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>>
    <div class="panel-1row2cols-row clearfix"><?php print $content['top']; ?></div>
    <div class="panel-1row2cols-row clearfix">
        <div class="panel-1row2cols-left"><?php print $content['left']; ?></div>
        <div class="panel-1row2cols-right"><?php print $content['right']; ?></div>
    </div>
</div>

```

This means there’s only one file left to edit, our css file. We will make the layout fit the area it will be in, so we won’t give any fixed widths:

The outer div and the rows will be 100%:

```
.panel-1row2cols {
    width: 100%;
}
.panel-1row2cols-row{
    width: 100%;
}
Our columns will float to the left and to the right:
.panel-1row2cols-left {
    float: left;
}
.panel-1row2cols-right {
    float: right;
}

```

Finally we will have to make our layout ready for use, by clearing the cache so it will actually show up with the other layouts.

---
Tags: panels, theming
---


title: Multisite Module Update

text:
# Question
Title: Multisite Module Update
Being able to update the shared modules folder in a multi-site Drupal installation is amazingly easy, but I am wondering, what are some best practices when it comes to that?

Updating modules on a live environment when multiple sites are affected can be bad if a module has some sort of bug or if it's incompatible with something you were unaware of, correct? Usually we like to perform quality assurance on sites after a module update has been performed, but that starts to become a hassle once there are many sites under one core.

Assuming the sites/all folder is synchronized between development and live environments, pushing a site live is specially an interesting experience - since we want to make sure that all of the modules are updated. Sometimes these modules are in the shared modules folder, meaning it would affect every remaining multi-site as well. Then, in that case the only solutions I can imagine at the moment would be to either:

Push the site live without updating any of the shared modules - Perform updates on the live environment periodically when everyone is available to do Quality Assurance. Perform module updates everytime a new site is pushed live. In this scenario, quality assurance would have to be performed on every site under multi-site - every single time a new site is pushed live. Any input would be appreciated. Thanks for your help, guys!

# Answer
I always run with a Dev mirror copy of the Live site and test all modules here before updating the live site with those modules, do this and test the site thoroughly. Make sure the dev and live environments are identical or as close to identical as possible.
> 0 votes

---
Tags: updating, multi-sites
---


# Question
Title: 7 - FAPI: form_set_error messages on bottom of page or dialog box
My ajax FAPI multi-step form is rather large, the error validation message are located by default at the top. But users can't see these messages as they are clicking submit on bottom of a large form (scroll down).

Editing the $messages in the template has no effect on de FAPI vailidation.

Is there a way to place it in a dialog box or at the bottom?

# Answer
Perhaps the Inline Form Errors module is useful to you. It provides Inline Form Errors (as the name implies). More details from the module's project page:

> IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.
>
> IFE provides three behaviours for the configured forms
>
> * Leave the messages in place, this option will copy the error messages and place them inline. The original error messages set by Drupal will remain in place.
> * Show an alternative message, this option will replace the original messages with a generic error message such as 'Please correct all errors.'. This message can be set in the IFE configuration page. The original error messages are placed inline with the form elements
> * Remove all messages, this option will remove all error messages and place them inline with the form element
>
> In all cases only the messages related to the form will be touched. All other messages will remain in tact.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: When is the filter value available to a context filter in a view?
There is very odd negative grammer for setting up Context filters in views.

I set a context filter to take a value from the URL (perhaps context filters are primarily for something else?)

However when I go to set it up I need to put my details into the field labelled

```
WHEN THE FILTER VALUE IS NOT AVAILABLE

```

This seems very odd to me, could someone explain to me When the filter is available?

I may not be making any sense but then again neither does that page!

# Answer
At the very top of the contextual filter configuration window you have:

> This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'.

The answer to your question `When the filter is available?` is short:

**The filter is available only if has been provided.**

Let say, you want to show a block with the content that depend on node id. Obviously you don't want to provide the node id by yourself on each node to see what the block content is. You don't need to provide it, because the node id is in the URL, so **it's available**. Of course the node id is not always in the URL, for example if you're viewing a user profile or a list of recently added articles. That's why this fieldset has been labeled:

**WHEN THE FILTER VALUE IS NOT AVAILABLE**

In this fieldset you can decide what to do when the filter hasn't been provided (display all results? provide default? .. many options there..)
> 2 votes

# Answer
Good one Toby, As I understand it;

A contextual filter source can be anything; like if i have to embed a views from my code to output the result; I'd feed the contextual parameters as last param in `views_embed_view();`

Hence, The views page makes a little sense with the sentence `'WHEN THE FILTER VALUE IS NOT AVAILABLE'`, where you supply the secondary source of a contextual param.
> 1 votes

---
Tags: 7, views, uri
---


# Question
Title: Commerce cart form alter to do an availability check
I have some nodes I use as rentable objects, and I want to check availability on the Commerce Cart page (made by Views, the one you see at `/cart`). I also need to check it a last time before the user is sent off to payment, but as for the views Cart form, what function actually handles the quantity updates? I can see that the `edit quantity` field has my pre-update value as `default_value` and the new value as `value`, but which function actually sets that on submit?

# Answer
I'm not sure what you're asking about quantity for, so I'm going to set that question aside and answer the broader question of confirming availability before purchase. In Drupal Commerce, the product pricing system serves a two-fold purpose:

1. Determine the price of a product for the current user.
2. Determine if the product is no longer purchasable.

While #1 is the most common use case, #2 even has some core representation: if you add a product to your cart and then disable that product as an administrator, the product will be removed from your cart thanks to a default product pricing rule that unsets the price of disabled products. We'll make this process more explicit in the next version of Drupal Commerce, but right now you should understand that if the unit price of a product line item is "unset" or set to a NULL (empty) value, the product will not be considered purchasable.

This will result in one of two behaviors:

1. For a product in the cart, it will be removed.
2. For an Add to Cart form, the *Add to cart* button will be changed to *Product not available*.

So, in your case, I'd just add a product pricing rule that performed the availability check. If the product is not available, the Add to Cart form will not allow the product to be purchased. If it was already in the cart, it would be removed, so you might use a separate rule to remove unavailable products from the cart and display a message informing the customer what happened. If they were on a checkout page, it would be user friendly to also send them back to the cart page.

Since I don't know how you're checking availability, I'll just add that if you can't do what you need through Rules directly, you can just whip up a simple custom condition to perform the check for ya. There should be plenty of examples in our code and elsewhere.
> 1 votes

---
Tags: 7, forms, commerce
---


# Question
Title: If I have added extra fields to a user profile, how can I programmatically check if those fields are empty?
I have added some fields to my user entity, (doing this in hook\_install(), in .install file). This is in a custom module. If I uninstall this custom module I only want to uninstall those fields if users don't have any values for the field, so I don't end up losing data from my users. How can I check fields of a user?

# Answer
> 2 votes
I would advise against keeping those fields around after an uninstall. It's a module's responsibility to clean up after itself, and a user of your module should be able to assume that if they *disable* the module, the functionality will be gone, but the data remains in the database. If the user *uninstalls* the module, the assumption is that the module will clean up after itself - delete all its data, custom tables, created variables, etc.

If you don't want to lose any data, just disable your module without uninstalling it - then the uninstall hook doesn't run. But my suggestion is to keep to the community's expectations and properly clean up the custom database tables, fields and variables that your module has created in the uninstall\_hook.

I think with open source projects like Drupal, where there are tons and tons of contributing authors and contrib modules, it's even more important for each of us to conform to the expectations of a module's behavior. Otherwise, if each module does what it wants upon uninstall, we wouldn't know what to expect in terms of our databases. What if a user has another contrib module that conflicts with your module's fields, for example? How could they ever get rid of them if your uninstall hook doesn't clean them up?

# Answer
> 0 votes
I took a stab and typed field\_has\_data into Google...low and behold :)

field\_has\_data()

> Determine whether a field has any data.

Returns

> TRUE if the field has data for any entity; FALSE otherwise.

It takes a field structure as an argument, which you can get from `field_info_field()`

```
$field = field_info_field('field_name');
if (field_has_data($field)) {
 // ...
}

```

---
Tags: entities, users
---


title: Commerce order rule save order

text:
# Question
Title: Commerce order rule save order
I have a field in my orders which should be updated when an order is saved. I created a rule with the event "commerce order save", do the calculation for the field and at least save the order. But that logically gives me an endless loop.

How can I save the order without firing the event again?

# Answer
You can use the '**Before saving a commerce order**' trigger in Rules. It's right there in the 'Commerce Order' section. Then you don't need a save action since it's about to be saved already...

That should do it for you!
> 3 votes

---
Tags: rules, commerce
---


# Question
Title: Finding a node with a time closest to the current time without being past
I am working on a site which has a Class (ECK) entity type. Each Class may have 0+ "Class Offerings," which are instances of a class at a specific date. I am trying to create a view listing a class and the next upcoming Offering for each class (if one exists). If there is no upcoming Offering, I would still like to list the Class. How could I accomplish this?

# Answer
Absolutely!

Add a filter to your view, that is based on your date field and choose the operator as 'Is greater than or equal to'.

You have as an option to enter a relative date for the comparison and then enter in any variety of relative times and dates. For your purpose just choose 'now' as the comparison.

That will pull up all nodes with a date field that is greater than or equal to now: i.e. all the future ones!

============= EDIT ===============

If you don't need all of the future ones, just limit the results to 1 and order by the date. That will give you just the *next* one coming up.

Let us know if that works for you!
> 1 votes

---
Tags: views
---


title: Override Ajax throbber icon styles

text:
# Question
Title: Override Ajax throbber icon styles
I've been digging around the CSS and JS files but I haven't quite found the exact thing that places the `throbber.gif` where it appears when clicking on 'previous' or 'next'.

The styling is in `system.base.css` file and I found this declaration:

```
.ajax-progress .throbber {
    background: url("../../misc/throbber.gif") no-repeat scroll 0 -18px transparent;
    float: left;
    height: 15px;
    margin: 2px;
    width: 15px;
}

```

but besides removing the background, the other parts of this declaration do not affect the placement of the `throbber.gif`.

It's hard to use Firebug and get the styles as the throbber only appears after pushing a button and it's only alive for a few seconds so I've tried screen capturing during the 'throbbing' and measuring distances in the scrn cap in Photoshop and applying but I discovered that the throbber is 'attached' to the button somewhere as it just moves the whole kit and kaboodle... the 'throbber' still appears right next to either 'previous' or 'next' button.

I'm trying to avoid the little jump that happens. When pushing 'next', the 'next' button is shoved left and down a little to make room for the throbber gif, and then shifts back when the new page is loaded.

Any ideas?

# Answer
You can try Views Sexy Throbber, not exactly that you need, but is still cool...
> 0 votes

---
Tags: 7, theming, ajax
---


# Question
Title: Drupal 7 webform module is not sending email properly
I have this modules enabled in my Drupal 7 site:

I have configured Mail system to "format" mails with MIME Mail and "mail" with SMTP Authentication. This configuration is set as site-wide default class.

It works fine for register user email, but when send mail with webforms it doesn't use that configuration (It sends emails with a local smtp).

How can I make webform take mail system configuration?

## This is what I did:

1. Install smtp module and config to send mails with amazon ese service. (Using the test option of this module it was working fine)
2. Needed to send html mails so I installed "mime mail" and "mail system" modules
3. After enable both modules I have created a class with "mail system" module in this way:

* Create a class with:

    **format**: MimeMailSystem

    **mail**: SmtpMailSystem
    * After that apply the new class to:

    **Site-wide default class**

    **Mime mail module class**
4. Tested the result with post register emails (This was working fine, amazon ses with html emails)
5. Installed "webform" module and create a contact form
6. Webform is sending mails but is not using my smtp config, it's using my local sendmail server (I realize this when the email was detected as possible phishing and looked at the email header)
7. This shouldn't be working like this, it should be using the site-wide default class defined in "mail system"
8. Post register emails are still working

# Answer
> 7 votes
I found the solution for the problem, it's really easy by the way. I hope this is helpfull for somebody else.

What we need is go to:

```
admin/config/system/mailsystem

```

Then press "New Setting" link, select "Webform" in the combobox, leave the "key" field empty and save configurations.

Then a new option is enable as shown in the image:

Then we only need to select the right class for Webform module and save.

That's all, i think this should work for other modules too.

---
Tags: 7, webforms, emails
---


# Question
Title: How do I change the delta values using a hook?
I have a view getting all fields from nodes that have a relationship with the viewed node (using delta = all); it then only shows one node using CSS styles.

How do I change the delta value for every request and take its value as an argument from the URL?

I reloaded the page from JavaScript when the user needs to see the next field (using pager controls).

Which hooks does the Views module provide to edit that value?

# Answer
You can specify the validation criteria with PHP code in your contextual filter settings:

**When the filter value IS in the URL or a default is provided**

Specify validation criteria -\> PHP Code

```
if($handler->argument){
  $view->display['default']->handler->options['pager']['options'] = array(
    'offset' => 0,
    'items_per_page' => $handler->argument
  );
  return true;
}
else {
  return false;
}

```

That's it. Now, for every request the delta will be equal with the argument from the URL. `$handler->argument` It's the argument which has been provided by your contextual filter.
> 1 votes

---
Tags: views, hooks
---


# Question
Title: Is the database table "field_revision_body" used in a core module or can I just drop it?
I recently installed the revisioning module and now im cleaning it up and uninstalling it, but it seem to have created a bunch of field\_revision\_field\_ tables in my database. Since it creates another table for every field you have, it creates alot of mess. I uninstalled the revisioning module, but these tables still stayed. I was wondering if I can just drop these? Also i see there is a field\_revision\_body table, but i dont know if it was generated by the revisioning module. So im asking if anyone knows what this table is used for? I tried deleting it, but i get an error when editing a node. So it must be used for something.

# Answer
> 2 votes
Both tables (`field_data_*` and `field_revision_*`) are added and used by the field SQL storage module in core. The existence of both tables make it possible to store revisions of field data. There's no way to use that storage system without both `data_*` and `revision_*` tables.

So don't delete it :)

There are modules out there defining alternative storage systems without using revision tables (e.g. Field SQL norevisions) but I'm not sure how difficult it would be to convert an existing database to use that system.

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


# Question
Title: Customizing a View with Taxonomy, color coding and icons
I have been searching for help with this and I am stumped.

I am trying to create an attractive, styled table with categories of Web Resources and associated icons for each category.

I currently have the following:

What I would like to do:

* Show the Taxonomy icons next to the technology category names in the Views table
* Style each Views generated table with a different css (e.g. border color, bg color)

But I can't find where I can create/generate specific CSS classes for each of the tables. They are all showing up in the output HTML as:

```
<table class="views-table cols-0">...</table>

```

And I don't even know where to start to display the Taxonomy icons next to the Taxonomy.

Do I need to work in Templates? If so, how do I add the appropriate icon to the table captions without hardcoding (e.g. switch / case), because that won't be flexible in the long run. I want site maintainers (not me) to be able to simply add a new category to the Taxonomy and upload an icon to go with it and have it show up in the View as a header for that category.

Thanks to anyone who can help.

# Answer
> 2 votes
First, to have the associated icon show up with the taxonomy term, do the following:

* add field: image field from taxonomy
* add field: Global: custom text, set it to \[name\] \[field\_your\_image\_field\]
* exclude label from display
* exclude these two fields from display
* change your table grouping from taxonomy name to Custom text ( or whatever you named it )

To style the output, you'll use two settings:

under Format: table | settings, set the row class here

to style individual fields, click on the field in the fields list, click on style settings, and customize field HTML / create a CSS class

There are lots of options here for setting field and label classes, and html elements

Good luck

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


title: style doesn't reflect what's in css

text:
# Question
Title: style doesn't reflect what's in css
On my page http://www.athleticedgefitness.com/, I added a drop down menu under Contact. The hover color is yellow but for some reason, I cannot find that color style in my colors.css. What I found is that the devtools show that the background color change is caused by a rule starting at line 44 in http://www.athleticedgefitness.com/sites/default/files/color/corporateclean-659c1a2d/colors.css?mp37st The rule is:

```
#header-menu ul.menu li ul.menu li a:hover,
#header-menu ul.menu li.expanded ul.menu li.expanded a:hover,
#header-menu ul.menu li.expanded ul.menu li.leaf a:hover,
#navigation .block-superfish ul.sf-menu li li:hover,
#navigation .block-superfish ul.sf-menu li li a:focus, #navigation
.block-superfish ul.sf-menu li li a:hover, #navigation .block-superfish
ul.sf-menu li li a:active  { background-color:#fbff24; }

```

But If I check in my colors.css, my rule actually looks like this:

```
#header-menu ul.menu li ul.menu li a:hover,
#header-menu ul.menu li.expanded ul.menu li.expanded a:hover,
#header-menu ul.menu li.expanded ul.menu li.leaf a:hover,
#navigation .block-superfish ul.sf-menu li li:hover,
#navigation .block-superfish ul.sf-menu li li a:focus, #navigation .block-superfish ul.sf-menu li li a:hover, #navigation .block-superfish ul.sf-menu li li a:active  { background-color:#1b1b1b; }

```

I have tried to clear the caches and everything but that didn't help either, any recommendations? This is in Drupal 7.x with the Corporateclean theme.

Thank you!

# Answer
Added and configured Nice Menus - can configure the style sheets properly with that, unsure why that yellow wouldn't disappear...
> 0 votes

# Answer
Have you checked the css file route (Chrome will show that in the dev tool) that the website is reading? I use superfish as well, there are some css files for the menu bar in '.../sites/all/superfish/css/', but I also have my overriding style in my custom theme folder. Are you sure the browser is linking to the css file that you think it is linking to?

And, that happened to me once, probably is not your case, but I once forgot to save my css after editing it :P

Good luck.
> 1 votes

---
Tags: theming
---


# Question
Title: Content profile fields on registration form by role
I have two main users roles: authenticated and agent.

First role uses content profile fields on registration form.

Users with the agent role can only be created by admins but agent doesn't need content profile fields.

In `user_add_form` the content profile fields is added as well so the admin must fill them.

How can I disable those fields when an admin want to create user with the agent role?

# Answer
You can use `hook_form_alter` to alter the form. This is how the profile fields is added and they can be removed this way as well.

You have to make sure that your custom module is run after the profile module, which may require that you alter the weight of the module. This is merely a value in the `system` table.
> 2 votes

# Answer
There is two checkboxes on 'Content profile' tab of the node type: "Use on Registration" and "Use on administrative user creation form" See image the below image
> 0 votes

---
Tags: 6, users
---


# Question
Title: I want to define a hover color in the style sheet
I designed a page with the corporateclean theme on http://www.athleticedgefitness.com/. I used nice menus for the drop down. Now I would like to color all my links #E3007B on hover, but I'm not exactly sure how I can get this accomplished. Any help would be appreciated!

# Answer
> 1 votes
Just put this in the css of your subtheme ("styles.css" i think):

a:hover, li:hover {color:#E3007B !important;}

---
Tags: navigation, theming
---


# Question
Title: How can i fetch the value from database in a simple module?
I'm working in drupal 7 and I have tried all help but not able to fetch the value from database.

```
    function myModule_load($node){

    $result = db_query("SELECT * FROM {uc_auction_bids} WHERE nid = :nid", array(':nid' => 258,));
$record = $result->fetch();

    // print the fields/values of $record
print('<pre>'); print_r($record); print('</pre>');

```

and also

```
    function myModule_block_view($delta) {
       if (($node = menu_get_object()) && ($node->type === 'product')) {
        $results = db_query("SELECT * FROM {uc_auction_bids} WHERE nid = :nid", array(':nid' => $node->nid));
        $records = $results->fetchAllAssoc('bid');

        $content = ... // Format records here...

        return array(
          'subject' => t('Bids'),
          'content' => $content
        );   } }

```

I want to fetch the value in module and in the page, but not at the top of the drupal header

# Answer
> 1 votes
Something like this should work:

```
/**
 * Implements hook_block_view
 */
function MY_MODULE_block_view($delta = '') {

  if (($node = menu_get_object()) && ($node->type == 'product')) {
    $query = db_select('uc_auction_bids', 'bids');
    $query->fields('bids');
    $query->condition('nid', $node->nid);
    $result = $query->execute()->fetchAllAssoc('bid');

    // Debug
    drupal_set_message('<pre>'.print_r($result,1).'</pre>');

    $content = ''; // Format records here...

    return array(
      'subject' => t('Bids'),
      'content' => $content
    );
  }

}

```

# Answer
> 0 votes
To fetch values from database: you can try this.

```
   $query = db_select('uc_auction_bids', 'u');
   $query->fields('u', array('field1', 'field2')); // and other fields required
   $query->condition('nid', $nid_value, '=');
   $result = $query->execute();
   foreach ($result as $record) {

    //USE $record->field1;
    //USE $record->field2;
    // and so on

    }

```

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


# Question
Title: Batch removal of users and comments without causing excess load on server
I have a basic shared hosting account and don't want/plan to upgrade anytime soon. Unfortunately, my site has been subjected to large scale attacks by spambots that have lead to the generation of thousands of spam comments and users. I would like to delete these, but deleting them in batches causes the server to crash, every time. What should I do to avoid these crashes?

# Answer
Try setting up a View with VBO.

* Add a new users view
* Add a bulk operations field to the view
* Add a "Delete item" operation to the field settings
* Configure the field settings to process "1" per batch
* Add any other required exposed filters.

That will delete one user per batch run until finished, so should be fine on your server.
> 2 votes

---
Tags: 7, users, comments
---


# Question
Title: How to call function after submit button clicked
```
$nid = db_insert('tennis_vana')
  ->fields(array(   'firstname' => $first,   'lastname' => $last   ))
  ->execute();

unset($form);
$form_state['rebuild'] = TRUE;

drupal_set_message("you data has been saved");

$details=project_list1();

```

this is not working. My requirement is, I want to call and display information from after submit.

# Answer
If you want to call the function after submit of the form.

Add this part in hook\_menu:

```
function MYMODULE_menu(){

    $items['project'] = array(
    'title' => 'Project List' ,
    'page callback' => 'project_list1',
    'access callback' => TRUE,
    'menu_name' => 'devel',
    'type' => MENU_CALLBACK,
    );

 return $items;

}

```

If you want the menu to appear in main menu you can make these changes:

```
     'menu_name' => 'main-menu',
     'type' => MENU_NORMAL_ITEM,

Your  function here:

  function project_list1(){
     /////code
    }

```

And then in your submit function, you can directly add:

```
  //Add this in the last line of your submit function
   drupal_goto('project');

```

This will directly go to the path 'project' and call your function

> project\_list1()
> 1 votes

---
Tags: hooks, 7
---


# Question
Title: How do I use Views Global Filter with Geofield 2.x Exposed Proximity Filter?
I am trying to set it up so that a views global filter https://drupal.org/project/global\_filter can set the distance and city for the proximity filter for Geofield? What are the steps to do this?

# Answer
> -1 votes
Add a filter that precedes that filter that is not exposed and creates the initial filter you want. Usually you can do this with most views handler filters, so it *should* work with the proximity filter.

---
Tags: views, location
---


# Question
Title: How to show different content for various roles for the same url?
we have a use case whereby 6-7 types of user roles can access the same nodes (lots of them) and see different content based on roles.

For example a user with role A accesses sitename.com/faq and sees a particular content. However when a user with role B accesses sitename/faq that they see some different content as based on their role. (Please note that we are not merely talking about translation here)

How would I get about getting this setup? I know that if we had 2-3 nodes that required such access that I could check it programmatically however in this case it is a lot of nodes and doing that would be problematic.

Any tips or modules that you can think off that would help me with that?

Many thanks

# Answer
> 1 votes
I like using page manager with variants set on role based contexts. Assuming you've got chaos tool suite installed, you already have it.

If you haven't made use of page manager, it is accessed from /admin/structure/pages

A decent introduction to the sort of thing you want to do can be found here: http://nodeone.se/en/learn-page-manager-part-1-overview

At its simplest, page manager can be used to override default paths using a redirect, based on context settings, like ... say ... the roles of the currently logged in user. It integrates well with panels, providing context for panels based content, including views content panes.

Using the Context module might work for you too, depending on how you've set up your pages. I use that one for placing blocks based on user roles and paths. https://drupal.org/project/context ... um ... "block system on steroids" is one description of it.

Without knowing a bit more about how you've set up your FAQs, that's about all I can give you for now.

# Answer
> 1 votes
Sounds like either the Content Access module, the ACL module, (maybe) the Nodeaccess module, or possibly even a combination thereof, would be a good place to start.

---
Tags: nodes
---


# Question
Title: Nodes containing simple field collection not displaying properly
I have a content type to which I added fields like description, image and a field collection containing two simple text fields. Editing and viewing in the backend (logged in as admin) works properly. But when I log off and go to the node it just shows the title and no more. Can anybody lead me to the right direction to find the error?

EDIT: If I leave the field collection fields empty, the other fields get displayed to other users, if I fill in something nothing shows up, just the title

# Answer
> 0 votes
I think I have found the answer, but not really the solution. I deleted the following code in my node.tpl which caused the malfunctioning of field collection:

```
<?php if (!empty($content['links'])): ?>
<nav class="links node-links clearfix"><?php print render($content['links']); ?></nav>
<?php endif; ?>

```

But I do not understand why.

---
Tags: entities
---


title: How to add javascript to drupal 7?

text:
# Question
Title: How to add javascript to drupal 7?
I found a responsive menu code here and I want to add it to my Drupal 7 site. I have no experience with JavaScript, but I thought that if i just copy the script into mytheme/js/menu.js, call it in mytheme.info, and add the HTML to a block, I will have the script up and running.

The HTML part works fine, but the JavaScript part isn't working.

Why doesn't my JavaScript code work?

# Answer
Well adding JavaScript can be done through drupal\_add\_js().

You can add the JavaScript code in your template.php file.

1. Create a cool.js file where you copy the JavaScript code
2. Put the file in your themes/MYTHEME/js folder
3. In your template.php file, create a page preprocess function

```
function MYTHEME_preprocess_page(&$vars) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/js/cool.js", array("preprocess" => True));
}

```
4. Clear the cache
5. Load your page and check the page source code to see if **cool.js** is being loaded; use `ctrl`+`f` to see if the file is present there
6. If the effect is still not coming, then verify the IDs in the HTML are correct
> 1 votes

# Answer
You can use Singe page website module to create single page website in the drupal 7.

You can check example for implementation of the module.

I have also checked your site engeego and I found that there is some javascript issue.

If you include javascript in drupal 7 theme, you need to enclose this into below function.

```
(function($) {

    //your code

})(jQuery);

```
> 0 votes

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


# Question
Title: How do I rewrite attached file field output in Views to override the filename?
I am trying to build a simple Views Accordion view to display support documents. I created a simple content type with three fields: Group (my category), Document Title, and File. The only way I can get the attached file to appear is by inserting the field Content: File. That links to the file and displays the little PDF icon, but shows the actual filename as the hyperlink text. I would like to use the Document Title field contents as the hyperlink text, but can't figure out the proper way to do this. I have tried hiding the file from display and rewriting the output of the Document Title field to be something like: `<a href="[field_file]">[title]</a>` However, it appears Drupal is rendering the link to the file instead of inserting the path to the file, as it shows the PDF icon and the filename.

Is there a way to override the hyperlink text when showing an attached file?

# Answer
> 2 votes
Certainly, you just have to use the correct formatter to start with. I am guessing that you are using the "Generic Files" one. If you instead select "Path to File" you can then use rewrite output the way you mention in your question. Little gotcha: make sure the title field you are using isn't "linked to its node" or things will get odd :)

(Note, I am suggesting you rewrite the file field instead of the title field)

---
Tags: views, navigation
---


# Question
Title: How to add multiple value field in webform
I want to add a file field called picture to a webform, and Want it to be a multiple value field to allow users to upload more than a picture

# Answer
Webform Multiple File Upload allows user to upload multiple files on a webform and you can also limit the number of files, see the below image.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: When I save a user account as an admin, I get logged in as that user
I'm experiencing a strange issue that I'm having a really hard time debugging.

When I save a user account (of an authenticated user) as an admin, the account is saved, but when the page reloads I get an access denied and I am suddenly logged in as the user I saved, not the admin. This happens whether I save the account in the UI (via the People page) or save the account using a rules action.

Recently, I added a custom function and modified a few of my rules, so these changes are likely to be the cause of the problem. The site is version-controlled using git, so I can roll back to a working version, but I would like to attempt to determine what I did wrong.

I have Netbeans working with Xdebug. I just don't know where to set breakpoints or how otherwise to start looking for the source of this problem.

# Answer
Can you re-produce the problem from CLI?

Using `drush scr`, bootstrap, login as user 1, save a new user, check if your ID changed.

If you can do this from CLI, `git bisect` can be very helpful in finding the commit that caused it.
> 2 votes

---
Tags: debugging
---


# Question
Title: CKeditor + Media: insert image tag rather than link to image
I want to insert an image into node body content using Ckeditor and Media. Everything seems to work except all I get is a link to the image file but I would like it to insert an image tag. When I click Ckeditor's **Add Media** button and choose an image I get an option **Current format is** and I can choose from **Default, Preview** and **Teaser**. While the first two return nothing, Teaser at least inserts a link to the image file.

How can I get it to insert an image tag instead of a link?

I am using Drupal 7.22 with Media 7.x-2.0-unstable7, Wysiwyg 7.x-2.2 and the latest Ckeditor.

# Answer
> 2 votes
Insert Module will do that, it will place the image in body field. Support for all major WYSIWYG editors, including tinyMCE, CKeditor.

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

# Answer
> 0 votes
After lots of trying and searching for answers I finally found an answer. It turns out that **Media 7.x-2.0-unstable7 and Wysiwyg 7.x-2.2 currently only support CKeditor up to version 4.0.3**. Any version greater than that will, at least for now, fail. If you have to downgrade your CKeditor version and have mixed up buttons make sure to empty your cache. After that the Media button works as expected and lets you insert images using image styles defined at `admin/structure/file-types/manage/image/file-display`. Hope this helps anybody!

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


# Question
Title: Migrate Organic Groups from a Drupal 6 database to Drupal 7
I'm using migrate\_d2d to migrate my Drupal 6 site to Drupal 7. I've already created several working migration classes to migrate the content of the D6 site into the D7 site. Now I'm working on migrating the organic groups and the related user memberships. I've read that OG (i'm using 7.x-1.19) got a build in migrate routine. When I checked /admin/config/group/group-migrate, I hoped to see some settings where I could insert the data of my legacy database, my User Migration class, click a button and be done with it. :-D Unfortunately, that's not the case.

I have a hard time to find any documentation of how to use the migration functionality which comes with OG. Could anyone please give me a hint how one is supposed to migrate OG groups/memberships from a D6 database to a D7 database?

Many thanks!

# Answer
The migration classes that come with Organic Groups are for doing a full site upgrade only. In other words, if you were to drag Drupal 7 files over top of your Drupal 6 site and run an upgrade, the migrate classes that come with OG would be helpful.

However, in your case (and mine) you are doing a full migration from an old Drupal 6 site to a fresh, empty Drupal 7 site. The classes provided by OG will not be helpful here, nor even show in your migration list.

What I'm currently doing is working on a manual migration path for OG groups using migrate\_d2d to pull all the group nodes over. Then I'll write another migration to add users to these groups by injecting them into the right database tables. THEN as each of my other node types are migrated over, they will add themselves to the OG tables that track which content are part of which group.
> 2 votes

# Answer
Documentation on how to use the migration features integrated into OG is available since 2013-06-19 here in the "Administration & Security Guide":

Migrate: Contributed module support: Organic Groups
> 0 votes

---
Tags: organic-groups, migrations
---


# Question
Title: After upgrade from OG6 to OG7 directly to ver. 2.x: Is there any possibility to use OG migrate (available only in OG 1.5)?
I´ve realised that OG Migrate is only in 7.x-1.5 but NOT in OG 2.x.

I´ve accidentally updated my site from D6 to D7 directely to OG 2.x.

Is there anything I could do to use OG migrate?

# Answer
> 0 votes
For OG 7.x-2.2, the migrate functionality is now coming with the OG module itself. No additional module is needed. Documentation can be found here:

Migrate: Contributed module support: Organic Groups

Which means the functionality is no longer in migrate\_og (where it was for OG 6.x-1.x) and also no longer in migrate\_extras (where it was, I think, for OG 7.x-1.x).

---
Tags: organic-groups, migrations
---


# Question
Title: how to add field_image widget (imagefield crop) to a custom form api
How can i add to my custom form api in my custom module the default widget from field\_image? I am using imagefield\_crop module widget and it works in node/add form, but i cannot replicate it in my custom form api.

# Answer
> 1 votes
Problem is, Field API and Form API are separate things. You can add form elements to custom forms created with Form API, and you can add fields to custom entities created with Field API, but you can't really cross the border. Well, you can wrap form element into a field, but not the other way around.

---
Tags: entities, media
---


title: Creating an “unzip” custom module

text:
# Question
Title: Creating an “unzip” custom module
I am creating a website that will allow users to upload projects. Project submissions will consist of .zip file. Once the user uploads their project, I need to unzip the .zip file and find the .html file . Also, it needs to be possible to upload these projects through the web interface "Add New Content" and through Node.create by way of the services module. note I'm using the PclZip library. This is part of the code I use when the uploaded file but it does not extract the file

```
function custom_unzip_node_submit($node, $form, &$form_state) {
    if ($node->type == 'flipper') {
    $p_zipname = base_path() .'sites/default/files'.$form_state["complete form"]["#node"]->field_file["und"][0]["filename"];
    $to_extract = base_path() . 'test/';

    $zip = new PclZip($p_zipname);
    $ar = $zip->extract(PCLZIP_OPT_PATH, $to_extract);

    }
}
```

# Answer
> 2 votes
Keep in mind Drupal 7 has a built in library for working with archive files.

Archiver Zip

See also system.archiver.inc

Perhaps you'll have more success using that.

Lastly, make sure the path to the uploaded file is correct for extraction.

---
Tags: views, theming
---


# Question
Title: Reuse file uploaded via (File|Image|Whatever)Field in another node
I noticed the existence of this file\_usage table in D7's database and I was wondering if it's possible to link in a new node the same file I uploaded using a file field in a previously created node. This seems logical to me, yet I can't seem to find a way to do it.

# Answer
> 3 votes
The FileField Sources module expands the file field widget and allows the user to select new or existing files through additional means, including re-use files by an auto-complete textfield, attach server-side files uploaded via FTP, transfer files from a remote server (cURL required) and select existing files through the IMCE file browser.

The Media module (2.x) provides and additional file field widget which use its media browser to upload or select a (media) file.

# Answer
> 1 votes
I know this an old thread, but https://drupal.org/project/media does what you want. (or at least the goal of media is to do what you want.)

If you can use media 2.x (as I write this there are several show stoppers with wysiwyg editors and 2.x) I would go that route.

---
Tags: 7, files, media
---


# Question
Title: Don't render html.tpl.php for a specific path
Is it possible to load page content without rendering html.tpl.php? I mean on default Drupal has the follwoing:

Html.tpl.php --\> Page.tpl.php --\>...(etc.)

my goal is to remove Html.tpl.php for a custom path (site://ajax-unesco)

so:

page--ajax-unesco.tpl.php --\> ... (etc.)

# Answer
> 3 votes
You could do something like this:

```
/**
 * Implements hook_menu
 */
function MY_MODULE_menu(){
  $items = array();
  $items['clean/view'] = array(
    'page callback'    => 'MY_MODULE_clean_view',
    'page arguments'   => array(2, 3),
    'access arguments' => array('access content'),
    'type'             => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Menu callback for clean/view
 * Output view without wrapper page markup
 */
function MY_MODULE_clean_view($name, $display = 'default'){
  // Note views_embed_view performs views access check
  print views_embed_view($name, $display);
  drupal_exit();
}

```

You can then use the dynamic path `/clean/view/view_name/display_id` to render the View without the wrapper markup.

---
Tags: theming
---


# Question
Title: Specify which Migrate entries need to be updated using prepareRow
I have made a Migration that i run with Cron. My highwater field is the date changed, which is present in the XML (source) document. Then I do this in my cron function:

```
 $result = $migration->prepareUpdate();
 $result = $migration->processImport();

```

Problem is is this will update ALL nodes from the XML. I would like to only update those that have been changed, according to their modifiedAt date. If I just do:

```
 $result = $migration->processImport();

```

Then nothing at all updates. I think processImport() would work if it were just about importing new items, but I also need to update any existing items that have changed. The ones that don't need updating can be skipped, of course. Is there another method I could call here? Is there a way I need to set up some kind of prepareRow to mark items as needing updating?

# Answer
The recommended way to do what you are trying to do is with drush. Is drush available to you? if so have cron execute a drush mi command. See https://drupal.org/node/1561820. Also make sure your highwater mark is set up correctly. See https://drupal.org/node/1223936.
> 0 votes

---
Tags: 6, migrations
---


# Question
Title: How to extend a view plugin style implemented by another module?
I have some requirements that leads me to extend the functionality of a views plugin style implemented by a contrib. module by adding some fields and validations in it's configuration form.

I started to implement a custom module to alter this by extending the `contrib_views_plugin_style` Class implemented by the contrib. module using the views API. I added the fields with no problem but I'm worried about the `render` method because I don't want to have a copy of the contrib. plus my custom code and I still not sure if this is the best way to do this.

I plan to post this to d.o by posting a patch or maybe another contrib. module but it would be nice if I could keep just the new code and didn't have to have any duplicated code.

Here is the contrib module code:

http://drupalcode.org/project/leaflet.git/blob/refs/heads/7.x-1.x:/leaflet\_views/leaflet\_views\_plugin\_style.inc

There is another way to achieve this goal?

PS. I prefer to start without hacking the contrib module but if there is no way to do this it's OK.

# Answer
First you need to have a `my_module.views.inc`, which can have basically the same contents as http://drupalcode.org/project/leaflet.git/blob/refs/heads/7.x-1.x:/leaflet\_views/leaflet\_views.views.inc, but with changed names.

You can leave the handler the same, in which case you need to leave the path the same too. Otherwise you can create your own hadler in `my_module_views_plugin_style.inc` along the lines of

```
class my_module_views_plugin_style extends leaflet_views_plugin_style {
   // ...
}

```

You then only need to define any methods that you want to modify:

```
function option_definition() {
  $options = parent::option_definition();
  // your changes here
  return $options;
}

```

You also need a theme file. If you are modifying the display at all, you probably need to just copy the theme file over from the dependency, and change the `'theme'` line in `my_module.views.inc`.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do you delete a content type's URL aliases in bulk?
I have a content type where I want to delete all of its URL aliases in bulk. Currently the pathauto url alias page only has the option to delete all content url aliases regardless of what type it is.

How can you delete url aliases in bulk matching only a specific content type?

Also would it be okay to delete the url\_aliases via phpmyadmin? I'm not sure if the url\_aliases table is linked to something else.

# Answer
I'd go with Views Bulk Operations.

* set the pathauto path for the content type to the default you want, but don't bulk update
* create simple view for the content type you're interested in
* add the field Bulk Opertations: Content
* Under Bulk Operations Settings check Enable "Select all items on all pages"
* select Update Node Alias
* add filters as required

navigate to the view page, select all, uncheck any special cases, and give it a whirl

but maybe backup first
> 8 votes

# Answer
I'd do it as an SQL query. Run as a SELECT first, to verify that all is well:

```
 SELECT alias FROM node n JOIN url_alias u ON CONCAT('node/', n.nid) =
 u.source WHERE n.type='my_type'

```

then edit it to make it a DELETE:

```
 DELETE u  FROM node n JOIN url_alias u ON CONCAT('node/', n.nid) =
 u.source WHERE n.type='my_type'

```
> 11 votes

---
Tags: 7, nodes, path-aliases
---


# Question
Title: Drupal 7 and taxonomy views - sorting by number in URLs
How can I tell Drupal 7 that 99 should go *AFTER* 100 when sorting items (descending) according to a number in URL or in Title?

I have this taxonomy view for magazine articles. Published issues range from 90 to 120, for now. Sorted ascending, the list goes from 100 to 120 and then 90, 91, and so on. Descending, I get 99, 98, 97.... 91, 90, 120, 119 and so on.

Sorting by posting date is not an option, since we're moving to the new Drupal site lots of old content and new issues will be loaded before very old ones.

# Answer
Your data is being sorted alphabetically rather than numerically.

The simplest solution would be to store the 'Issue numbers' as an integer rather than as a sting. Views will sort numeric fields the way you're looking to sort them without any fuss.

This obviously won't work if you ever have issue numbers that contain anything but but numbers.
> 1 votes

# Answer
You might also try using the Views Natural Sort module to solve this problem. A natural sort algorithm is intended to order mixed alphabetic and numeric data much as a human being would.
> 1 votes

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


# Question
Title: Drupal, Displaying a Content list of a User from their Profile, accessible by anyone via Views
I am running Drupal 7 and I would like to know how to create a View that displays as a tab on a users profile that displays all of his or her created content. This is what I have so far, but it only shows the tab for the logged in user, no one else can access it.

I got most of the code from here.

# Answer
It seems like you were very close. I would add on to the contextual filter. You need to provide a default value for the filter. Either of the following will work:

* Using PHP Code. Enter the following into the box "return arg(1);" without the quotes.
* Raw value from URL. Change Path component to 2.
> 0 votes

---
Tags: views
---


# Question
Title: How do I cache my custom entities using entity api with entitycache?
I have implemented custom entites, extending on Entity API. This is essentially identical to what the Model module does with a few extra customisations (fields, solr/facet integration etc).

I want to cache my custom entities using the Entity Cache module to get fast loading of entities when using Views and Apachesolr along with automatic cache updating when my entities are updated.

What do I have to do to implement this?

# Answer
You can achieve this quite easily with a few hooks and additions to your existing hooks.

Define the cache table in your hook\_schema() implementation in your module's .install file:

```
// Optional cache table for entitycache support.
$schema['cache_entity_my_entity'] = drupal_get_schema_unprocessed('system', 'cache');
$schema['cache_entity_my_entity']['description'] = 'Cache table used to store my_entity entity records.';

```

This adds a db table that can be used to store your cached entities.

Add an update hook to create the table:

```
function my_entity_update_700X() {
  if (!db_table_exists('cache_entity_my_entity')) {
    $schema = drupal_get_schema_unprocessed('system', 'cache');
    $schema['description'] = 'Cache table used to store my_entity entity records.';
    db_create_table('cache_entity_my_entity', $schema);
  }
}

```

Enable entitycache in hook\_entity\_info(). Add this near the bottom before return $info;

```
if (module_exists('entitycache')) {
  $info['my_entity']['field cache'] = FALSE;
  $info['my_entity']['entity cache'] = TRUE;
}

```

Implement hook\_flush\_caches() in your .module file:

```
/**
 * Implements hook_flush_caches().
 */
function my_entity_flush_caches() {
  return array('cache_entity_my_entity');
}

```

And that's it! Entity API takes care of the interactions and things like load() and resetCache() (I found you have to implement those functions when adding entitycache functionality to non-entityapi entities)
> 4 votes

---
Tags: 7, entities
---


title: Arbitrary rating field

text:
# Question
Title: Arbitrary rating field
I need a field that will allow content editors to enter a rating while editing a node, with the options 'yes', 'no', 'maybe' and 'unknown'. I then want to be able to display those ratings in a view, as images (tick, cross, fence, ?). I need to be able to have more than one on each node.

I can't do this with the rate module, because it doesn't do fields (there is a rate field issue, but it's not moving very fast). Fivestar only does five-star ratings, so that's out.

Optionally, I would also like to be able to give each result a numerical value, so that I can do calculations across fields (e.g. median).

Are there any options out there that can do this kind of rating?

# Answer
> I need a field that will allow content editors to enter a rating while editing a node...

You could use Drupal's built in Field API to do this. Given that a node will already be in edit mode while being rated, you wont need any additional add-on modules.

If you use the integer type, calculations should be simple. You can override the text like this:

To add the images next to each item, you could use CSS. Each element should have the necessary classes to theme them as required.
> 1 votes

---
Tags: rating
---


title: How to hide the View tab in user page?

text:
# Question
Title: How to hide the View tab in user page?
In the user page (www.example.com/user), there are `[View | Edit]` tabs. Is it possible to hide the `View` tab and leave `Edit` tab there?

# Answer
Use Tab Tamer, which allows you to move, hide and disable tabs on various pages.

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

# Answer
You could also just use `hook_menu_local_tasks_alter()` in D7:

```
function MYMODULE_menu_local_tasks_alter(&$data){
foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "user/%/view"){
            unset($data['tabs'][0]['output'][$key]);
        }
    }
}

```

Documentation
> 13 votes

# Answer
If you give the appropriate permission to the user, only then the *view* and *edit* tag will visible otherwise it will not be visible. (For checking you can sign out from the website and click the menu in user page. The view and edit tag will not visible)
> 0 votes

---
Tags: 7, users
---


# Question
Title: How do I use contextual filters and relationships to show related articles?
So, I've been trying to get this figured out for most of the day. I had it essentially working in the previewer at one point, but now it doesn't seem to work at all.

Use case: each node published with the content type "Article" comes with a Taxonomy field for included tags. What I'm trying to do is to create a block that appears under the article with a series of thumbnails that link to other articles. These articles in turn are related based on the tags used in each article.

So, the question is:

1. What would be a good way to set this up using Contextual Filters and Views to have the View itself automatically see the field\_tags used as a Taxonomy term reference in an Article, and have it automatically display the output based on the tags of each article?

I've tried setting up the Contextual Filter to be aware that the terms would be in the Content Type: Articles via the Relationships filter, but frankly I'm kind of stumped as to what I need to do to even accomplish this.

# Answer
I have implemented the same in one project in Drupal 7 to display products of same catalog.

You can create a views of article content and can create a contextual filters for tags. It will display all the article of that tags.

You can follow below step:

* Add a contextual filter of tags. Checked radio button "Provide default value".
* Select "Taxonomy term Id from url" in the type drop down.
* Checked "Load default filter from node page" check box.
* Checked "Limit terms by vocabulary" check box.
* In the Vocabularies section, checked the check box of Vocabularies (tags) which you want to add filter in the views.
* Under the more section, checked "Allow multiple values" check box, so multiple tags can use filter the term.

You can find below image for reference.

You also need to add contextual filter of node id and follow below step, so current node page will not display in related views section.

* Add content: Nid contextual filter in the views.
* Checked "Provide default value" radio button and select "Content id from url" in the type drop down.
* Under the more section in contextual filter, checked "Exclude" check box.
> 1 votes

# Answer
Have you tried using Similar by Terms?

(edit) The problem with Views taxonomy arguments is that taxonomy is now contained in a field not some voodoo taxonomy module code. Because of this, some of the taxonomy API in Drupal 6 is not available in Drupal 7.

I use the Context module with Views Arguments from Context. I made a patch that ported it Drupal 7. This gives another option under Contexual filter in views to get the arguments based on the context or loaded objects and entities at that time.

This is a particularly uses function:

```
function taxonomy_node_get_terms($node, $key = 'tid') {
static $terms;
  if (!isset($terms[$node->vid][$key])) {
    $query = db_select('taxonomy_index', 'r');
    $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
    $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
    $query->fields( $t_alias );
    $query->condition("r.nid", $node->nid);
    $result = $query->execute();
    $terms[$node->vid][$key] = array();
    foreach ($result as $term) {
      $terms[$node->vid][$key][$term->$key] = $term;
      }
  }
return $terms[$node->vid][$key];
}

```

It should not have been removed from Drupal core. It will find the taxonomy terms that you use if you pass it the current node object.
> 0 votes

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


# Question
Title: Overriding a specific view mode html.tpl.php template
How can I override the html.tpl.php template for only the "teaser" view mode of the "Article" content type?

I found this on the Drupal 7 Template (Theme Hook) Suggestions page on drupal.org page, but cannot see how to drill down to a specific view mode for a single content type.

> **html.tpl.php** base template: *html.tpl.php* The following are some examples of how you may override the base template:
>
> 1. html--internalviewpath.tpl.php
> 2. List item
>
> html--node--id.tpl.php
>
> See html.tpl.php in the Drupal API documentation for more information.

Will I need to implement a page preprocess hook to accomplish this?

# Answer
> 8 votes
As I am sure you know, the *teaser* view is only/mostly used when a list of nodes are put together, eg, the promoted to front page listing, a View listing, etc.

So, let's say you have a View page listing the most recent Articles, and it's sitting at `www.yourhost.com/recent/articles`, you could override the `html.tpl.php` there by creating a `html--recent-articles.tpl.php` file in your theme and modifying it accordingly.

Views itself also allows the use of node templates when a node is presented in a listing; if that is what you are needing or requiring, the template files there are along the lines of `node-view-VIEWNAME.tpl.php.`

# Answer
> 1 votes
Though Jimajamma is right, unless you're doing something insanely abstract, I wouldn't recommend doing a template override to simply edit a "teaser".

If you need more control of your displays, use Display Suite, maybe even combined with DS Extras if you need more functionality.

---
Tags: 7, theming
---


title: What is the use of has_js cookie?

text:
# Question
Title: What is the use of has_js cookie?
I am building an Android app that talks to Services module using REST endpoint. When I post any content without setting the "has\_js=1" cookie to the REST endpoint in JSON format, my content is never accepted by Drupal or Service module.

What is the use of has\_js cookie and why do I need to send along with my POST requests?

**Update:**

Following is my code to post the article content type. If I do not add the has\_js=1 cookie, article won't be posted to Drupal site.

```
 protected Integer doInBackground(String... params) {

        //read session_name and session_id from passed parameters
        String session_name=params[0];
        String session_id=params[1];

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://ec2-54-***-**-***.us-west-2.compute.amazonaws.com/cmac/rest/node");

        try {

            //get title and body UI elements
            TextView txtTitle = (TextView) findViewById(R.id.editTitle);
            TextView txtBody = (TextView) findViewById(R.id.editBody);

            //extract text from UI elements and remove extra spaces
            String title=txtTitle.getText().toString().trim();
            String body=txtBody.getText().toString().trim();

            //create JSON object to pass to Services endpoint
            JSONObject json= new JSONObject(" { \"title\":\""+title+"\",\"type\":\"article\",\"body\":{\"und\":[{ \"value\":\""+body+"\"}]}}");

            StringEntity se = new StringEntity( json.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se);

            BasicHttpContext mHttpContext = new BasicHttpContext();
            CookieStore mCookieStore      = new BasicCookieStore();

            //create the session cookie
            BasicClientCookie cookie = new BasicClientCookie(session_name, session_id);
            cookie.setVersion(0);
            cookie.setDomain(".ec2-54-***-**-***.us-west-2.compute.amazonaws.com");
            cookie.setPath("/");
            mCookieStore.addCookie(cookie);
            cookie = new BasicClientCookie("has_js", "1");
            mCookieStore.addCookie(cookie);
            mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);

            httpclient.execute(httppost,mHttpContext);

            return 0;

        }catch (Exception e) {
            Log.v("Error adding article",e.getMessage());
        }

        return 0;
    }

```

# Answer
> 2 votes
The has\_js cookie has been used by the Batch API. Without this cookie, or when JS is disabled in the client browser, the batch API will give you a WSOD.

See $\_COOKIE\['has\_js'\] must die.

If your service endpoint is dealing with the Batch API internally, then you will have this problem.

---
Tags: 8, services
---


# Question
Title: How do I programmatically create an entity reference in hook_entity_info()?
Is there a way to create an entity reference in hook\_entity\_info? I was hoping for something like the following.

```
'entity keys' => array(
  'id' => 'id',
  'store_ref_id' => 'store_ref_id',
),

```

I have a content type store with its ID, and a new entity\_type product. I would like to have a field in the new entity referenced to content type.

How can I do this?

Would it be better to re-use the already created field, which is used as reference between content types?

# Answer
You can attach this field like any other:

```
function MY_MODULE_install() {
  // Create a field for company reference to be used by various entities
  $field = array(
    'field_name' => 'company_reference',
    'type' => 'entityreference',
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'cardinality' => 1,
    'translatable' => FALSE,
  );
  field_create_field($field);

  // Attach the company reference field to employee instance
  $instance = array(
    'field_name' => 'company_reference',
    'entity_type' => 'employee',
    'bundle' => 'employee',
    'label' => 'Company',
    'required' => false,
    'widget' => array(
      'type' => 'options_select'
    ),
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'display' => array(
      'default' => array('label' => 'inline', 'type' => 'entityreference_label'),
    ),
  );
  field_create_instance($instance);
}

```

Code sample taken from this more comprehensive manual.
> 7 votes

---
Tags: entities
---


# Question
Title: Having issues getting solr search facets to appear on non-search pages
I'm using the solr search integration module with facet api on drupal 7 and I'm having issues getting the facets to show on non-search pages. I've checked the box for non-search pages and added a few different paths but nothing appears on those pages in the regions that I assign the facet blocks. It seems that the blocks are not receiving any data to populate and I don't know why. Any incite on what I'm doing wrong would be greatly appreciated.

# Answer
This is also something I want whereby the search facets are visible alongside a content type.

This problem applies to search facets in general (e.g. for those who don't use solr but use 'database search' - a "poor man's" version with less demanding requirements, suitable for shared hosting.)

Facets are generated from search results - so on a page with no search results the facets will not appear. That appears to be the design, as explained here: Show facet filter even if there is no result

There are several possibilities that you (and I) could consider:

* How do I allow facets on my full content display page? \- here the answer is not to display faceted search on a content page / non-search page but rely on breadcrumbs to link back to a search page
* My preferred approach (not yet implemented): is to put search results on the same page as the content. These search results will be the same as those that one clicked through before the content page. In other words, the same list of results that contained the link to the content item are displayed on the page of the content item itself. These will of course be focused search items ("drill down"ed) results. These would serve a purpose for the user as "related" and follows convention - if you look at this site drupal.stackexchange.com you'll see related results. But we would probably want to display them in a smaller space, using a different view with theming and the view could restrict the number of items shown.
> 0 votes

---
Tags: 7, search
---