title: Returning results from facet fields

text:
# Question
Title: Returning results from facet fields
Is it possible to turn on facet field and use its results in custom module, for custom dropdown list (instead of a block) ? I installed Search API and Facet modules and successfully created facet block, but don't want to see results in a block.

# Answer
> 0 votes
You can create custom widget for facet api, after that you can put results from widget into drupal\_static as source data.

It's easiest way if not hack facetapi module.

UPD.

Seems I found better solution:

```
$adapter = facetapi_adapter_load('search_api@INDEX NAME');
$adapter->processFacets();
$processor = $adapter->getProcessor('FACET NAME');
$facet_values = $processor->getBuild();

```

---
Tags: search
---


# Question
Title: How to use node data in content type as hierarchical select
I have a content type having the following fields

Project Type (Node Reference - Select List) Project Name (textfield) Manager (user reference - manager role) - Select List Employee (user reference - employee role) - Checkboxes

Created two nodes as following

node-1(see Image)

**Project Name** \- Project-1

**Manager Name** \- Manager-1

**Employee** \- Emp-2, Emp-3

node-2

**Project Name** \- Project-2

**Manager Name** \- Manager-3

**Employee** \- Emp-1

I need to use these fields data in another content type like follows

All Project names to be listed in select list(like node reference). If I choose Project-1 , the relative Manager Name (Manager-1) and Employees(Emp-2, Emp-3) should be loaded automatically(like hierarchical/chain select).

Is there contributed module available for this or I need to create a custom module for this?

# Answer
> 1 votes
It looks like you need Reference field option limit, or module with similar functionality:

> This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.
>
> This is best illustrated by examples:
>
> *(...)*
>
> **Example 2: sports and teams**
>
> Suppose you want news stories to be marked as being about a sport and a particular team for that sport, perhaps using taxonomy terms for both. To make editing easier, you would probably like want the 'team' dropdown to be limited to just teams for the current news story's sport.
>
> To achieve this with this module, add the 'sport' field to both news story nodes and team taxonomy terms. Hence the team 'Chudley Cannons' would have as its sport taxonomy term 'Quidditch'. (This probably entails taxonomy term reference fields on terms themselves... which was bound to happen with FieldAPI sooner or later.)
>
> Thus, when editing a news story node, selecting 'Quidditch' as the sport will cause the team reference field widget to update to show only teams which also have 'Quidditch' as their sport.

If this module is not *exactly* what you want, it can be a good start for coding own functionality. At least it solves all AJAX interactions for you, so only part you might need to alter is the actual selection.

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


# Question
Title: Is there a way to easily add image swap/rollover to images on a Basic Page?
I would like to do some simple image rollovers on a Basic Page, without having to write a bunch of individual CSS cases for each specific image. (Ie. - swap Img1 for Img2 on mouseover.) Is there an easy way, or a useful module that anyone knows of? I didn't find anything on drupal.org.

# Answer
> 0 votes
You can try Rollover Filter module. This is the only module for rollover effect AFAIK.

> This module provides a simple method to enable content editors to use image rollover states. It makes no checks against the referenced image types, it simply converts \[rollover\] wrappers into actual rollover images. It does use a Javascript based approach, and causes no harm to images in an environment where there is no Javascript.

---
Tags: media
---


# Question
Title: Creating node-based photo galleries with prev/next links within each taxonomy (specific gallery)
I want to create a collection of photo galleries where each gallery has it's own main page with thumbnails, and clicking on each thumbnail takes you to the node for that thumbnail with the full-size version of the image as well as next/prev links to go to other node pages within that same gallery. I don't want to use colorbox or lightbox, all node-based per image entry per gallery.

My current plan is to use taxonomy to specify the different galleries, use views to create the individual gallery homepage, and use a custom content type for each image's node. I'm not sure how to get the next/previous links on the node page to only go to nodes within that specific gallery, and couldn't find a module upon my initial search.

I'll be using Drupal 7. Are there any modules that would do this, or is there a better approach to achieving the result in a way other than what I'm planning?

# Answer
Well, it looks like the Drupal 7 version of Node Gallery has everything I need. I installed it, and it took care of it without any custom configuration needed.
> 1 votes

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


# Question
Title: Search API and Facets API with multilingual taxonomy
I have some taxonomy terms and the settings look like this.

All these terms have been translated.

After indexing the content with Search API and Facets API, the facets are not shown with translation.

Why is it happening?

# Answer
> 0 votes
To localize FacetAPI you should install FacetAPI i18n.

> The Facet API Translation module integrates the Facet API and Internationalization projects allowing site builders to translate configuration settings. This module also overrides common mapping callbacks, such as the content type mapping callback, to translate the display name of facets.

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


title: Different logo on specific page / node

text:
# Question
Title: Different logo on specific page / node
I have a special page called www.mydomain.com/special (whcih is a page node type). Only on that specific page, I want an extra image in the header of that page (next to the logo)

The logo and sublogo's is contained in the page.tpl.php provided by the previous themer.

What I would like to add in the page.tpl.php is somthing like:

```
if I am on page xyz
  <div>extra logo</div>
endif

```

It this possible or am I totally wrong?

# Answer
If you know the node `NID` of this special page, it would be a quick...

```
<?php if ($_GET['q']=='node/NID'): ?>
  <div>extra logo</div>
<?php endif; ?>

```

...in your `page.tpl.php` file. You could also create a special template for this node:

```
page--NID.tpl.php // for Drupal 7
page-NID.tpl.php  // for Drupal 6

```

...and have it in there all the time.

If you want to make sure that `www.example.com/special` uses a special template regardless of what `node/NID` it is really, eg, `special` is really an alias for `node/6` or something, then you will need to get a bit more "special" with some preprocessing to look at the path alias and check if it is `special` and then do things different. And I say preprocessing because there should be as little logic in the templates as possible.
> 2 votes

# Answer
current\_path() function should be available in page.tpl.php. Just check the result and add what you need.

Or, like pointed out in the comment, duplicate page.tpl.php and name it page--special.tpl.php, clear your cache, and add what you need. Keep in mind that this new .tpl will apply only to your /special page, so you wont need to check the url.
> 0 votes

# Answer
If could, in template.php of your theme, declare preprocess\_page hook and add a variable:

```
<?php

function yourtheme_preprocess_page(&$vars) {
  // Change this "if" with your logic
  if (current_path() == 'mypage') {
    $vars['custom_text'] = 'custom text';
  }

}
?>

```

Next, in your page.tpl.php, add the variable near the title, like this:

```
<h2><?php print $title ?>
  <?php if ($custom_text) { print $custom_text; } ?>
</h2>

```
> 0 votes

---
Tags: theming, 7
---


# Question
Title: Prev/Next on field group horizontal tabs
I'm using entityform and Field group to create a multi-step form, using Horizontal tabs.

I'd like the Prev/Next buttons, that show when you use Multipage, to show when using horizontal tabs. i.e tabs + Prev/Next

I'd like pointers on how to go about coding it myself (if it's not currently configurable) as I don't know where to start.

# Answer
> 2 votes
OK, well before this is closed, I will post what I did in the hope it might help someone.

I added a #tab\_back/#tab\_next buttons to the form, and used a bit of jquery to handle the UI.

```
  var current_tab = 0;
  jQuery("#tab_back").hide();
  jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();

  function click_tab(inc)  {

    newtab = current_tab + inc;
    if (newtab >= 0 && newtab <= 4 )  {
      jQuery('.horizontal-tab-button-'+newtab).find("a").click();
      current_tab = newtab;
      jQuery("html, body").animate({ scrollTop: 0 }, "slow");
    }
    return false;
  }

  jQuery("#tab_back").click(function () {
    click_tab(-1);
    return false;
  });

  jQuery("#tab_next").click(function () {
    click_tab(1);
    return false;
  });

  jQuery('.horizontal-tab-button-0').find("a").click(function () {
    current_tab = 0;
    jQuery("#tab_back").hide();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-1').find("a").click(function () {
    current_tab = 1;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-2').find("a").click(function () {
    current_tab = 2;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-3').find("a").click(function () {
    current_tab = 3;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-4').find("a").click(function () {
    current_tab = 4;
    jQuery("#tab_back").show();
    jQuery("#tab_next").hide();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').show();
  });

```

For what it's worth, I didn't really need tutoring, just help knowing which avenue to explore as it could have been done many different ways. Anyway, hope this helps someone. feel free to pick at my javascript... It's not my forte.

---
Tags: 7, entities
---


# Question
Title: Why would my import of multiple selections work in one content type but not the other?
I've got two content types that both have one off CSV file imports. They both have fields where you can select multiple values. The csv is comma delimited and the multiple selection data, for the field in question, is separated from the rest of the data by quotation marks, within the quotation marks there are no spaces between values; each value is instead comma separated.

For one of the content types this works perfectly, multiple values are put into the field. This field is a node reference.

However for the other content type this doesn't work instead if there are multiple values in the csv no values are given to the content, there are no error messages in any logs. This field is a multi check-box/radio input. I've checked and double checked to make sure the are no spelling discrepancies and I've ensured the field is set up correctly. If you manually create a new node of this content type you can allocate multiple values within this field.

Both fields are set to take unlimited values.

# Answer
Eventually finding no solution to the problem I decided to replicate the multiple field selection import that was working.

I made a new content type which contained nothing but the data items I wanted to be able to select and then used a node reference from the original content type. This isn't the most opportune method as whenever this data is displayed it is displayed as a link, a link which then takes you to a page which has nothing on it apart from the name of the data. However imports correctly put the desired data into the the field.

My suspicions regarding this issue are around how the node reference handles multi-fields. Perhaps handling them in a similar way to the import, as in \[datafield1,dataf2,"dataf3,dataf3,dataf3",dataf4\](as clarification, the previous example is how the csv is laid out). However I've no idea whether or not this actually has any grounds.
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: How to name a template file for the following theme hook suggestions?
I hardly managed it to create theme hook suggestions to work with different bean blocks, so I can use custom .tpl files like:

```
bean--{bundle_name}.tpl.php // currently only bunde is 'zielgruppe'

```

Here is the code so far:

```
/**
 * Override or insert variables into the block templates.
 */
function mymodule_preprocess_block(&$variables) {
  // For bean blocks.
  if ($variables['block']->module == 'bean') {
    // Get the bean elements.
    $beans = $variables['elements']['bean'];
    // There is only 1 bean per block.
    $bean = $beans[reset(element_children($beans))];
    // Add bean type classes to the parent block.
    $variables['classes_array'][] = drupal_html_class('bean-' . $bean['#bundle']);
    // Add template suggestions for bean types.
    $variables['theme_hook_suggestions'][] = 'bean__' . $bean['#bundle'] . '_tile';
    $variables['theme_hook_suggestions'][] = 'bean__' . $bean['#bundle'] . '_' . $bean['#entity']->delta;
  }
}

```

But for the last suggestion I just cant figure how to freakin name the file. `delta` prints `"für-angehende-lehrkräfte"`. I've tried to following file names which dont get noticed:

```
bean--zielgruppe-für_angehende_lehrkräfte.tpl.php
bean--zielgruppe-für-angehende-lehrkräfte.tpl.php

```

(appearently stack messes up ü characters in code areas)

For instance, `bean--zielgruppe-tile.tpl.php` works.

# Answer
> 1 votes
It appears that you have non-ASCII characters in your machine names. That is not a good idea, because they are used in file system constructs and your file system's character set encoding for non-ASCII characters is not necessarily the same as Drupal's internal character set encoding (UTF-8). Since the machine names are never displayed to users, the simple workaround is to only use ASCII characters in machine names.

Just replace the non-ASCII characters in your machine names with ASCII near equivalent characters (ü → u and so on), and you will not have to guess how to create file names matching your machine names.

PS: Note that this answer is just an expansion on the upvoted comment made by Mołot on Feb 13th. I think a full answer may help future readers. However, I'll delete it if the OP posts a self-answer or if Mołot prefer to expand the comment into a full answer himself.

# Answer
> 1 votes
You can also output the theme\_hook\_suggestion with DSM. You'll see all the suggestions and template candidates for your content. (https://drupal.org/project/devel\_themer could help you too)

---
Tags: theming, blocks
---


# Question
Title: How do I schedule a PHP function every 2 month?
I need, every 2 months, to execute some rule component programmatically, but I don't know how to do this.

If I use `hook_cron()`, I don't know how to check 2 months are passed from the last time it was executed.

I can check *'the 10th day of the month' + 'month number is even'*.

If cron tasks run twice a day, I cannot send 2 identical emails to users.

How can I achieve this?

# Answer
You can easly do this without having access to crontab/shell, by using following code in your cron\_hook:

```
// check if current day is 10th and month is an even number
if (date('d')==10 && date('m') % 2 == 0) {
    // get todays-date (format: yyyymmdd)
    $today = date('Ymd');
    // get info about last run
    $last_run = variable_get('my_last_run', 0);
    // check last run was not today
    if ($last_run!=$today) {
        // set last run to today
        variable_set('my_last_run', $today);

        /* Place your code here */

    }
}

```

For more info on the modulo-operator (the % ) check:
http://www.php.net/manual/en/internals2.opcodes.mod.php
> 2 votes

# Answer
Rules has a submodule called rules\_scheduler made for that purpose.
> 1 votes

# Answer
The best way is use crontab ,create a php file as example `mycorn.php` trigger your rule in it and create a crontab to run your php file every 2 month.
Just one note, please set permission only owner can execute it.

Below links help you , how to set cron.

http://www.adminschoice.com/crontab-quick-reference/
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
> -2 votes

---
Tags: cron
---


title: Menu based on URL

text:
# Question
Title: Menu based on URL
Is there way to show a menu based on the url provided?

For example:

```
sub1.test.com will provide menu A
sub2.test.com will provide menu B

```

Kind of a multisite principle but without using the actual multisite.

# Answer
You need this: https://drupal.org/project/domain

& https://drupal.org/project/domain\_menu\_access

Using domain module you can manage various settings like theme, block for specific domain.

Using domain menu access you can restrict specific menu link to appear in specific domain under menu configuration settings.
> 1 votes

---
Tags: routes, uri
---


# Question
Title: Specify on which subdomain to show node (Multisite with shared Database)
I'm using multisite with shared database. Is there any way I can specify on which subdomain I want the content to be displayed (on node creation)?

So If I create a node, I would like to have checkboxes that say (subdomain1, subdomain2, subdomain3).

Thanks in advance

# Answer
You need this:

https://drupal.org/project/domain

On each node it will ask to affiliate content for specific domain and they would appear only over those for which you have selected.
> 0 votes

---
Tags: 7, multi-sites, subsites
---


title: localhost subsites configuration

text:
# Question
Title: localhost subsites configuration
I know how to install a single instance of Drupal very well but I want to create a number of sub-sites under my Drupal installation. My file structure is as follows:

```
drupal7_main
 -sites
   --drupal7_sub1
    settings.php
   --drupal7_sub2
    settings.php

```

I'm developing on my localhost and the plan is to duplicate the structure on the production server.

However, only drupal7\_main works. When I visit localhost/drupal7\_main, Drupal is ready and configurable as usual; when I visit localhost/drupal7\_sub1, I get the following error.

> Not Found
> The requested URL /drupal7\_sub1 was not found on this server.

I get the same for drupal7\_sub2.

I'm trying to learn this process and would appreciate some help.

# Answer
> 0 votes
You need to create symbolic links in order that your `drupal7_sub1` and `drupal7_sub2` directories works. Those symlinks needs to target your `drupal7_main` directory.

To create a symlink, open a commandline tool and execute following commands (if your on a Windows machine). You need to put the correct paths depending your `localhost` configuration.

First go to root directory of your localhost

```
cd C:/wampp/htdocs/

```

Create symlink for each subwebsite (drupal7\_sub1, drupal7\_sub2)

```
mklink /D drupal7_sub1 C:/wampp/htdocs/drupal7_main
mklink /D drupal7_sub2 C:/wampp/htdocs/drupal7_main

```

Executing this will already give you a result when visiting `localhost/drupal7_sub1`. If everything went well, you should see your `localhost/drupal7_main` website.

Because your working with a localhost URL (and not real domain name, can be a development URL only existing on local, i.e. dev.yourproject.com), you need to slightly adapt your folder structure in order that each subwebsite uses its own `settings.php` and file folder for the `files` (uploads, css, ctools, js).

You need to prefix your subfolders under `drupal7_main/sites/` with `localhost`.

```
drupal7_main/sites/drupal7_sub1 --> drupal7_main/sites/localhost.drupal7_sub1
drupal7_main/sites/drupal7_sub2 --> drupal7_main/sites/localhost.drupal7_sub2

```

# Answer
> 0 votes
You need to configure your httpd.conf file

in your case you need to add this in your httpd.conf (assuming you using lamp)

```
<VirtualHost *:80>
 #DocumentRoot /opt/lampp/htdocs/html
 #ServerName localhost
</VirtualHost>

<VirtualHost *:80>
 ServerName drupal7_sub1
 ServerAlias drupal7_sub1
 DocumentRoot  /opt/lampp/htdocs/'site-root-folder'
</VirtualHost>

<VirtualHost *:80>
  ServerAdmin webmaster@localhost
 ServerName drupal7_sub2
 ServerAlias drupal7_sub
 DocumentRoot /opt/lampp/htdocs/'site-root-folder'
</VirtualHost>`

```

# Answer
> 0 votes
All your new sites vhost should be pointing to the drupal root installation where the index file lives and the entry point for all your sites, not to the site1 folder. "DocumentRoot /var/www/multisite" this should be the same for all your sites.

With multi-site a approach you can shared modules between sites (those in all folder), have different modules per site, you can have different databases per site and share tables between them.

Your drupal sites are going to share the same code base, One drupal core for everyone.

This can be useful https://drupal.org/documentation/install/multi-site This is also here How do I setup multiple sites with one database in Drupal 7 (or) Multisite Apache configuration with Drupal

---
Tags: 7, multi-sites, subsites
---


# Question
Title: Why doesn't JW Player work in a custom content type?
I downloaded *JW Player* and used it on the default *Page* content type that comes with Drupal to show videos; it worked seamlessly.

I created a content type with a video field and I attaching videos normally in both the fields, but when I use the content type I created, it doesn't show a video. It shows a blunt listing of the *Video Link*.

How can I make *JW player* show videos in the content type I created?

The following is the markup shown for the content types.

### Page

```
<div class="field-items">
  <div class="field-item even">
    <div class="jwplayer-video">
      <div id="a7638d2f8c40bfe2669593f3ee69e066_wrapper" style="position: relative; width: 200px; height: 200px;">
        <object type="application/x-shockwave-flash" data="http://player.swf" width="100%" height="100%" bgcolor="#ffffff" id="a76593f3ee69e066" name="a76593f3ee69e066" tabindex="0"><param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always"><param name="seamlesstabbing" value="true"><param name="wmode" value="opaque"><param name="flashvars" value="netstreambasepath=page24_2.mp4&skin=glow.xml&autostart=1&controlbar.position=none">
        </object>
      </div>
    </div>
  </div>
</div>

```

### Content type I created

```
<div class="field-items">
  <div class="field-item even">
    <span class="file">
      <img class="file-icon" alt="" title="video/mp4" src="/0065bd-doc/ops-lop/modules/file/icons/video-x-generic.png">
      <a href="/page24_3.mp4" type="video/mp4; length=4838313">page24.mp4</a>
    </span>
  </div>
</div>

```

# Answer
There are many ways you can do this

1. Jwplayer Drupal Module

Video : http://www.youtube.com/watch?v=mAAIfi0pYHw

2. Embedding jwplayer in HTML5

http://www.longtailvideo.com/support/jw-player/28839/embedding-the-player/

For your example :

WRONG CODE (dont use)

```
<div class="field-item even">

<span class="file">

<img class="file-icon" alt="" title="video/mp4" src="/0065bd-doc/ops-lop/modules/file/icons/video-x-generic.png">

<a href="/page24_3.mp4" type="video/mp4; length=4838313">page24.mp4</a>

</span></div></div>

```

Try This

```
<div class="field-items">

    <div class="field-item even">
        <span class="file">

            <img class="file-icon" alt="" title="video/mp4" src="/0065bd-doc/ops-lop/modules/file/icons/video-x-generic.png">

            <div id='playerNrEyADwjFyrz' onclick='jwVideoSetup('/page24_3.mp4')'></div>
            <script type='text/javascript'>
                function jwVideoSetup(src)
                {
                    jwplayer('playerNrEyADwjFyrz').setup({
                       file: src,
                       title: 'video title',
                       width: '100%',
                       aspectratio: '16:9'
                    });
                }
            </script>

        </span>
    </div>
</div>

```
> 0 votes

---
Tags: nodes
---


# Question
Title: The Search API module shows a two-words taxonomy term as two separated words, in its widget
I am using taxonomy terms to classify my content, and the Search API and Facets modules for searching.

I have some nodes that are tagged with "Asian Cuisine" term; after indexing the content, "Asian Cuisine" is handled as two separated words.

Is there a way to avoid it happens?

# Answer
> 2 votes
Based on your screenshots, consider using the "Taxonomy Term" type for the field indexes. This should remedy your issue.

By using Full Text, you're breaking up the taxonomy term names into searchable words. Use either the default taxonomy term value, or try using the "All Parent Terms" field.

---
Tags: taxonomy-terms, search
---


# Question
Title: $form_state values show node title instead of integer
I'm using a select list in my custom module. When I select some option in the list after submitting the form, I can see the `$form_state['values']['select_field']` is showing an integer.

How can I make the form\_state values to show the title of the list, instead of number of the selected option?

# Answer
Whatever you set as the array keys for options will be the values, so if you want to see option content rather than value, you need to set it up like that:

```
$form['select_field'] = array(
  '#options' => array('Text' => 'Text', 'More Text' => 'More Text'),
);

```

Or, leave the numeric keys where they are, and refer back to the original options array in your submit handler:

```
$selected_index = $form_state['values']['select_field'];
$display_value = $form['select_field']['#options'][$selected_index];

```

If you go with the first option, `drupal_map_assoc()` will probably be useful.
> 3 votes

---
Tags: forms
---


# Question
Title: How to print URL arguments in headers VIEWS
I have a blog with URL `http:/node/add/blog` and I am using a view discussion board to display the content of blog using VIEWS.

I want to add this URL `http:/node/add/blog` to Header view. Any idea? How to do it?

# Answer
You can use arg() function to access the url parameters.

Returns a component of the current Drupal path.

When viewing a page at the path "admin/structure/types", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".
> 0 votes

---
Tags: views
---


title: Cropping image with Drupal 7 api

text:
# Question
Title: Cropping image with Drupal 7 api
I tried below codes but nothing happen.Any ideas?

```
$image = image_load('/home/ok/sites/default/files/20140213030054333.jpg', $toolkit = FALSE);
//print_r($image);
 image_scale_and_crop($image, 350,700);

```

# Answer
> 2 votes
Taking a wild stab in the dark:

```
image_save($image);

```

---
Tags: media
---


title: How to use #ajax trigger_as?

text:
# Question
Title: How to use #ajax trigger_as?
I'm trying to figure out how to trigger an element with a link in a form using trigger\_as.

I tried the following snippet. The button ajax callback works, but the link doesn't. The link does seem to use the right name and value in trigger\_as (as seen in the js console), but the post callback doesn't return anything.

```
$form['add_more'] = array(
  '#type' => 'submit',
  '#value' => t('Add another item'),
  '#attributes' => array('class' => array('add-more-submit')),
  '#submit' => array('field_add_more_submit'),
  '#name' => 'result_fields_add_more',
  '#ajax' => array(
    'callback' => '__update_fields',
    'wrapper' => 'example-wrapper',
    'effect' => 'fade',
  ),
);

$form['add_more_link'] = array(
  '#type' => 'link',
  '#title' => t('add'),
  '#href' => '#',
  '#process' => array('ajax_process_form'),
  '#ajax' => array(
    'callback' => '_update_fields',
    'wrapper' => 'example-wrapper',
    'effect' => 'fade',
    'event' => 'click',
    'trigger_as' => array(
      'name' => 'result_fields_add_more',
      'value' => t('Add another item'),
    ),
  ),
);

```

I tried to follow this example, but didn't work: http://drupal.org/node/753270#comment-2910362 I also didn't find an ajax link in the rules module, only a button with an ajax callback. I thought I followed the documentation correctly: http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#ajax\_trigger\_as

EDIT: One fix is to trigger the submit event through javascript code, but I was really hoping the form api would be able to handle this itself: https://drupal.stackexchange.com/a/34375

# Answer
It's only working with form elements in Drupal 7 as of now, not with link elements.
> 0 votes

# Answer
No support for links, but for what its worth heres a working snippet that uses a select.

When the select changes it triggers the submit buttons callback. Note, you still have to define the callback on the select box as ajax.inc assumes all ajax enabled elements have one.

````
<?php

  $submit_name = 'product-submit-' . $node->nid;
  $form['product_id'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'my-form-wrapper',
      'callback' => 'product_change_callback',
      'trigger_as' => array(
        'name' => $submit_name,
      ),
    ),
  );

  $form['submit'] = array(
    '#name' => $submit_name,
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'product_change_callback',
    ),
  );
?>

````
> 1 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Arrange fields in a drupal form by multiple columns/rows
I'm trying to create forms that I can customize to display multiple elements in a column or row, instead of the current one field per line that seems to be the default.

I've been searching around for a few modules and so far have only come across one that would be able to do what I need which is Form Panel.

How do I edit or create forms where I have control of the layout? I would like to avoid code as much as possible.

# Answer
Are you talking about webforms or the regular, Field/CCK form?

While there should and might be better or cleaner ways to do it, I solved this problem in CSS, with quite a bit of futzing to make things line up exactly. Here is the CSS for aligning a webform into columns:

```
/* Set left quarter column via the label. Margin top aligns label with form item box */
.webform-component-textfield label {
  width: 24%;
  float: left;
  display: inline;
  margin-top: 2px;
  margin-right: 1%;
  text-align: right;
}

/* Align form text-box fields in next qtr column: */
.webform-client-form .form-text {
  width: 25%;
  float: left;
  margin-left: 2px;
  display: inline;
}

/* Third column (if you need it) in next column, through specific id selector */
#webform-component-last-name label {
  width: 14%;
  display: inline;
}

/* Fourth column on form text-box: */
#webform-component-last-name .form-text {
  width: 23%;
  display: inline;
}

/* Radio buttons in second column note use of plural RADIOS vs singular RADIO */
.webform-client-form .form-radios {
  width: 75%;
  float: left;
  border-bottom: 1px dotted #CCC;
  margin: 7px 0 0 0px;
}

/* Radio buttons  */
.webform-client-form .form-radio {
  width: 20px;
  float: left;
  margin: 2px 0 0 0px;
}
/* followed by labels: */
.webform-client-form .form-radios label.option {
  width: 13%;
  margin: 1px 0 0 0;
}

```
> 0 votes

# Answer
I did use the https://drupal.org/project/webform\_layout Module which does create a div container around one or more fields.

You may choose between Horizontal, Equal Width and Vertical Orientation. Further you can nest divs of Layout Boxes.

It is simple and does the job.
> 1 votes

# Answer
what about Field/CCK form how to arrange fields like Arrange field this only works content types i wanted eck.
> 0 votes

---
Tags: forms, panels
---


# Question
Title: Difference between Content: Updated date and Content revision: Updated date in Views
In views Filter criteria, What is the difference between Content: Updated date and Content revision: Updated date?

# Answer
I can see that the descriptions provided for both these filters can make things a little confusing. The below description and the image should help you out.

`Content: Updated Date` maps to `node.changed` and tells you the latest time when the node was changed. `Content revision: Updated data` maps to `node_revision.timestamp` when a particular revision of the node (not necessarily the latest revision) was created.

You can check this in the query put together by Views, as shown in the image below. Hope this helps.
> 6 votes

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


title: Appending extra columns to Views table

text:
# Question
Title: Appending extra columns to Views table
Can anyone tell me if there's a way to use hook\_form\_alter, or some other approach, to insert an extra column with to a views generated table.

I am trying to insert some buttons which will update node data when a user clicks on a relevant button.

# Answer
There are multiple ways you can add an extra column or a field to each row of your views output. And you can choose what is best for your use case.

For a Drupal 7 site you can use -

If you need to pass any kind of dynamic context to your custom extra field, say a node id, there are multiple ways to do that too.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Is there a dummy field to provide additional instructions to the users on node add form?
I'm building quite complex node form and I need to provide users with additional instructions how to fill the form. Are there any modules that would allow me to add sort of `dummy` fields with some HTML that would be displayed when user edits or creates new node? I don't want to save any data for these fields. I would like to be able to provide some HTML that will be displayed among other node form elements. Even plain text would do.

# Answer
> 1 votes
Try the Markup module:

> This module adds the ability for site admins to add "Markup" widgets to the form. These essentially let designers of cck content-types insert additional markup into the node/edit form to display to content-authors. This is the equivalent of adding additional elements to $form of the type '#markup'.

# Answer
> 0 votes
There is in built functionality in Drupal core to do precisely what you are trying to do. Here is how to go about it. Refer the images to follow the steps.

1. Navigate to your Content Type / Node Type and click on 'manage fields'.
2. Click 'Edit' link against each field.
3. In the field edit form that shows up, enter what is called the 'HELP TEXT' and enter instructions for the user that are related to the particular field.
4. You can use reasonable amount of HTML in your instructions.
5. Save your field changes.

Now when you visit the node/add form you would shown the help text alongside your respective fields, as shown below. You can add JS/CSS in your theme to change the display of the help text as desired.

---
Tags: 7, entities
---


# Question
Title: limit validation button on visible state textfield?
Suppose I had a selectbox with 2 options. One option enabling the visible state of one field, while the other disables that state and makes a different text field visible.

If I had a button that has limit\_validation\_errors, how would one go about validating only the field whose state is visible?

Currently my setup looks like the following:

```
$form['unit'] = array(
  '#type' => 'select',
  '#options' => array(
    0 => '€',
    1 => '%',
  ),
  '#default_value' => 0,
);

$form['price-percentage-field'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#description' => t('Set the percentage discount price for this volume set'),
  '#size' => 10,
  '#element_validate' => array('price_percentage_validate'),
  '#states' => array(
    'visible' => array(
      ':input[name="unit"]' => array('value' => 1),
    ),
  ),
);

$form['price-field'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#description' => t('Set the price for this volume set'),
  '#size' => 10,
  '#element_validate' => array('price_validate'),
  '#states' => array(
    'visible' => array(
      ':input[name="unit"]' => array('value' => 0),
    ),
  ),
);

$form['add'] = array(
  '#type' => 'submit',
  '#value' => t('Add'),
  '#name' => 'add_row',
  '#limit_validation_errors' => array(
    array('price-field'),
    array('price-percentage-field'),
  ),
  '#submit' => array('add_volume_standard'),
  '#ajax' => array(
    'callback' => 'add_volume_standard_ajax_callback',
    'wrapper' => 'error-placeholder', //<- this here is for my custom error-placeholder that will contain the form_errors nicely in a div using a few ajax_commands and form_states
    'method' => 'append',
    'effect' => 'fade',
  ),
  '#title' => t('Click this button to add a standard volume price'),
);

```

When using this code, both fields will always be validated. While I want to only validate the visible field. How can I do this?

Also, a validation function is not my preferable approach. I have my reasons.

# Answer
> 0 votes
I would personally prefer a form-validation-function, which seems for me the ideal solution...
But since you're using custom validators, you can check the value of your unit-field in there:

The second argument in your custom element-validation-function is the form\_state-object, with that you have access all form-values. (eg. $form\_state\['values'\]\['unit'\])
Check the value of the unit-field in both validation-functions, depending of it's state do or skip the validation.

Example:

```
   function price_percentage_validate($element, &$form_state, $form) {
        if ($form_state['values']['unit']>0) {
            /* your validation code */
        }
    }
   function price_validate($element, &$form_state, $form) {
        if ($form_state['values']['unit']<1) {
            /* your validation code */
        }
    }

```

---
Tags: forms
---


# Question
Title: Node Gallery not using administration theme for its custom tabs
I'm using a very minimal custom theme for the website, but Bartik for administration.

Node Gallery plugin adds tabs to the Edit Node page (e.g. `node/46/edit`): "Manage Items", "Sort items" and "Upload new items". When I click on them, **the custom theme is used instead of Bartik**. I suspect this is because these pages weren't properly flagged as admin pages, or something like that.

**How can I make Node Gallery use administration theme for its custom tabs?**

# Answer
> 3 votes
Generally, to declare a path as an admin path (and thus one that would open in the overlay/use the admin theme, etc.) you need to declare them using hook\_admin\_paths.

If this is the issue (I don't know Node Gallery, so I can't be more precise) the best would be to implement hook\_admin\_paths in the Node Gallery module and submit the patch on the Node Gallery issue queue.

# Answer
> 0 votes
Do you have Bartik (your admin theme) not being used just for the extra tabs provided by Node Gallery? Or it not being used for the regular node/edit pages either?

If it is the later case and you are on Drupal 7, you can goto `admin/appearance` and at the bottom of the page set your 'administration theme' and check the option to use it during content editing.

---
Tags: theming
---


# Question
Title: How to display one image in multiple sizes across the site?
I would like one image to show in different locations, for example:

* Event in the Calendar (Cropped version of the image)
* Homepage (if promoted to Front Page - as the full size of the image)

Is this possible using Drupal 7?

Thanks! Izumi.

# Answer
Imagecache module has been moved into core for Drupal 7

It's called Image Styles

I haven't used the module, but Image Formatter Link To Image Styles module exposes the Image Style presets in in the imagefield
> 1 votes

# Answer
To speed up page loads (especially if you use Image magic and need many different sizes on images that users will load) I try to create only one image style, whenever I can, of the largest size I will use. Then, when I need the same image in a smaller size I call on this same image style and shrink it either with HTML or CSS (e.g.: height:20px; width: 20px;) Of course, it's better if you keep the image withe same height/width ratio.)

If you can imagine hundreds or thousands of users uploading images that need to be cropped, scaled, etc. that can take some resources on the server. The method above minimizes that. :)
> 0 votes

---
Tags: media
---


# Question
Title: How do I enable and use the password module for Drupal 6?
I've uploaded the module to my site, but it doesn't appear in the list of modules so I can't enable it. Does this module work differently than other modules?

https://drupal.org/project/password

# Answer
> 0 votes
No, this module works as any other module. See my screenshot as I can see it in my module listing -

Are you sure you have it in sites/all/modules/ ? Are the permissions correctly set?

---
Tags: 7
---


# Question
Title: node_delete() does not trigger the "deleting content" Rule?
Due to certain requirements, we are developing a custom module to handle node creation and deletion, using `node_save()` and `node_delete()` respectively. However when we add a Rule with the Rules module to perform certain tasks with the events "After saving new content" and "After deleting content", the event "After saving new content" is triggered with `node_save()` without problem, but the event "After deleting content" is never triggered at all with `node_delete()`. Anyone has any idea what could be going wrong here? Thanks.

# Answer
> 1 votes
Short inspection of rules code showed that it should be triggered after node delete:

```
function rules_entity_delete($entity, $type) {
  switch ($type) {
  ...
    case 'node':
      rules_invoke_event('node_delete--' . $entity->type, $entity);
      rules_invoke_event('node_delete', $entity);
      break;
  ...

```

(from events.inc)

Have you tried turning on rules debug to see what is happening? Go to *admin/config/workflow/rules/settings* and turn on *Show debug information* to *Always*.

Maybe the event *is* being invoked, but some of your condition is incorrect and it appears that nothing is happening.

---
Tags: nodes
---


# Question
Title: How to limit the number of authenticated users logged in simultaneously?
I'm building a project for a client who asked for:

1. Limit the number of authenticated users logged in simultaneously. For example the site won't allow more than 20 users to be logged in at the same time. It would tell the user to try again later.
2. The site would also force the users to log out 30 minutes (for example) after they logged in so others could use the site. For this part, I found the following modules - Automated Logout and Session expire.

Is there a module for the first part? or should I code a new one?

# Answer
Have you tried Session Limit module (https://drupal.org/project/session\_limit)? I do not have first hand experience with it but the module pages says "Configure session limiting exclusions by role" which might be what you want. Alternatively, it also has integration with rules, which also might be useful.
> 0 votes

---
Tags: users, performance
---


title: How do I hide the real filename?

text:
# Question
Title: How do I hide the real filename?
I managed to "hide" files using "private folders". The problem with this is that, when I upload an image called "cat.jpg", it will appear in the file system as "cat.jpg". If I then try to view it, the URL will be something like /system/files/styles/medium/private/cat.jpg?itok=fDHu1Q5k.

Is there a way to obfuscate the name, so that it will instead be something like /system/files/styles/medium/private/2342343534532122.jpg?itok=fDHu1Q5k?

To be clear, I want whoever uploads the file to be able to upload it as "cat.jpg". When it hits the file system, it must still be stored as cat.jpg. Only when it's opened displayed as URL, must the filename be changed. Yes, I know, changing the filename on upload would probably be easier, but there are just too many already uploaded files for me to consider this route, and I still want to be able to browse through the files on the filesystem using the original names.

# Answer
> 1 votes
You can use apache module mod-auth-token (https://code.google.com/p/mod-auth-token/) to generate a one-time url. Please refer to the documentation for more specific instructions (there is both apache configuration and php example how to use it).

---
Tags: media
---


# Question
Title: Trying to write my own Views filter handler
Partially as an exercise, partially as a real need, I'm trying to wrap up a views plugin to provide a filter labeled `Taxonomy Term: Has children terms` \- so to allow terms that do/don't have direct children (depending on the option form setting). So far none of my hits was successful, they all ended up in "Broken handler" messages. Most probably because I declare table relations the wrong way.

Looking at how taxonomy.views.inc does it:

```
$data['taxonomy_term_hierarchy']['parent'] = array(
  // ...
);

```

I tried:

```
function taxfil_views_data() {
  $data = array();
  $data['taxonomy_term_hierarchy']['tid'] = array(
   'title' => t('Has children terms'),
   'help' => t('Check if the term has direct children'),
   'relationship' => array(
      'base' => 'taxonomy_term_data',
      'field' => 'tid',
      'label' => t('Has kids'),
   ),
   'filter' => array(
      'help' => t('My Help'),
      'handler' => 'views_handler_filter_taxfil',
    ),
  );
  return $data
}

```

I am also unsure about the parent class of the filter handler to extend, but at this point I'm close to thinking it does not really matter, as there is bigger problem in front of it.

Usually the example/tutorials base on own tables that a module creates, whereas mine has to re-use the existing.

Could anyone point me to the right direction?

# Answer
> 0 votes
In your specific case, since "taxonomy\_term\_hierarchy" already exists in the views data, you want to implement hook\_views\_data\_alter() instead, making your implementation much simpler (untested):

```
function foo_views_data_alter(&$data) {
  $data['taxonomy_term_hierarchy']['has_children'] = array(
    'title' => t('Has children terms'),
    'help' => t('Check if the term has direct children'),
    'filter' => array(
      'help' => t('My Help'),
      'handler' => 'views_handler_filter_term_children',
    ),
  );
}

```

As far as what filter to extend, a good one might be `views_handler_filter_boolean_operator` but you can just start from `views_handler_filter` too.

---
Tags: views
---


# Question
Title: How can I theme a single value from a multi-value theme?
I'm trying to output a single piece of text from a multi-value text field (unlimited # of values) in my node template and I can't for the life of me figure out how to do it AND apply the THEME to it.

If I just do this:

```
render($content['field_hero_slideshow_header_text'][0])

```

I get the plain old markup for the field. However I want it to be run through the filters and have the theme template applied to it just as if I were rendering the full field with all the values like so:

```
render($content['field_hero_slideshow_header_text'])

```

I've tinkered with passing the #theme values and other vars to the array and using the theme() function also. but I can't quite seem to get it. What am I missing?

# Answer
> 2 votes
It seems like there are properties in $content\['field\_hero\_slideshow\_header\_text'\] which determine how it's themed. Perhaps a '#theme'.

Can you try making a copy of the entire field with just the value you want?

```
$content['field_hero_slideshow_header_text_copy'] = $content['field_hero_slideshow_header_text'];

// Unset all multi values, they have integer keys.
foreach($content['field_hero_slideshow_header_text_copy'] as $k => $v) {
  if (is_int($k)) { unset($content['field_hero_slideshow_header_text_copy'][$k]; }
}

// Add just the one we want back in.
$content['field_hero_slideshow_header_text_copy'][0] = $content['field_hero_slideshow_header_text'][0];

// Output single field.
render($content['field_hero_slideshow_header_text_copy']);

// Do you need to remove the field from the original array?
unset(render($content['field_hero_slideshow_header_text'][0]);

```

Not the nicest way I know. You could try copying properties from the parent to the child and it might output correctly, though I don't think so because the theme function probably expects data in a parent \> child format.

---
Tags: entities, theming
---


# Question
Title: Views contextual filter for taxonomy terms on the currently-viewed taxonomy term
I have two taxonomy term vocabularies:

1. Model
2. Parts

A part is associated with a model via a taxonomy term reference field on the Parts term. The idea is when a user clicks on a model and is viewing the taxonomy term page, they should be able to see all the parts that reference that model.

What I want is something similar to the views contextual filter "Content:NID" and "Content ID from URL".

All of the Views contextual filters and fields appear to be very focused on nodes, so I'm guessing Views just doesn't have this feature yet.

EDIT: Here is the query I want:

```
SELECT entity_id from taxonomy_term_data as tt
JOIN field_data_field_part_model as pm ON tt.tid = pm.field_part_model_tid
WHERE pm.field_part_model_tid = CURRENT_TERM_TID_GOES_HERE

```

EDIT:

Here is the view that I am using. Instead of finding the parts that reference this model, it finds every single part that has anything entered in field\_parts\_model. A part can be compatible with more than one model, and so field\_parts\_model is multiple cardinality, maybe that is messing it up? This doesn't make any sense.

```
$view = new view();
$view->name = 'related_terms';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Related Terms';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'entity';
$handler->display->display_options['row_options']['view_mode'] = 'teaser';
/* Relationship: Taxonomy term: Part Model (field_part_model) */
$handler->display->display_options['relationships']['field_part_model_tid']['id'] = 'field_part_model_tid';
$handler->display->display_options['relationships']['field_part_model_tid']['table'] = 'field_data_field_part_model';
$handler->display->display_options['relationships']['field_part_model_tid']['field'] = 'field_part_model_tid';
$handler->display->display_options['relationships']['field_part_model_tid']['label'] = 'Compatible Models';
$handler->display->display_options['relationships']['field_part_model_tid']['required'] = TRUE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Contextual filter: Taxonomy term: Term ID */
$handler->display->display_options['arguments']['tid']['id'] = 'tid';
$handler->display->display_options['arguments']['tid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['tid']['field'] = 'tid';
$handler->display->display_options['arguments']['tid']['relationship'] = 'field_part_model_tid';
$handler->display->display_options['arguments']['tid']['default_action'] = 'not found';
$handler->display->display_options['arguments']['tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['tid']['summary_options']['items_per_page'] = '25';

/* Display: Related Parts */
$handler = $view->new_display('panel_pane', 'Related Parts', 'panel_pane_2');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Related Parts';
$handler->display->display_options['display_description'] = 'Finds a list of parts that are related to the currently-viewed model.';
$handler->display->display_options['argument_input'] = array(
  'tid' => array(
    'type' => 'context',
    'context' => 'entity:taxonomy_term.tid',
    'context_optional' => 0,
    'panel' => '0',
    'fixed' => '',
    'label' => 'Taxonomy term: Term ID',
  ),
);

```

# Answer
In order to create a view that will display more relevant options to Taxonomy you have to choose taxonomy as your base table.

In drupal 7, when creating a view, select "Taxonomy Terms" under the "Show" drop-down. add your field for the part and then create a relationship to your other taxonomy vocabulary via the taxonomy reference field that you created earlier on.

You can now add the taxonomy term of the other vocabulary when the relationship is matched.

for example:
> 1 votes

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


title: Passing variables in drupal_mail

text:
# Question
Title: Passing variables in drupal_mail
I have a custom module with form and I want to pass the values from form\_state into email. This is my code.

```
//The form page callback
function mymodule_page($form, &$form_state) {
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter name here'),
    );
    $form['surname'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter surname here'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('mymodule_submit'),
    );

    return $form;
}

function mymodule_submit($form, &$form_state) {
    $name = $form_state['values']['name'];
    drupal_mail('mymodule', 'mymodule_mail', 'myemail', language_default(), array($name));
    dpm($form_state);
}

/**
 * Implements hook_mail().
 */
function custom_test_mail($key, &$message, $params) {
    switch($key) {
        case 'mymodule_mail':

        $message['subject'] = t('Hello');
        $message['body'][] = t('This is a body text');

        break;
    }
}

```

I'm receiving the email with the subject and body, but without the value from $form\['name'\].

How can I pass the values from form fields?

# Answer
You're already passing `$name` as a parameter, but you're not actually inserting it into the body so it won't show up in the email.

It's best to use a keyed array so you can easily refer to parameters by name, something like this:

```
$params = array('name' => $name);
drupal_mail('mymodule', 'mymodule_mail', 'myemail', language_default(), $params);

...

$message['body'][] = t('This is a body text');
$message['body'][] = t('Name: @name', array('@name' => $params['name']));

```
> 6 votes

---
Tags: forms, hooks, emails
---


# Question
Title: How to display user picture programmatically in a rule (User Relationships)
Starting from the code in a previous question, I am now trying to post a user picture in a rule that displays a relationship between two users (User Relationships module.)

It is the requestees's picture I am trying to display (the $requestee variable is allowed)

Here is the code I have so far:

```
$imgpath = file_load(($requestee->picture[und][0]['uid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail', 'attributes' => array('class' => array('RequesteesPicture'))));
$link = l($image, "user/$requestee->uid", array('html' => TRUE));
print $link;

```

I see the placeholder for the pic. The link to the requestee's picture is correct and the image style is also correct. But the pic does not show.

What do I need to do to make the pic show up?

Thanks. :)

# Answer
> 0 votes
Try something like this, just for grins. Make sure you're actually returning the URI, and maybe provide an alternative image if they don't have one for themselves. Also, your link might be messed up.

I'm not entirely sure how you're getting that URI for the profile image.

```
$imgpath = $requestee->picture[und][0]['uid']->uri; // Maybe? I would think the URI is in the picture array.
$vars = array(
  'style_name' => 'thumbnail',
  'path' => $imgpath,
  'attributes' => array(
    'class' => array('RequesteesPicture'),
  ),
);
$image = theme_image_style($vars);
$link = l($image, "user/" . $requestee->uid, array('html' => TRUE));
print $link;

```

---
Tags: users
---


# Question
Title: How to add 'Welcome {username}' in blocks with Drupal 7
I am replacing a drupal 6 website by a drupal 7 one with the same content. On that Drupal 6 website there is a block that comes visible when you're logged in. As heading it shows the message 'Welcome {username}' in that block.

I'm looking for a way to do that in Drupal 7, i tried to do this with the module 'Token' but i doesn't work. What's the best way to do this?

# Answer
> 11 votes
Either in a block or in a custom module that adds a block, add the following code:

```
if (user_is_logged_in() == TRUE) {
    global $user;

    print "Welcome " . $user->name;
}
else {
    print "Please log in.";
}

```

This is more useful if you want CURRENT user information. Possibly this as well for the `user_is_logged_in` function.

# Answer
> 5 votes
If you want to do this in a module (recommended as opposed to adding php code to a block, which would then not be in version control), then you can do this:

(in this case, all this code would go in a custom module named userwelcome.)

```
/**
 * @file
 * Adds a block that welcomes users when they log in.
 */

/**
 * Implements hook_theme().
 */
function userwelcome_theme($existing, $type, $theme, $path) {
  return array(
    'userwelcome_welcome_block' => array(
      'variables' => array('user' => NULL),
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function userwelcome_block_info() {
  // This example comes from node.module.
  $blocks['welcome'] = array(
    'info' => t('User welcome'),
    'cache' => DRUPAL_CACHE_PER_USER,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function userwelcome_block_view($delta = '') {
  global $user;
  $block = array();

  switch ($delta) {
    case 'welcome':
      // Don't show for anonymous users.
      if ($user->uid) {
        $block['subject'] = '';
        $block['content'] = array(
          '#theme' => 'userwelcome_welcome_block',
          '#user' => $user,
        );
      }
      break;
  }
  return $block;
}

/**
 * Theme the user welcome block for a given user.
 */
function theme_userwelcome_welcome_block($variables) {
  $user = $variables['user'];
  $output = t('Welcome !username', array('!username' => theme('username', array('account' => $user))));
  return $output;
}

```

If you then wanted to override the themeing of this block in a theme you would do this (in your template.php file of your theme):

```
/**
 * Theme the userwelcome block.
 */
function THEMENAME_userwelcome_welcome_block(&$variables) {
  // Return the output of the block here.
}

```

Note that because this is a custom module you could also just update the theme funciton in the module directly.

If you don't want to use a custom module you can create a custom block with php code and add this:

```
global $user;
// Only for logged in users.
if ($user->uid) {
  print 'Welcome ' . theme('username', array('account' => $user));
}

```

# Answer
> 5 votes
Use views module. Create new view \> show users \> block display. Add contextual filter \> provide default argument \> user ID from logged in user. Configure fields (you can rewrite results) to include whatever text/tokens or user profile fields you wish. Save and add block to region.

Done with one module and no code.

-lunk\_rat

---
Tags: blocks
---


title: Benefits of using a base theme?

text:
# Question
Title: Benefits of using a base theme?
In building a new theme (for a bespoke build, rather than distribution) is it essential to start with a base theme? If I look at the Zen theme, for example, I would scrap most of the HTML and CSS in order to start with a blank-er canvass than that theme provides. Are there still many benefits to using a theme like Zen in that case?

**Update** In an attempt to clarify, this is for a professional project, and in terms of HTML/CSS we'd usually start from as little as possible; normalize.css, modernizr and not much more. Most themes seem too 'opinionated', there's too much we'd have to re-style or remove to the point where it would slow development down.

# Answer
If you're not doing a traditional 3 column with header and footer site layout, then no - you probably won't get much out of something like Zen.

That said, you can still leverage the awesome Zen Grids gem with SASS and get the benefits Zen's grid system without any of the cruft from the base theme.

Anyone who has themed enough Drupal sites understands that you're going to be dealing with machine-generated HTML at some point (either from Views, or some other contrib module). You could spend a ton of time overriding all the theme functions to get the exact HTML you need so you can apply the col-xx classes your grid system of choice needs, or you can use the classes that already exist on the pre-existing markup and make them compatible with your grid with Zen Grid's mixins.

I like to say that Zen Grids acknowledges the reality of Drupal theming and comes up with a system that works with Drupal as opposed to against it.
> 1 votes

# Answer
The major benefit of using a base theme is that things like jquery and responsive style sheets are included, i.e. you don't have to reinvent the wheel. It is far easier to override and or change the base theme than to create everything from scratch, which depending on your knowledge of Drupal might mean that if you miss something, the base theme stylesheets will have you covered. All of this means faster shipping.
> 0 votes

---
Tags: theming
---


title: Using views to create comic reader

text:
# Question
Title: Using views to create comic reader
I'm trying to create a comic reader like a flip book. I think the views module can do this but I don't know how to do it. I plan to structure like this:

```
Terms (Series)
     - Sub Term (Chapters)
           - Nodes using image field (Pictures)

```

What I want to do is I want make a views in the subterms to show only one node at a time but the node contains the image that is linked to the next node in sequence order. So how can I do this? I only want the nodes from the subterm to show up

# Answer
There's a lot of moving parts here. I'm going to make some assumptions. First, you have nodes. Each node has 1 image on it (through a file / image field).

You then want to display the nodes in some sequence order (maybe through a slideshow or something).

Each time you look at the view, you should only look at one "flip book" at a time.

For this you need to use a Views "Contextual Filter" (or "argument" in the older language). You would build your page view to pull in all the images of all the nodes. You would probably set your views to display as a views\_slideshow or something.

The first "contextual filter" your view will have is the term (I'm assuming from taxonomy) that you want to build the flip book from. So, you might go and view yoursite.com/flipbook/37 (where 37 is the term id that all the image nodes are tagged with for this book).
> 1 votes

---
Tags: views, paging, navigation
---


# Question
Title: change comment form container to textarea
How to remove the red section in next image (comment form)?

I have try change the type to textarea, but on submit the form a blank page appears.

```
function THEME_form_comment_form_alter(&$form, &$form_state) {
    $form['comment_body']['#type'] = 'textarea';
}

```

# Answer
You can make the field plain text in the comment body field settings.

e.g:

http://example.com/admin/structure/types/manage/article/comment/fields/comment\_body

> "Text processing" \> "Plain text"
> 1 votes

# Answer
You can hide all that text entirely by using the "better formats" module. https://drupal.org/project/better\_formats I think that is what you're after, here. But you'll also just want to be cautious that you're setting a proper input format for people here for what they're doing. For comments, you'll likely want it to be a very limited HTML format, or a Plain Text format.
> 0 votes

---
Tags: 7, forms, comments
---


# Question
Title: Show create content menu item to ananymous users but call URL for login/register popup on click
I thought it would be simple to do, but after lots of searching I couldn't find exact solution for it.

So the issue is, I have 2-3 main menu items which I have to show to anonymous users but have to call a URL(for login/register popup) & prompt for login or register if they click on them.

Best solution I found for create content link **"node/add/node-type"** was something like --

```
function THEME_preprocess_page(&$vars, $hook) {
    global $user;
    # if url starts with "add" and current user is anonymous
    if (arg(1) === 'add' && $user->uid === 0) {
          # redirect to login page
          drupal_goto('user/login');
          exit;
    }
}

```

It didn't work & it says - "$base\_path has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer."

This is a very important functionality thing & I don't know how people resolve it. Can I get any suggestion for it ?

# Answer
> 0 votes
You can use hook\_node\_access for that.

Of course it's not a turn-key solution, but I'm sure this example will help anyone who will face this kind of issues.

Example:

```
/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access($node, $op, $account) {

  // define restricted node id's
  $restricted_nids = array(7,27);

  // If $node is a string, the node has not yet been created. We don't care
  // about that case.
  // Check permissions only for restricted nids.
  if (!is_string($node) && in_array($node->nid, $restricted_nids) && $op == 'view') {

    global $user;

    // OPTION #1
    // Give an access if they have ANY of these roles.

    //$has_permission = array_intersect(array('testrole', 'testrole2'), array_values($user->roles));
    //return $has_permission ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;

    // OPTION #2
    // Give an access if they have ALL of required roles.

    $required_roles = array('testrole', 'testrole2');
    $has_permission = (count(array_intersect($user->roles, $required_roles)) == count($required_roles)) ? TRUE : FALSE;
    if ($has_permission) {
      return NODE_ACCESS_ALLOW;
    }
    else {
      if ($user->uid) {
        drupal_set_message("You don't have appropriate permission to view this content");
      }
      else {
        drupal_set_message('You have to login to see this content');
        drupal_goto('user/login');
      }
      return NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}

```

# Answer
> 1 votes
I had the same problem, and solved it without coding.

1. Manually set the menu path with absolute URL, ie. http://yourdomain.com/node/add/node-type
2. Install and enable the module r4032login
3. Done!

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


# Question
Title: How to hook bundle create/read/update/delete events?
There's an ongoing discussion about how there should be CRUD hooks on bundle events, `hook_entity_bundle_[create/load/update/delete/etc]` (currently in the context of Drupal 8).

In the mean time, in Drupal 7, what's the closest thing we have to a `hook_entity_bundle_create`? To put it another way, how best to define a function that will be called every time an entity bundle is created, where the function can access data about that bundle?

The above link mentions the `hook_field_attach` hooks (the Field Attach API), but it's not clear which if any of these hooks will be called reliably on bundle editting.

It's be great to clearly get down what the current equivalent of bundle CRUD hooks are.

# Answer
> 0 votes
So here's the best I can find so far. It's not great.

* **Create**: There's `hook_field_attach_create_bundle`, but it doesn't automatically get called any time a bundle is created. Seems that every module for every entity with bundles has to call `field_attach_create_bundle($entity_type_name, $bundle_type_name);` every time a bundle is going to be created/saved, else the hook doesn't know about it. It seems not to do anything except call the hooks - I've seen modules that forget to add this line.
* **Read**: I can't find an equivalent here (no big deal I guess as it's not clear what 'reading' a bundle would mean - accessing info on it?)
* **Update**: The closest I can find is `hook_field_attach_rename_bundle`. Not great.
* **Delete**: There's `hook_field_attach_delete_bundle`. Like `..._create`, it needs to be called in the code, so some modules' entities might not call it. But it appears that `field_attach_delete_bundle()` actually handles the deletion of field data, so it's less likely to be forgotten or overlooked.

# Answer
> 0 votes
The Drupal 8 change notice covers these points nicely.

https://drupal.org/node/1964766

---
Tags: 7, hooks, entities
---


# Question
Title: Efficient way to keep Drupal 7 session alive from another web app?
Is there a simple PHP file I could create which, when called by an authenticated user, will keep their Drupal session alive?

I don't want to do an AJAX call to /index.php as this will cause unnecessary overhead. I just need a way to keep the session alive from another app.

Could I use the bootstrap method below, rather than instantiating the whole stack?

```
<?php
    define('DRUPAL_ROOT', '/my/local/root');
    include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
?>

```

# Answer
> 1 votes
If you're worried about unnecessary overhead, why not check out the High-performance JavaScript callback handler module.

It allows you to control what exactly gets loaded during the Drupal bootstrapping process, so that you would only spin up the bare essentials to keep your session alive from another app.

Check out this blog post for a good breakdown of how you implement this module:

High performance AJAX callbacks with Drupal 7 and the JS module

---
Tags: 7, sessions, bootstrapping
---


# Question
Title: Weird activites in my site. Is my site hacked?
Since long time I have been noticing some weird activity going on on my website.

For example:

* The `includes` folder was deleted
* CSS files were modified
* Node edit access was given to anonymous users

I was thinking it could be human error by my team, but I can confirm they are not doing anything as such because they are just updating the content without touching the site configuration.

I see these users which we never created:

* martinm14vxbyycdniot/fallsatj@hotmail.com
* qhzcedrichjergsj/obscenehail72mbb@seznam.cz

They show as blocked users and I don't see any content created by them. I searched for the email ids and found they are marked as spammers but dont know what it is. These things are really worrying me. Does anyone know what might be going on?

Is my website hacked?

**Update:**

few minutes after posting this (and after deleting above users) this user is crated

* qhzcedrichjergsj/obscenehail72mbb@seznam.cz

# Answer
> 4 votes
If your site is set up to allow people to register for the site, but requires administrator approval before they're activated (pretty common set up for Drupal), then spammers will manage to *register* accounts, but the accounts created like that will show as blocked users until they're approved. That may explain why these blocked accounts exist. If this is the case, then this is normal, and no grounds for concern.

To make sure only admins can create accounts, navigate to *Home » Administration » Configuration » People » Account Settings* and tick the radio button "Administrators only" for "Who can register accounts?".

As for the other "weird" stuff you've noticed (`includes` folder deleted, CSS files modified, node edit access given to anonymous users): It gives grounds for concern, but it is impossible to tell whether it is caused by malicious actions from outsiders, or human error by some careless admin.

If node edit access were given to anonymous users, but no node was ever defaced or otherwise maliciously altered because of this, I would lean in the direction of human error.

---
Tags: users, security, advertising
---


title: Form type select with multiple values

text:
# Question
Title: Form type select with multiple values
I have a form field with type select. The results values are taken from the database. If the select list is with single value I'm displaying the value title on the submit like this:

```
   $selected_index = $form_state['values']['select_list']; //the field is select_list
   $display_value = form['select_list']['#options'][$selected_index];
   dpm($display_value); //it's showing the selected option value title.

```

When I'm using `'#multiple' => TRUE`; into the form field, It's showing error: Warning: Illegal offset type in...

How can I display the titles of the multiple values?

EDIT:

This is my code:

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

global $user;

$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid and type = :type', array(':uid' => $user->uid, ':type' => 'outlets'));

$droplist = array();
foreach($result as $record) {
    $title = $record->title;
    array_push($droplist, $title);

    $form['select_list'] = array(
       '#type' => 'select',
       '#title' => 'Select list',
       '#options' => $droplist, //I'm getting this list from my database
       '#multiple' => TRUE,
   );
}

function mymodule_submit($form, &$form_state) {
   $selected_index = $form_state['values']['select_list'];

   foreach($selected_index as $key => $sindex)
   dpm($sindex);
}

```

# Answer
> 2 votes
In case of multiple values, the return value is an array of all selected values. Therefore, `$selected_index` is now an array and not a string.

# Answer
> -1 votes
When you use `multiple` the value of field is array instead of only one value you can get them :

```
  $selected_index = $form_state['values']['select_list']['und']; //the field is select_list
  $values=array();
  foreach(  $selected_index as $sindex){
   $values=$sindex['value'];
   //dsm($sindex['value']);
}

```

---
Tags: forms
---


# Question
Title: Using form_set_error in the submit handler
I have a multistep form and on each submit I send completed fields off to an external API which returns data about the next step of the form.

The problem is, if I use form\_set\_error in the submit handler, the form\_storage is cleared and so the form resets to the first page.

Here's a arbitrary example;

```
function example_form($form, &$form_state) {
  if(!isset($form_state['step'])){
    $form_state['step'] = 1;
  }
  $form['test'] = array('#markup' => '<p>Step: ' . $form_state['step'] . '</p>');

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'go'
  );
  return $form;
}

function example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  if($form_state['step'] > 5){
    form_set_error('test', 'error');
    return;
  }
  $form_state['step']++;
}

```

So this create a form with just a text block displaying the step number and a submit button that takes you to the next step. Until you go past the 5th step at which point it should start to error.

For some reason in my testing this breaks the step count, and on error takes you back to step 2.

moving the form\_set\_error into the form callback, or into a validate callback fixes the issue, but it would be cleaner if I could call it in the submit handler.

# Answer
In case it's useful to anyone else, I have a unsatisfactory work around;

Store the error in form\_state, and look for them in the form callback.

```
function example_form($form, &$form_state) {
  // if we had an error in the submit handler, trigger it now
  if(isset($form_state['error']) && $form_state['error']){
    form_set_error('test', 'test');
  }
  if(!isset($form_state['step'])){
    $form_state['step'] = 1;
  }
  $form['test'] = array('#markup' => '<p>Step: ' . $form_state['step'] . '</p>');

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'go'
  );
  return $form;
}

function example_submit($form, &$form_state) {

  $form_state['rebuild'] = TRUE;
  if($form_state['step'] > 5){
    //store error and return before the step is increased
    $form_state['error'] = true;
    return;
  }

  $form_state['step']++;
}

```
> 5 votes

# Answer
`form_set_error()` isn't supposed to be used in a submit handler; it's part of the validation workflow. From the docs:

> When a validation error is detected, the validator calls form\_set\_error() to indicate which element needs to be changed and provide an error message. **This causes the Form API to not execute the form submit handlers**, and instead to re-display the form to the user with the corresponding elements rendered with an 'error' CSS class (shown as red by default).

Emphasis mine.

The point is to use `form_set_error()` to stop the process from ever reaching the submit handler.

Don't forget, you're *validating* whether or not the current step is greater than 5. That logic needs to happen in a validation handler. :)
> 3 votes

# Answer
```
function example_form_validate($form, &$form_state) {
}

```

Use this function to validate your data when submitting a form
> 0 votes

# Answer
form set error will clear your input, so do not use that function here. Instead, use the drupal\_set\_message. It is not perfect, but it will work.
> 0 votes

---
Tags: forms
---


title: Textfield value not saving to database

text:
# Question
Title: Textfield value not saving to database
I am having a problem with saving values of a textfield in the database.

Usecase: Users with a certain role should add two things on their accountpage the first time they login. 1.change their password 2.agree with terms.

Point 2 is the trouble part. I have a text field with two values: 'Agree' and 'Not agree' Now i like to hide the second option but with my current code the value of the agree option is not getting saved to the database.

Help appreciated Thanks

Used code

```
<?php
function regform_form_user_profile_form_alter(&$form, $form_state,  $form_id) {
  global $user;
 // Making password required when role=In between role.
if( ($form_id == 'user_profile_form') and (isset($form['account']['pass'])) and (in_array('In between role', array_values($user->roles))) ){
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#required'] = TRUE;
    $form['account']['pass']['#type'] = 'password_confirm';
    $form['account']['pass']['#required'] = TRUE;

   // Disabling and hiding 'Dont agree field' field

  $form['field_agree'] = array(
  '#type' => 'checkboxes',
  '#options' => array(
   'Agree' => t('Agree'),
   'Do not agree' => t('Do not agree'),

 ),
);
hide($form['field_agree']['Do not agree']);
 }
}
?>

```

# Answer
It is not necessary to hide the 'no' option from checkbox - just go the the field settings and make it a single on/off checkbox, that way you will not have to deal with this at all.

Then, go to the field settings and set the Default value to off (see screenshot).
> 0 votes

---
Tags: forms
---


# Question
Title: How to switch logo and menu links based on subdomain?
my D7 site will be accessible from 4 different subdomains: \- a.site.com \- b.site.com \- c.site.com \- www.site.com (or just site.com)

I already enabled a domain cookie for .site.com and the login works across all subdomains.

Now I want to be able to show a different logo logo based on the subdomain and I also want to be able to switch the main menu links.

I tried the context module but didn't find a way to detect the subdomain.

I don't want to use the domain access module. I was thinking about modifying the theme to switch the logos. Can I do the same for the menu links?

Does anyone have a better idea?

# Answer
> 3 votes
I am unaware of any contrib modules that do this (well, other than Domain Access), but it would be pretty trivial to write a little custom code to accomplish it.

Essentially, you would add something to your theme preprocess to detect the domain and tack on body classes. How to do this depends on whether you are using Drupal 6 or Drupal 7. Either method, though, would use `$_SERVER["HTTP_HOST"]` to detect the theme.

Then, in your CSS you would preface your logo rules with `body.whatever` to choose the correct one.

The menu thing is a little trickier. You would use essentially the same logic, but set a variable containing the proper menu and print this out in your theme. To be honest, though, I really would use Domain Access for this if you are using Panels. The domain shows up as a panel selection rule, so you can do all of this from the UI.

# Answer
> 0 votes
> I tried the context module but didn't find a way to detect the subdomain.

You need to use the Context Domain module. I'm not sure about the logos, but maybe you can use Context Reaction Menus for handling the main menu.

# Answer
> 0 votes
You need this: https://drupal.org/project/domain

& https://drupal.org/project/domain\_menu\_access

Using domain module you can manage various settings like theme, block for specific domain.

Using domain menu access you can restrict specific menu link to appear in specific domain under menu configuration settings.

---
Tags: theming, 7
---


# Question
Title: Unable to add custom validation rules using client side validation module in Drupal 7
First I want to clarify that I am new to Drupal. So please excuse me If my question is naive.

I have installed the `Client Side module` in Drupal and it is working fine for all the required fields. I have built a custom form using Drupal form API. Now I want to add some custom rules to some of the fields on the from. I have searched on the internet and found this https://drupal.org/project/fapi\_validation and below is the code that I have implemented but this is not working. I think there is some thing that I am missing here. The module name is **instructor\_registration** and I have written this code in instructor\_registration.module file.

```
function instructor_registration_fapi_validation_rules() {

return array(
    'select_required' => array(
        'callback' => 'validation_rule_select_required',
        'error_msg' => 'Please select %field',
    ),
);
}

function validation_rule_select_required($value) {
if ($value == '0') {
    return FALSE;
}
else {
    return TRUE;
}
}

```

In the form element I am calling this as :

```
'#rules' => array('select_required'),

```

If there is any other information required from my side then please let me know.

# Answer
Finally found the solution. Actually the code that I was writing was not complete. The examples for adding custom rules in client side validation can found at https://drupal.org/node/1324772 . Hope this helps some one.

Cheers!!!
> 0 votes

---
Tags: forms
---


title: Generating node title from node fields

text:
# Question
Title: Generating node title from node fields
So, this is a newbie question. I'm using Automatic Nodetitles with a custom content type. I'd like the node's title to be equivalent to one of my fields. After some snooping around I came up with this:

```
<?php return $node->field_my_field ?>

```

I put this in the "Pattern for the title" field, but this just returns 'Array'. So, it must be an array. However, I'm not having any luck figuring out how to index it to get the value I'm looking for. Everything I tried just gives me 'Undefined offset' errors.

This can't be too hard.... Thanks!

# Answer
```
<?php return $node->field_my_field['und'][0]['value']; ?>

```
> 3 votes

# Answer
I think it's better idea to use token instead of php code for this simple replacement.

When you have the token module installed you'll have a list with available tokens under the **Pattern for the title:** input box. And if your field is named \*field\_my\_field\* then you'll have the tokens

```
[field_my_field-formatted]
[field_my_field-raw]

```

or something like that to choose from.
> 4 votes

# Answer
For tokens what finally worked for me was

> \[node:field\_my\_field\]

That being said I am using Automatic Entity Labels so it may not.
> 1 votes

# Answer
I agree that it may be better to use tokens. To add to martin's post, and in response to the issue that DilbertDave raises, I believe that though most of the Token API has been added into Drupal7, certain aspects of the original token plugin still haven't, including, field support. So to that end, you may find it helpful to install the Token module which will then enable you to use field-based tokens such as others here have suggested:

```
[field_my_field-formatted]
[field_my_field-raw]

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Why is my content showing up below other blocks?
I did some work on my site and now i realize that even though my main page content block is weighted to be at the top, it shows below everything else within that area.

Is there any way someone can take a look and help me figure out why this is happening?

Using \- drupal 7 \- omega3 main theme with a custom subtheme

example of my issue: http://www.destinationsound.net/contact

The two blocks "Buy Beats Front Page" and "Banner Ad Top" blocks are the two located above the contact form on the contact page (and other pages)

# Answer
Try hiding the row weights and dragging the items around. Change them any way you want - then save configuration then go back in and change them to the way you want them to be and save again. Dont forget to clear your caches.
> 0 votes

---
Tags: theming
---


# Question
Title: How can I avoid that users vote for their own posts?
I want to avoid that users can vote for their own posts, as it happens on Stack Exchange sites. For this, I created the following rule:

* ON event "User votes on a node", the condition is "execute PHP code" and the code is the following one:

```
global $user;
return $node->uid != $user->uid;

```

Still, users can vote on their own posts. What should I do?

Using the following code, I get an error message given below.

```
global $user;

dpr($user);
dpr($node);

return $node->uid != $user->uid;

```

# Answer
The rate module allows you to do this in its settings. You have to create a widget for this : admin/structure/rate (just add a new one and then you'll see the option). You will be asked to choose the content type and the position of the widget in the page that you need to define to see the vote system. I didn't try nor with views integration, neither with Drupal 6.
> 0 votes

---
Tags: rules, rating
---


# Question
Title: How do I get third party jQuery plugins to work with Drupal?
I am trying to use the Slider Revolution jQuery plugin (from ThemePunch) on my Drupal site to create a slider on the front page.

I cannot for the life of me figure how to get this working. I have manually built a simple HTML page (outside of Drupal) to check the plugin and it works flawlessly, I just cannot seem to get it working in Drupal.

*Drupal version: 7*

*Slider Revolution version: 4.1.2*

Instructions for Slider Revolution: http://pastebin.com/gxNSV4hh

My theme is using *jQuery 1.9.0*

I have added into ***mytheme*.info**:

```
scripts[] = js/rs-plugin/js/jquery.themepunch.revolution.js
scripts[] = js/rs-plugin/js/jquery.themepunch.plugins.min.js

```

I have added to my front page:

```
<div class="tp-banner-container">
<div class="tp-banner" >
    <ul>
        <!-- SLIDE  -->
        <li data-transition="fade" data-slotamount="7" data-masterspeed="1500" >
            <!-- MAIN IMAGE -->
            <img src="/sites/all/themes/sure2sell/js/rs-plugin/images/slidebg1.jpg"  alt="slidebg1"  data-bgfit="cover" data-bgposition="left top" data-bgrepeat="no-repeat">
            <!-- LAYERS -->
            <!-- LAYER NR. 1 -->
            <div class="tp-caption lightgrey_divider skewfromrightshort fadeout"
                data-x="85"
                data-y="224"
                data-speed="500"
                data-start="1200"
                data-easing="Power4.easeOut">My Caption
            </div>
            ...

        </li>
        <!-- SLIDE  -->
        <li data-transition="zoomout" data-slotamount="7" data-masterspeed="1000" >
            <!-- MAIN IMAGE -->
            <img src="/sites/all/themes/sure2sell/js/rs-plugin/images/darkblurbg.jpg"  alt="darkblurbg"  data-bgfit="cover" data-bgposition="left top" data-bgrepeat="no-repeat">
            <!-- LAYERS -->
            <!-- LAYER NR. 1 -->
            <div class="tp-caption lightgrey_divider skewfromrightshort fadeout"
                data-x="85"
                data-y="224"
                data-speed="500"
                data-start="1200"
                data-easing="Power4.easeOut">My Caption
            </div>
            ...
        </li>
        ....
    </ul>
</div>

```

Using **Tracking Code module** I have added (before ***/body***) :

```
<script type="text/javascript">
  jQuery(document).ready(function() {
   jQuery('.tp-banner').revolution(
    {
      delay:9000,
      startwidth:1170,
      startheight:500,
      hideThumbs:10
    });
  });
</script>

```

Slider Revolution file ***jquery.themepunch.revolution.js*** is structured like:

```
(function(jQuery,undefined){

    ////////////////////////////////////////
    // THE REVOLUTION PLUGIN STARTS HERE //
    ///////////////////////////////////////

    jQuery.fn.extend({

    // OUR PLUGIN HERE :)
    revolution: function(options) {
    ...........
    ...........
    }})

})(jQuery);

```

Slider Revolution file ***jquery.themepunch.plugins.min.js*** is structured like:

```
(function(t){"use strict";var e=t.GreenSockGlobals||t;if(!e.TweenLite){
    ..........
    ..........
);

(function(e,t){
    ..........
    ..........
})(jQuery)

```

How do I go about implementing this in Drupal? I believe Drupal expects jQuery/Javascript to be in a specific format (https://drupal.org/update/modules/6/7#javascript\_compatibility) but I really don't know where to start with this. JS/jQuery really isn't my thing so I'm unsure what needs changed/added to make this compatible with Drupal.

**Update:** it works flawlessly, even with jQuery 1.7 : http://build.kaipee.co.uk/drupaltest/

Looks like it's an issue with my site/theme :(

# Answer
Read Managing Javascript in Drupal 7 for the full details, but basically you're looking for something like this:

```
(function($, Drupal) {
  Drupal.behaviors.sliderRevolution = {
    attach: function(context, settings) {
      $('.tp-banner', context).once('sliderRevolution', function() {
        $(this).revolution({
          delay:9000,
          startwidth:1170,
          startheight:500,
          hideThumbs:10
        });
      });
    }
  }
})(jQuery, Drupal);

```
> 3 votes

---
Tags: javascript
---


title: How to display facets in tabs

text:
# Question
Title: How to display facets in tabs
i am using Search API and Facets API to display facets based results .

i wonder how to display the facets in tabs. Is there a module for it.

BBCGoodFood is doing that already . (done with Drupal)

http://www.bbcgoodfood.com/search/recipes?query=asian

Any clue? thanks

# Answer
> 1 votes
Use the aptly named Facet API Tabs module.

> This module adds the option of displaying search facets as tabs. It's heavily based on the "links" widget that comes with FacetAPI, and has just altered the rendering rules of the links, as well as added the "All" tab.

---
Tags: views, search
---


title: Exposed Filters in more better way

text:
# Question
Title: Exposed Filters in more better way
i have a view with lot of exposed fields for searching ... (50 +)

i am looking for some thing like this.

with "add more " button you can add only the fields you want to search in .. possible ?

thanks

# Answer
> 0 votes
With jQuery , make a `<select id='hider_s'>` list in the views TPL , and print all the fields names in it and `<option value="$theFieldID">`. Hide all the exposed fields with css , and add below jQuery to select list . `jQuery('#hider_s').on('change', function() { $selectedval=this.value; jQuery("#"+$selectedval).css("display","inline"); });`

# Answer
> 0 votes
May be this can help - Views Dependent Filter.

> Allows the presence of exposed filters on a view to be controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.

# Answer
> 0 votes
While it doesn't really solve your problem, Better Exposed Filters has a "Secondary exposed form" option. That allows you to select some number of filters and put them into a collapsible fieldset. So, you could have your primary filter options shown with (eg: English search options) with the Arabic options held in the fieldset.

Like I said, not exactly what you were asking for, but to do what you've shown would take custom coding -- probably easiest to do in the theme layer, or you could write a custom exposed form plugin.

---
Tags: search, views
---


title: Manage main menu in module

text:
# Question
Title: Manage main menu in module
I have a series of sites that use the same theme. What I'm looking to achieve is to manage the main menu (or a standard menu) via a module instead.

Reasoning: Most of these sites will have the menu the exact same. If I need to change something, I would do it in the module. I could put it in the theme, but I'd rather the site admins not have control over appearance or to change the theme, have the ability to add to the menu if that have a small item that needs to be placed there, or the ability to simply not show the entire menu and manage their own.

I've tried the following, but every time the cache is cleared, a new item is added. If I change something, it just adds a new item and leaves the old one.

```
function something_mainmenu_menu() {

    $items['external'] = array(
        'title' => 'External Item',
        'link_path' => 'http://www.whatever.com',
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu'
    );
}

```

Is this possible in Drupal as a module, or should I just put it in the theme and do a case based on the URL?

# Answer
> 0 votes
You can stop roles from editing menus via the permissions page. That should lock that down.

Then to manage the menus on all your sites you could use Menu Export/Import module (https://drupal.org/project/menu\_import), which plays nicely with Drush to allow you to export/import entire menus. You could maintain your "master" menu in a text file in json format and then periodically push it out to all sites at once using Drush aliases or a simple shell script. Because Drush uses uid 1 I think you should be able to do whatever you need regardless of how you set your roles' permissions via the UI.

---
Tags: routes, hooks
---


# Question
Title: Panels template files: Inheriting a tpl file in a sub theme
In my Drupal custom parent theme, I have included a file called `panels-pane.tpl.php`. This is the main panel pane template. By including this tpl file in my theme, I can override the one in the Panels module folder, which allows me to control its mark-up.

It all works fine. However, when I enable a sub theme that is based on the parent theme, this particular file is ignored. All the other files are inherited.

How can I get this file to be inherited as well?

Would it be possible to force this to be always loaded regardless of the theme?

Please note: I am talking about overriding the `panels-pane.tpl.php` that comes from the original Panels module. I am *not* talking about creating a custom Panels layout.

Steps I have tried:

1. Copying the `panels-pane.tpl.php` into the sub themes template directory.
2. Clearing the caches
3. Uninstalling and then re-enable the parent and sub themes

**UPDATED** Panels has a file called `panels.module`. In it has a function called `panels_theme()`, which contains the following:

```
  $theme['panels_pane'] = array(
    'variables' => array('output' => array(), 'pane' => array(), 'display' => array()),
    'path' => drupal_get_path('module', 'panels') . '/templates',
    'template' => 'panels-pane',
  );

```

Can I use this to control `panels-pane.tpl.php` from inside a module by using theme\_registry\_alter?

I have tried the following code, but it doesn't work:

```
function legendary_theme_registry_alter(&$theme_registry) {
 $theme['panels_pane'] = array(
    'variables' => array('output' => array(), 'pane' => array(), 'display' => array()),
    'path' => drupal_get_path('theme', 'legendary') . '/templates',
    'template' => 'panels-pane',
  );
}

```

# Answer
> 2 votes
Here's the weird news, just having a `panels-pane.tpl.php` in a parent theme should work. It's working for me in a highly used parent theme. So I'm guessing any theme suggestions or other steps aren't going to cut it...

I would check for typos, in this case I would look at the file name (sounds like that's fine), then I would check the sub-theme info file to make sure that's set correctly (although it sounds like that may also be right)

```
base theme = base_theme_name

```

Then I would check file permissions on tpl/theme folder. 664 tends to work for me, and apache needs access to it and the folder it's in.

If that seems fine my two steps before I panic with drupal are:

```
drush rr

```

restart apache

Hope that helps.

---
Tags: theming, panels
---