# Question
Title: Path Breadcrumbs adds unwanted space in link path, why and how can I avoid it?
I added in the link path field for a breadcrumb the following:

```
%site:url%node:tax-title-for-url-construction

```

"%node:tax-title-for-url-construction" is a custom token which returns a taxonomy title like "Xbox 360" in a cleaner way "xbox-360".

So the links should look like http://domain.com/xbox-360 but it return the following http://domain.com/ xbox-360 Note the space between site url and tax title, but there is no space in the link path field within the breadcrumbs configuration. So where does this space come from?

Here is the code from my custom token:

```
<?php
$node = node_load(arg(1));
$rtaxidarray = field_get_items('node', $node, 'field_plattform');
$rtaxid = $rtaxidarray[0]["tid"];    // taxid sauber
$term = taxonomy_term_load($rtaxid);
$name = $term->name;
$small = strtolower($name);
$clean = str_replace(" ", "-", $small);
return $clean;
?>

```

# Answer
> 0 votes
HM There was a space before the opening php tag in the custom token value field, I really hate spaces. I think spaces should be exchanged with a X ;)

---
Tags: taxonomy-terms, nodes, breadcrumbs, tokens
---


# Question
Title: Migrating database content to a new server
I am moving a Drupal site onto a new server. I am using putty to scp the database onto this new server; I have not done this before, so there are things I am not sure.

There is a database called 'website' in the mysql on the server already, while my original database name is actually 'mydrupalsite'. If I just import the file mydrupalsite.sql into database 'website', and change the database name in setting.php, will that be ok?

# Answer
> 2 votes
It will be sufficient most of the time, but it is a good idea to open mydrupalsite.sql in text editor and scan it for old configurations. Especially if domain name also changes. Even if not, some modules needs may save things like local network addresses to data import sources et cetera.

And of course don't forget to truncate all cache tables and session table before data export. Best would be to disable cache and css/js aggregation on site before export, truncate tables, and re-enable these performance options on new site.

Alternatively, simply omit data from these tables when exporting with Backup and Migrate module or your favourite SQL client you use for export (for example, phpMyAdmin can do that, too). Of course disabling aggregation to have proper variables exported still needs to be done.

**Safety note:**

Truncating cache and session tables is only safe if you have put your site in maintenance mode. If you want to avoid it, you can't really truncate them, as they will be instantly re-populated and only effect will be performance hit and users logged out. In that case you need to omit that data, and make sure no one will change anything in the time of server switching, for the sake of consistency. Read only mode can help with that.

When talking about migration security - more modules equals more risk. My experience tells me that if your site is complicated one, you need to assume something will go wrong. So plan for it. Make sure you have time and manpower to fix it, no matter what exactly it is. Make sure you have enough old server paid for at least month after planned migration, so you can postpone and retry it. And make sure hosting company you are migrating away from will keep backups for you for at least 3 months.

---
Tags: database, migrations
---


# Question
Title: Contextual Filter for a Multiple Value Taxonomy Field
I have a content type with a taxonomy field that allows multiple values (a set of positions within the organization). I'm trying to create a view of some of these positions by passing a contextual filter via the URL. I can make a hard coded filter for a specific position by entering a filter criteria that says the field must be one of whatever position I'm looking for. However, when I try using a contextual filter instead, nothing is returned. I'm guessing it's because the contextual filter is not using a "one of" comparison. How do I create a filter that will display content types with the given position from the URL?

# Answer
Should be possible with View → Advanced → Your Contextual Filter → More → Allow Multiple Values.

Then supply values like "123+456" to get all that have either tid 123 or 456, or values like "123,456" if you only want those that have both terms applied.

**Note this does not scale well because of the way Views does its SQL**
> 3 votes

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


# Question
Title: Update hooks not being run when module enabled - chicken and egg problem
I've created a custom module to be used for deploying configuration updates like enabaling modules, reverting features, executing db queries, etc...

The module initially has an empty .module file, a .info file and a .install file with three hook\_update\_n functions.

When I enable the module, the schema version is set to the last "n" value of the update hooks, but the functions inside those hooks aren't executed.

What's the proper way to enable a "utility" module like this during deployment, and still run the update hooks via update.php?

Should the functions go in a hook\_install instead?

Seems like a "who's on first" type problem.

Thank you.

# Answer
> 1 votes
A module with an install file gets run at install, for an example if you install/enable a module with one `hook_install` and three `hook_update_` only the `hook_install` will be ran.

The best way to do what you want to do is create a module like you want, with a empty `hook_install` then just keep adding `hook_update_` functions as you need to do more stuff, then when you are done run update.php to run all the hooks.

It may also be a good idea to separate the types of stuff you want to do into groups (like create new items, and add them to the database, then another hook could be delete x and y, and another could be rename a and b) and add them as `hook_update_` so for example if you need to run something more then once for an example or maybe down the road, you could just call update.php and run that specific `hook_update_` function (if you for example wanted to run delete x and y more then once, you can).

---
Tags: updating
---


# Question
Title: is there anyway to populate nodes when type a custom content type value using node reference in drupal 7
is there anyway to populate nodes when type a custom content type value using node reference in drupal 7 ?

node refernce populate nodes when we start typing the title of the nodes . is there any option in drupal 7 that we type custom field and it populate the related nodes as it is working with the title.

Thanks

# Answer
> 1 votes
You can select a View in Content Settings in "VIEWS - NODES THAT CAN BE REFERENCED".

Let that View return whatever field values you want to return.

# Answer
> 0 votes
Try changing the widget type from "autocomplete" to "select list" of the node reference field of your content type at manage fields page.

# Answer
> 0 votes
If i get you right, you have a content type with node reference field, so when you refer a node instead of having node suggestions directly you want them to filter down by provided content type name.

Just to make sure you did'n miss this while adding the node reference fields you will get the option of choosing the content type as "Content types that can be referenced",this is one layer where you can filter/limit the node suggestions. But yes there are chances when you want to filter the suggestions on the fly,which will be interesting to have.

here is my view for implementing this-

* Build a custom autocomplete field ,backend for this can be served by a custom query.
* keep the node reference field as hidden field.
* While saving the node assign value(nid) in custom field to hidden node reference field.

**Edit** Easier way will be overiding node\_reference\_autocomplete\_value() in node\_reference.module

---
Tags: entities, nodes
---


title: Related date fields

text:
# Question
Title: Related date fields
I have made this 2 fields using the Date module and CCK.

* Field **Date 1** I use to choose the date so I put a popup widget
* Field **Date 2** which I need to be related to the first date field, and to which I have to add 6 months

Is it possible? Does somebody know how to do it?

I've tried to put some token in the "Date 2" field options *Default date* and *Relative*, but I've just had problems.

I've searched everywhere without finding a solution.

# Answer
I think you have to use the Date Restrictions module and get the date from the first date field as relative for the 2nd one.

From the module's page:

1. Date Restrictions Min/Max

Restricts valid minimum and maximum values to a fixed date, or relative interval. Dates or intervals may be provided statically in the field instance settings, or obtained from other fields attached to the host entity. Some examples:

* Reservation dates starting today, or three days ahead.
    * +18 years old.
    * Dates after, or before, 01/01/2000.
2. Date Restrictions Allowed Values

Restrict allowed values based on a multivalued date field, or the results of a view (not yet implemented).
3. Date Restrictions Host Entity

Allow restrictions based on fields in the same entity, within the add/edit form. Restrictions are performed live with ajax.
> 0 votes

---
Tags: datetime
---


# Question
Title: List all fields with the feature they are defined in
I'm interested in generating a list of all fields with a column highlighting the feature that contains the field base setting and another column highlighting the field instance feature, (if the field is defined in a feature).

Something like this...

```
**Field Name     |   Field Base Defined In  | Field Instance Defined In**
field_subtitle |   mysite_shared_fields   | blog_story_feature
field_other    |   mysite_shared_fields   | blog_story_feature

```

Has anyone attempted this? Or can anyone suggest a solution.

# Answer
Some useful functions /snippets below

```
field_info_instances();

$features_map = features_get_component_map();

$features_map['field_base'];
$features_map['field_instance'];
return;
foreach (field_info_fields() as $key => $field) {
  $base = isset($features_map['field_base'][$key]) ? join(',',$features_map['field_base'][$key]) : 'NOT IN A FEATURE!';
  $instance = 'todo';
  $rows[] = array($key, $base, $instance);
}
print theme('table', array('header' => array('machine_name', 'base', 'instance'), 'rows' => $rows));
return;

$components = features_get_components();
$field_base_component = $components['field_base'];
features_include_defaults($field_base_component);
$field_instance_components = $components['field_instance'];

```
> 0 votes

# Answer
For older sites where field instances and sites are not stored separately in features

```
$features_map = features_get_component_map(NULL, TRUE);

// loop through field instances, this gives a deep array of
// content types...
foreach (field_info_instances() as $type => $bundles) {
  // ...containing bundles...
  foreach ($bundles as $bundle => $field) {
    // ...containing fields
    foreach($field as $field_name => $field_info) {
       // the key for the feature is...
       $features_instance_key = $type . '-' . $bundle . '-' . $field_name;
       if ( isset($features_map['field'][$features_instance_key]) ) {
         $in_feature = join(',', $features_map['field'][$features_instance_key]);
       }
       else {
         $in_feature = 'NOT IN A FEATURE';
       }
       $instance_map[$field_name] = $in_feature;
    }
  }
}

foreach (field_info_fields() as $key => $field) {
  $rows[] = array($key, $instance_map[$key]);
}
print theme('table', array('header' => array('machine_name', 'feature'), 'rows' => $rows));
return;

```
> 0 votes

---
Tags: entities, features
---


# Question
Title: How to noindex on paginated pages in Drupal 7?
This question is almost a copy of: How to noindex comment/reply in Drupal 7

However in this case i would like to know how to add noindex,follow on paginated pages. For example I want to add noindex,follow on domain.com/artiklar?page=7 but not on domain.com/artiklar

How can I do this? Thanks!

# Answer
You can use Metatag module and Metatag Quick module to add a "noindex" meta tag to the artiklar content type for pagination pages (you will use the path based metatags part of metatags\_quick).
> 1 votes

---
Tags: 7, theming, paging, meta-tags
---


title: .htaccess: Options not allowed here

text:
# Question
Title: .htaccess: Options not allowed here
I just moved a new drupal site onto a directory '/drupal\_test' under my current site. So that I can test it while my current site is still running.

When I go to the directory www.mysite.com/drupal\_test. I got this error:

```
**Internal Server Error**
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Apache/2.2.16 (Debian) Server at www.bromptontech.com Port 80

```

I used putty command line to access the error log on the server and I got errors like this:

```
/var/www/drupal_test/.htaccess:Options not allowed here

```

I searched around and it seems something to do with the Allow Override settings, some say it is in httpd.conf, but I can't find this file anywhere, I can only find relevant code here in /etc/apache2/sites-enabled/000-default, I can see the tags.

Our IT guy gave me the root account to access the server, but he can't help me more than that, while I really have very limited knowledge about the server and these command lines, please can anyone help me with this? Thanks a lot!

# Answer
As your running the drupal from sub directory so modify the line containing "`RewriteBase`" (may be line no. 102) of .htaccess, change "`# RewriteBase /drupal`" to "RewriteBase /drupal\_test".

And if the above thing doesn't works for you than please try the following: Search for "`<directory /var/www/>`" in the "/etc/apache2/sites-available/default" file and change it as below:

```
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>

```
> 2 votes

# Answer
If it present, replace the `.htaccess` file with the `.htaccess` file of a fresh Drupal installation. I think there is no `.htaccess` file present in your directory.

for your case you need to put `.htaccess` file under `http://www.bromptontech.com/drupal_test/`

Try the above step first.

Try replace `.httaccess` file, If you still facing the problem then check to make sure RewriteBase / is pointing at the right folder (may need to uncomment it), and RewriteRule uses are correct.
> 0 votes

# Answer
Open up your .htaccess and remove

```
# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

```

This will make your folder contents viewable (assuming it is not turned off at a global level), so you may want to investigate a solution for that, either putting an empty index.html in those directories or something that will turn off directory listing. The symlinks shouldn't be a big deal but you won't be able to use symlinks.
> -1 votes

---
Tags: .htaccess
---


title: Validate if Date1 > Date2

text:
# Question
Title: Validate if Date1 > Date2
If I have 2 date fields in a content type: Event Start Date and Action Start Date.

Is there a way to validate that Action Start Date is later/greater than Event Start Date while creating the content?

# Answer
> 2 votes
If you use the Date module you can create one field and configure it to use a start and end date. Then the module will validate the end date is greater than start date automatically for you.

# Answer
> 1 votes
Use Date restrictions module. This is how to achieve what youre looking for:

* Enable Date Restrictions Min/Max and Date Restrictions Host Entity modules.
* Edit your target field (Action Start Date).
* Expand More settings and values » Restrictions » Minimun date.
* Choose option "Host entity: get fixed date from a field in the host entity" and select your source field (Event Start Date).

This will restrict the minimum value for the target field to the value of the source field.

If you're using date popup, it will restrict available days in the target field's popup, also if the source field changes, the target will be updated via ajax to reflect the new restriction.

# Answer
> 0 votes
How about this

> 1. hook\_form\_alter your content type.
> 2. Add custom validation handler to it.
> 3. In the validation callback try using date diff as below.

```
   // Pass the date field value while instantiating date object.
   $event_start = new DateTime('2013-01-26');
   $action_start  = new DateTime('2013-07-26');
   $date_diff = $event_start->diff($action_start);
   $date_diff->format('%R'); // use for point out relation: smaller/greater
   $date_diff->days;

```

if action date is larger/greater then $date\_diff-\>format('%R'); will return '+' else it will return '-'.

---
Tags: datetime, forms
---


title: offseting date by integer

text:
# Question
Title: offseting date by integer
I've got a content type with fields: starting date: Date (Unix timestamp) duration: integer ending date: Date (Unix timestamp)

User is setting only starting date (year, month, day) and duration (in days) end after saving the content I would like to automatically calculate ending date (=starting date + duration)

I suppose I should use rules. I tried using actions like set value or calculate value but I failed. Could you help me?

# Answer
> 1 votes
Interval module may help you. It provides an interval field type and also a rules action: "Apply an interval to a date".

# Answer
> -1 votes
For a quick fix I would recommend making a simple custom module with this function:

```
function YOUR_MODULE_node_presave($node) {
  if($node->type === "your_content_type") { // Replace with the content type of your node.
    // Replace $node->XXX with the actual names of your fields.
    $startdate = $node->start_date[LANGUAGE_NONE][0]['value'];
    $duration = $node->duration[LANGUAGE_NONE][0]['value'];
    $enddate = &$node->end_date[LANGUAGE_NONE][0]['value'];

    $enddate = strtotime('+ ' . $duration . ' days', $startdate);
  }
}

```

---
Tags: 7, rules, datetime
---


title: too many 503 errors

text:
# Question
Title: too many 503 errors
I am using cloudflare as a CDN. It started giving 520 errors lately,followed with the server going offline. I enquired to their customer support. They said that my server is giving 503 errors and thats the reason. This is what they pulled from their error log:

> 09/14 07:04:39 adda0ac581c038e www.exmple.com /favicon.ico 115.241.244.247 141.101.116.101 503 9026 www.example.com 141.101.116.101 115.241.244.247 23f8 /favicon.ico MISS 503
>
> 09/14 07:04:37 adda09fc63a038e www.example.com /article/articlename 115.241.244.247 141.101.116.101 503 9095 www.example.com 141.101.116.101 115.241.244.247 23f8 /articlename MISS 503
>
> 09/14 07:04:33 adda086e1d6038e www.example.com /favicon.ico 115.241.244.247 141.101.116.101 503 9026 www.example.com 141.101.116.101 115.241.244.247 23f8 /favicon.ico MISS 503
>
> 09/14 07:04:22 adda03f95c6038e www.example.com /articlename 115.241.244.247 141.101.116.101 503 9095 www.example.com 141.101.116.101 115.241.244.247 23f8 /articlename MISS 503

I contacted my server administrator and he said that the problem is with my script. I dont know where to start. The frequency of the error started increasing nowadays and it really annoys me as well as my customers. I noticed that this is found more if I try to enable a module, add content,flush the cache, etc. Any help will be greatly appreciated.

# Answer
> 3 votes
503 (Service unavailable) errors are usually caused by the server being overwhelmed by requests (or beng down for maintenance). It is unlikely that a script (which runs on the client side) is going to bring a server to its knees.

Check your logs at `/admin/reports/dblog` to see if your site has had a lot of attempts by spammers to log in. It might be a Denial of Service by spam bots, in which case you should implement some anti-spam measures.

---
Tags: 7
---


title: Custom DOM placement using AJAX

text:
# Question
Title: Custom DOM placement using AJAX
I'm using unlimited image upload option in my content type. Upload image and remove the uploaded image options are working fine with the unlimited option.

Usually, the uploaded images will be displaying one by one (**Last in Last** \- Image1, Image2, Image3,..ImageN). But, I need show the uploaded image at first/top place (**Last in First** \- ImageN,..., Image3, Image2, Image1).

Can you please help me in this?

**UPDATE:**

PFA for bulk node edit page in admin section. I used image upload as nested objects (unlimited). You can see two nodes display in edit mode (Title 1 and Title 2).

* New upload field should be add before the exiting uploaded image section when I click the "Add another item" button OR
* Ok. It can display under the existing uploaded image section. But, the image should be reorder as per my above requirement when I click the "Upload" button.

**Note:** I saw some hook in ajax.js file that will handle the ajax process. But, I don't know, how it's help to solve my problem.

```
 *  Drupal.behaviors.myCustomAJAXStuff = {
 *      attach: function (context, settings) {
 *        Drupal.ajax['edit-submit'].commands.insert = function (ajax, response, status) {
 *          new_content = $(response.data);
 *          $('#my-wrapper').append(new_content);
 *          alert('New content was appended to #my-wrapper');
 *        }
 *      }
 *    };

```

# Answer
I suggest you first create a View of the image files with node id passed as Contextual Argument. Make it display the images in the order you want and then add this View as a field using Viewfield
> 0 votes

# Answer
Drupal.behaviors are generally called after any new DOM element has been added to or removed from your web page during AJAX requests. Thus it becomes easier to execute your js code. Behaviors can be fired multiple times during page execution and can be run whenever new DOM elements are inserted into the document.

Also, modules could override or extend an existing behavior (e.g. if one module has a behavior of adding a fade effect on all links, a second module could replace the behavior by a different fade effect).

Syntax of writing the code is as below:

```
Drupal.behaviors.MyModuleName = {
  // This behavior function is called when new element is being added.
  attach: function (context, settings) {
    // Do your js stuffs you want to do after your AJAX call.
  },

  // This behavior function is called when elements are removed.
  detach: function (context, settings) {
    // Do your js stuffs you want to do after your AJAX call.
  }
}

```

---

Example (putting some new html after our AJAX call in a div):

```
(function($) {
  Drupal.behaviors.MyModuleName = {
    attach: function (context, settings) {
    // Weare going to do a ajax call, using a menuu call back.
      $.post( 'yourCallBackMenuPath', {
        // Your passsed parameters to the server side for desired functionality.
      }, function(data){
        // 'data' is the defined variable to collect value returned from server
        // which contains the html code which we are going to replace.
        $('elementSelecter').html(data);
      }
    );
  }
}
}(jQuery));

```

Detailed explanation/discussion regarding the same is available here.
> 0 votes

# Answer
Try to change append() on before() or insertBefore()

```
Drupal.behaviors.myCustomAJAXStuff = {
       attach: function (context, settings) {
         Drupal.ajax['edit-submit'].commands.insert = function (ajax, response, status) {
           new_content = $(response.data);
           $('#my-wrapper').before(new_content);
           alert('New content was appended to #my-wrapper');
         }
       }
     };

```
> 0 votes

---
Tags: 7, ajax
---


title: Disable module while running command

text:
# Question
Title: Disable module while running command
I have a custom drush command that does some pretty heavy node creation etc. I would like to disable certain modules only for the duration of the script to improve their performance.

I can not do a `drush dis module_name` before running my command because I need the modules to be active on the site while the script is running, but not active for the runtime environment of the current command.

I would rather not have to hack core, but from what I can see, I'm probably going to need to alter something in either `module_list()` or `drupal_load()` since neither of them have any hooks.

Is there any way to do what I'm after without hacking core?

# Answer
Here is one solution that I came up with after looking around in core's code. It seems to work as expected.

```
$module_list = module_list();
if (isset($module_list['token'])) {
    unset($module_list['token']);
}
// Reset the list to our new list of modules!
module_list(false, false, false, $module_list);
// Force to regenerate the stored list of hook implementations.
module_implements('', false, true);

```
> 1 votes

---
Tags: 6, drush
---


# Question
Title: How to print render Location's sub-fields?
I'm trying to print render inside my node--article.tpl.php two of Locations sub-fields: the Street address and City so that it looks like this: 16 Fleet Street, London -- without printing all other parameters (Province, Country etc) So far I've got

```
<?php
    print
        render($content['field_location'][0]['#street']) . ', ' .
        render($content['field_location'][0]['#city']);
?>

```

But it doesn't work. Can someone please help?

# Answer
If you have `devel` module installed than you check the exact contents of the array as: `dsm($content);`
Even if you don't have the devel module installed than check the contents of array as:

```
echo '<PRE>';
print_r($content);
echo '</PRE>';

```

I guess you probably have missed the language attribute - for regular non-location fields it's: `$content['field_location']['und'][0]['#street'];` and `$content['field_location'][0]['#city'];`
> 1 votes

---
Tags: theming
---


# Question
Title: How can I change divs and spans in a view
i have an unformatted view that show each element as a row. I want to change the css of some divs an span but i do not know how I can refer to them. The HTML output is:

```
<div class="view view-venue-view view-id-venue_view view-display-id-page view-dom-id-e95cd3ef12fe312b9c0dced54b3c2820">
<div class="view-content">
<div class="views-row views-row-1 views-row-odd views-row-first">
<div class="views-field views-field-title">
<div class="views-field views-field-field-venue-image">
<div class="views-field views-field-field-venue">
<span class="views-label views-label-field-venue">Address: </span>
<div class="field-content">Some Address </div>
</div>
<div class="views-field views-field-field-venue-date">
</div>
<div class="views-row views-row-2 views-row-even views-row-last">
</div>
</div>

```

For example I want to make the Address Label bold. I have tried to write to the css file #view-label-views-label-field-venue span { //some code} but it doesn't work. Any ideas on how general to refer to items of a view in order to change their css?

Thank you Stella

# Answer
If it was `<div id="div-id">` you would use `#div-id {...` in your css.

For a class like `<div class="div-class">` you would use `.div-class {...`
> 0 votes

# Answer
with your html structure span.views-label-field-venue {font-weight:bold;} .
> 0 votes

---
Tags: views, theming
---


title: Building a employee directory

text:
# Question
Title: Building a employee directory
I am new to drupal but long time programmer. I'm trying to figure out how to create a directory similar to the one here (http://studentunion.okstate.edu/directory). Using feeds i can get the info to import but every entry goes into its own node. So question is using feeds how do i get all the entries to display on a single page.

# Answer
> 1 votes
Since you've got each employee in his/her own node, you can use views to show pages or blocks/panels with all employees (or certain employees depending on the filters you set on the view).

---
Tags: feeds
---


# Question
Title: Warning: uasort(): Array was modified by the user comparison function in FacetapiWidget->applySorts()
I'm trying to build my own sorting function implementing `hook_facetapi_sort()` and sorting the following data by weight.

```
name, weight
dog, -2
cat, 1
zebra, -5
dolphin, 3
bee, 5

```

The code I wrote so far is the following one.

```
function zoo_facetapi_sort_animal(array $a, array$b) {
  $a = db_query("select weight from {animal} where name = :a", array(':a' => $a['#markup']))->fetchAssoc();
  $b = db_query("select weight from {animal} where name = :b", array(':b' => $b['#markup']))->fetchAssoc();

  $a_value = (isset($a['weight'])) ? $a['weight'] : 0;
  $b_value = (isset($b['weight'])) ? $b['weight'] : 0;

  return strnatcmp($b_value, $a_value);
}

```

The result is what I expected.

```
zebra
dog
cat
dolphin
bee

```

I get the following error message.

> Warning: uasort(): Array was modified by the user comparison function in FacetapiWidget-\>applySorts() (line 230 of /var/www/zoo.dev/sites/all/modules/facetapi/plugins/facetapi/widget.inc)

How do I avoid getting that message?

# Answer
> 0 votes
Register your own function as FacetAPI sort callback. Then select it in the FacetAPI sort order.

http://example.com/admin/config/search/facetapi/search\_api%40default\_node\_index/block/field\_animal\_type/edit

http://drupalcontrib.org/api/drupal/contributions%21facetapi%21facetapi.api.php/function/hook\_facetapi\_sort\_info/7

NB: You also accidentally collapsed the space between **array** and **$b**

function zoo\_facetapi\_sort\_animal(array $a, **array$b**) {...}

```
/**
 * Implements hook_facetapi_sort_info
 */
function zoo_facetapi_sort_info() {
  $sorts = array();

  $sorts['active'] = array(
    'label' => t('Animal ...'),
    'callback' => 'zoo_facetapi_sort_animal',
    'description' => t('Sort by whether the animal is ...'),
    'weight' => -50,
  );

  return $sorts;
}

function zoo_facetapi_sort_animal(array $a, array $b) {
  ...
}

```

---
Tags: hooks, search
---


# Question
Title: how to populate select list using hook_form_alter()?
I wanted to add values to a select list dynamically. Another module generates an array from a web service and I want to use those values to populate a select list in a form using ***hook\_form\_alter.***

I tried directly adding the options in #options of the field using the following code

```
<?php $form['field_mage_category']['und']['#options']=$arr; ?>

```

The above code adds the options to the select list and returns a value according to the options selected but when the form is loaded again for editing. The option is set to default value and other issue is that when a single option is deleted. The respective value is not getting deleted from the **field\_data table.**

I tried using #after-build property to populate the select list.below code is the call to \_add\_category\_select\_list function

```
      <?php function main_menu_form_alter(&$form, &$form_state, $form_id){
       if($form_id=='main_menu_node_form'){
           form['field_mage_category']['#after_build'] = array('_add_category_select_list');
          } ?>

```

and following is the code in the \_add\_category\_select\_list function

```
<?php function _add_category_select_list($element, &$form_state) {
$mlib=new Mlibrary();
$main_category=$mlib->get_main_menu_Categories();
   foreach($main_category as $main){
       $element['und']['#options'] = array($main['category_id'] => $main['Title'])+  $element['und']['#options'];
    }

return ($element);
   } ?>

```

The above code populates the select list but when the option is selected it is not returning any values for the options selected. Can anyone give me a proper way to add #options to select list dynamically using hook\_form\_alter or any other options that will allow me to add options from my module.

# Answer
Your first method was very close; I wouldn't advise using an `#after_build` function for this simply because it's not necessary.

When you're dealing with field widgets added to forms the actual form elements (textfield, select, checkbox, etc.) are a little further down in the array (see Why is hook\_form\_alter() so messy? for more info).

In your case this should work:

```
$form['field_mage_category']['und'][0]['value']['#options'] = $arr;

```
> 1 votes

# Answer
For select field we can use as follows

```
$form['field_task']['und']['#options'] =$arr;
//array('black'=>'black')

```
> 2 votes

---
Tags: entities
---


# Question
Title: How do I output view (page display) content in page--<view_path>.tpl.php?
I have a view called sabk\__view whose path is /sabk. It has a page display mode. I created a page named page--sabk.tpl.php in order to display the content of view, but I don't know what code displays the content of view.

I also checked *modules/system/page.tpl.php* to see if there is any useful variable (e.g. **print render($content)**), but none of them displayed anything about view.

How can I display view's output in a specific `<div>` tag? Do I need to implement `<theme>_preprocess_node`?

I am using Drupal 7, if that makes any difference.

# Answer
I use the following function to solve the issue

```
print views_embed_view('NAME_OF_VIEW','page');

```
> 3 votes

# Answer
Under view's advanced option there will be a option called as theme. Click on that. This will display the template files associated with views.

You need to copy that file and place in your template folder with any one of the names.

Try to clear cache/ rescan templates.
> 2 votes

# Answer
It's a ds\_extras module in the package Display Suit. It has a secret part, you have to turn on: admin/structure/ds/list/extras \> Other \> Views displays

Than you can add any views to render by ds: admin/structure/ds/vd, so you have close to full control over the html output of view.
> 2 votes

---
Tags: views, nodes
---


# Question
Title: How do I create a url for views that displays values using exposed filter?
I created a view block that displays in table where there is an exposed filter called category:

```
Category | Data
A           1
A           2
B           3
C           4

```

now I want to create multiple html links where their url points to a page where this view block is displaying.

However in this page I only want to display the data view where certain filter is activated

example:

Link 1 \> url points to page x with view only showing items with category A Link 2 \> url points to page x with view only showing items with category B

How do I create a url for views that displays values using exposed filter?

# Answer
> 0 votes
I think you want to use a contextual filter, not an exposed filter. The contextual filter will take an argument (such as the category term id or node id, depending on whether it's a taxonomy term or a node) and filter out all other nodes.

# Answer
> 0 votes
Go to your view with the exposed filters and select the filters you want and submit. Notice in the URL now there will be your exposed filter values, which will look like this:

yoursite.com/page-path?exposed\_filter\_1=filter\_value1&exposed\_filter\_2=filter\_value2

Then you can copy that url and make a link out of it elsewhere.

If your link has the ?exposed\_filter\_1=filter\_value1&exposed\_filter\_2=filter\_value2 part on the end then the filters will be set when you click the link.

# Answer
> 0 votes
Edit the view, click on the exposed filter. Look at the "Filter identifier" field, use the value of that field in the url.

If the Filter identifier says "type", the path you have placed the block on is "path", and the category id is 1, the url will be http://example.com/path?type=1

---
Tags: uri, views
---


title: To show content as links

text:
# Question
Title: To show content as links
I want to display 10 contents of same content type as links in a single view. Is it possible? How?

# Answer
views is the module you are looking for. It will allow you to list your contents filtered by content type as links. Look at this tutorial before you start.
> 0 votes

---
Tags: views, nodes, navigation
---


# Question
Title: What's the default weight of a form's submit element?
The following code is fairly standard for adding a submit button to the bottom of a form:

```
// Submit button.
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
);

```

It always appears at the bottom of the form so I assume it is assigned a 'heavy' #weight by default. Does anyone know its default value?

# Answer
> 7 votes
A submit button appears at the bottom of the form usually because it's simply added last in the form definition.

A submit button can still be placed anywhere and weighted using the `#weight` property.

The default weight is assigned automatically.

The relevant core code is in

`form_builder`

```
// Assign a decimal placeholder weight to preserve original array order.
if (!isset($element[$key]['#weight'])) {
  $element[$key]['#weight'] = $count/1000;
}
else {
  // If one of the child elements has a weight then we will need to sort
  // later.
  unset($element['#sorted']);
}

```

If not present the`#weight` property is calculated dynamically based on the count/item position while looping over the form element set.

---
Tags: forms
---


title: How to change core's default services

text:
# Question
Title: How to change core's default services
Dependency Injection is added to core, but there's no documentation to tell how developer can alter the default services. For example, I would like to change cache.bootstrap class to APC Caching.

# Answer
> 5 votes
You can look at LanguageTestServiceProvider to see how alterations are made. Or I can offer my class:

```
<?php
namespace Drupal\mongodb;

use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;

/**
 * MongoDB service provider. Registers Mongo-related services.
 */
class MongodbServiceProvider implements ServiceProviderInterface, ServiceModifierInterface {

  /**
   * {@inheritdoc}
   */
  public function register(ContainerBuilder $container) {
  }

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    foreach ($container->findTaggedServiceIds('mongodb.override') as $id => $attribute) {
      $container->setDefinition(substr($id, 8), $container->getDefinition($id));
    }
  }

}

```

Basically, in `alter` you need to use the `getDefinition` method, do something with the definition and then use the `setDefinition` method to put it back.

and then here's the relevant parts of mongodb.services.yml:

```
services:
  mongodb.flood:
    class: Drupal\mongodb\Flood\MongoDBBackend
    arguments: ['@mongo', '@request']
    tags:
      - { name: mongodb.override }

```

---
Tags: 8, symfony-services
---


title: Page title always displaying "Error"

text:
# Question
Title: Page title always displaying "Error"
I am porting the Disqus module to Drupal 8.

The new routes are working fine, except for the page title, which always displays "Error" instead of the desired title. I have already implemented `hook_menu()`.

What am I doing wrong?

# Answer
There is something wrong in the error handling with recoverable fatal errors.

They're not displayed but the affect the page title. Have a look at the watchdog output, there you should see some PHP errors.

This is a bug, so not really a good question for here, but for the time being, might help others.

Opened https://drupal.org/node/2100123
> 1 votes

# Answer
Static titles for a route can be defined with `_title` under `defaults` in the module.routing.yml file:

```
disqus.admin:
  path: '/admin/config/services/disqus'
  defaults:
    _form: '\Drupal\disqus\Form\DisqusSettingsForm'
    _title: 'Some static title'
  requirements:
    _permission: 'administer disqus'

```

You can also use `_title_callback` if you need to define a dynamic title. Full details in this change record.
> 0 votes

---
Tags: routes, 8
---


title: Alphabetically filtering a view

text:
# Question
Title: Alphabetically filtering a view
I have a view that I need to filter alphabetically. How is this done? I need to also add a list item for each letter of the alphabet, with an ID of that letter for a quick anchor scroll-to script. Can anyone help me getting this done?

# Answer
> 2 votes
This video is from Nodeone.se addresses sorting, but the entire series on Views is an excellent tutorial.

# Answer
> 0 votes
I think the Lexicon module will help you.

> A lexicon is a stock of terms used in a particular profession, subject or style; a vocabulary. The Lexicon module generates one or more Lexicon pages based on terms in taxonomies and optionally marks terms in the content and links them to the appropriate Lexicon page.

---
Tags: views
---


# Question
Title: How to change the behaviour or display of the language switcher?
On translated pages the language switcher shows links to translated languages, but for untranslated languages there is no link, but the name of the language without a link. In the case, that there is no corresponding node in a given language, i would like the language switcher to show a link to the front page instead.

How can i accomplish this behaviour? Thank you very much!

# Answer
> 13 votes
Add next into template.php file of your theme:

```
<?php
  function YOURTHEMENAME_links__locale_block($variables) {
    foreach($variables['links'] as $key => $lang) {
      if (isset($lang['attributes']['class']) && in_array('locale-untranslated', $lang['attributes']['class'])) {
        // Set here any page link.
        $variables['links'][$key]['href'] = '<front>';
      }
    }
    return theme_links($variables);
  }

```

# Answer
> 4 votes
there is a module for this now - Language Switcher Fallback. Does exactly what you asked, directing the user to the frontpage if no translation to a node. See here https://drupal.org/project/language\_switcher\_fallback

# Answer
> 1 votes
In the end I used this approach.

```
function YOURTHEME_language_switch_links_alter(array &$links, $type, $path) {
  $language_type = variable_get('translation_language_type', LANGUAGE_TYPE_INTERFACE);

  if ($type == $language_type && preg_match("!^node/(\d+)(/.+|)!", $path, $matches)) {
    $node = node_load((int) $matches[1]);

    if (empty($node->tnid)) {
      // If the node cannot be found nothing needs to be done. If it does not
      // have translations it might be a language neutral node, in which case we
      // must leave the language switch links unaltered. This is true also for
      // nodes not having translation support enabled.
      if (empty($node) || entity_language('node', $node) == LANGUAGE_NONE || !translation_supported_type($node->type)) {
        return;
      }
      $langcode = entity_language('node', $node);
      $translations = array($langcode => $node);
    }
    else {
      $translations = translation_node_get_translations($node->tnid);
    }

    foreach ($links as $langcode => $link) {
      if (isset($translations[$langcode]) && $translations[$langcode]->status) {
        // Translation in a different node.
        $links[$langcode]['href'] = 'node/' . $translations[$langcode]->nid . $matches[2];
      }
      else {
        // No translation in this language, or no permission to view.
        $links[$langcode]['href'] = '<front>';
      }
    }
  }
}

```

Which replaces this code fragment in the original Translation module.

```
  else {
    // No translation in this language, or no permission to view.
    unset($links[$langcode]['href']);
    $links[$langcode]['attributes']['class'][] = 'locale-untranslated';

```

I am pretty sure the other solution is more beautiful, but this solution is also working.

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


# Question
Title: How do I customise individual menu links?
I have a menu created through admin/structure/menu.

On some of the menus, I would like to place a var after the title.

I have tried placing the following in my theme template, but nothing happens.

```
 function mytheme_menu_link(array $variables) {
   print_r($variables['element']);
 }

```

How could I just place the content of a PHP variable after the menu link title?

# Answer
If you just need to add a string after the menu title, you can use the following code.

```
function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

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

  $output = l($element['#title'] . ' ' . t('the string you need to add'), $element['#href'], $element['#localized_options']);

  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

The alternative would be using the following code, which would give to who translate the string more context to translate it.

```
function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

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

  $output = l(t('!title the string you need to add', array('!title' => $element['#title'])), $element['#href'], $element['#localized_options']);

  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

You could also implement a preprocess function to alter the title.

```
function mytheme_preprocess_menu_link(array $variables) {
  $variables['element']['#title'] = t('!title the string you need to add', array('!title' => $variables['element']['#title']));
}

```
> 2 votes

---
Tags: routes, theming
---


# Question
Title: Preprocess function trying to alter title
I have used this code in template.php.

```
function mytemplate_preprocess_node(&$variables) {
  $variables['title'] = "trial" . check_plain($node->title);
}

```

I was trying to alter the page title, and wanted to make a test before. When I use that code, the title disappears from the teaser. Do you know why?

# Answer
> 4 votes
template\_preprocess\_node() uses the following code.

```
  $variables['node'] = $variables['elements']['#node'];
  $node = $variables['node'];

  $variables['date'] = format_date($node->created);
  $variables['name'] = theme('username', array('account' => $node));

  $uri = entity_uri('node', $node);
  $variables['node_url'] = url($uri['path'], $uri['options']);
  $variables['title'] = check_plain($node->title);

```

It is perfectly fine, to set `$variables['title']` in `hook_preprocess_node()` instead of calling `drupal_set_title()`/`drupal_get_title()`. The error in the code shown by the OP is not setting the local `$node` variable. The correct code is the following one.

```
// Drupal 7
function mytemplate_preprocess_node(&$variables) {
  $variables['title'] = "trial" . check_plain($variables['node']->title);
}

```

In Drupal 8, the equivalent for the code I wrote would be the following one.

```
// Drupal 8
function mytemplate_preprocess_node(&$variables) {
  $variables['label'] = "trial" . check_plain($variables['node']->label());
}

```

This would not change the title used for the `<title>` though. If you need to change that as well, you should use the following code.

```
// Drupal 7
function mytemplate_preprocess_node(&$variables) {
  $variables['title'] = "trial" . check_plain($variables['node']->title);
  drupal_set_title("trial" . check_plain($variables['node']->title), PASS_THROUGH);
}

```

# Answer
> 3 votes
You shouldn't be using that to alter the page title, you can just use `drupal_set_title();`

# Answer
> 3 votes
Also inducing title to the $variables array will not change the page title in the browser tab. So as already suggested page title can be set conditionally as below.

```
function mytheme_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your_content_type") {
    drupal_set_title("my_title");
  }
}

```

# Answer
> 2 votes
The title 'disappears' because you are assigning and undefined value to it. You're using `$node`, but that variable isn't in scope/defined.

Use:

```
$node = $variables['node'];
$variables['title'] = "trial" . check_plain($node->title);

```

Also, as Steven has already said, you should (ideally) use `drupal_set_title()` to set the page title. However, depending on when (in the page execution) you call this function, it may or may not affect the output of what you're seeing - it can be a bit tricky. It appears you're changing the title on the theme layer, at which point I'd say your approach is generally fine, but it may be nicer to do the change in something like `template_preprocess_page()`, instead.

---
Tags: theming
---


# Question
Title: Automatically fill title attribute of image
I defined a content type that consists of a field photo for which I can add up to 20 photos. I'm using the Multiupload Imagefield Widget module to be able to upload several images to one node. Since I'm using descriptive filenames, I would like the title attribute of each image to be automatically filled (instead of filling them all by myself). Does anybody know how to do this?

I looked at the File entity module, but this creates individual pieces of content for each Image I upload. That is not the direction I want to go in.

UPDATE: I'm using D7

# Answer
If you use D6 try image\_fupload module.

> Automatic node title creation and predefining of imagefield fields (customisable / themeable / editable by user / token support \[imagefield\])
> 0 votes

---
Tags: media
---


title: Automatic Node Reference

text:
# Question
Title: Automatic Node Reference
my task is, to create a forum-like behaviour which resembles StackExchange's platform with the only difference that only the question's poster will be able to comment on the replies.

My thought is to create a Content Type that describes the initial post/question, and then add a "Reply to this" button that should somehow create a new node of type "Reply" or something (ideally in the front-end, but that's another story - feel free to comment on it though) that should get *automatically* referenced to the initial post/question.

The "Reply" Content Type should maybe support Drupal's core comment functionality but restricted somehow to the initial post/question's creator.

The basic question is the automatic referencing. Other than that if you got any idea about the front-end content creation and/or the limitation of comments to the afforementioned role and CT, I'd be glad to get some extra input :)

EDIT: using Entity Reference module, not Node Reference module, fyi.

# Answer
> 1 votes
For the automatic referencing you could use entityreference\_prepopulate. So your button to answer from the question node would link to something like node/add/answer/27 where 27 is the question node nid. The module supports to hide the field once the value is in the URL so the user dont have to see the field.

# Answer
> 1 votes
I am in little doubt for not using comment as reply here. Module Question/Answer does with same entity combination of nodes and comments.

Otherwise modules like :

>

can be used to auto populate the node to be refereced with from url.

---
Tags: 7, comments, nodes
---


title: How to theme a field formatter?

text:
# Question
Title: How to theme a field formatter?
**Context**: using the registration module, I am trying to customize the entity registration form depending on the user:

* show a 'please login in order to register' to anonymous visitors
* show a 'edit registration' link to already registered users
* show the registration form, as well as an info message (xx seats left / fully booked butwait list is still open), to not registered yet users.

**Current status**: I managed to customize the field display using a field template in my custom theme. Unfortunately the field is not displayed anymore when the event is fully booked (without a 'fully booked' message). I changed that by implementing a custom field formatter based on the registration 'form' field formatter.

**Problem**: In order to have the thing easier to maintain, it sounds like a better idea to have the theming done directly in the module (named 'zss'). Although it is probably easy meat for drupalers, I do not manage to do that so far. The current code reads like:

```
function zss_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // we know we should only have a single item
  if (isset($items[0]['registration_type']) && !empty($items[0]['registration_type'])) {
    $reg_type = registration_type_load($items[0]['registration_type']);
    $settings = $display['settings'];
    $label = !empty($settings['label']) ? $settings['label'] : $reg_type->label;

    if ($display['type'] == 'zss_registration_default') {
      // Enable registration link if accessible.
      list($entity_id) = entity_extract_ids($entity_type, $entity);
      if (registration_register_page_access($entity_type, $entity)) { // && registration_status($entity_type, $entity_id)
        $registration = entity_get_controller('registration')->create(array(
          'entity_type' => $entity_type,
          'entity_id' => $entity_id,
          'type' => $reg_type->name,
        ));
        $element[0] = drupal_get_form('registration_form', $registration);
//         I tried the following to theme the field:
//         $element[0] = theme('zss_theme_zss_registration_default', drupal_get_form('registration_form', $registration));
      }
    }
  }
  return $element;
}

/**
 * Implements hook_theme().
 */
function zss_theme() {
  return array(
    // The theme function that our formatter uses:
    'zss_theme_zss_registration_default' => array(
      // Don't forget that all Drupal 7 theme functions have only one argument,
      // so you declare what variables get passed within that argument instead.
      // See http://drupal.org/node/224333#theme_changes
      'variables' => array('element' => NULL),
    ),
  );
}

/**
 * Theme function for 'zss_theme_zss_registration_default' field formatter.
 */
function zss_theme_zss_registration_default($element) {
  // Here I would like to have a condition, depending for instance on the user id
  return $element;
}

```

Thank you in advance for your help.

# Answer
> 1 votes
What I wanted was actually to theme the registration field directly from the module, by implementing zss\_field\__field\_registration($variables).

So, if you have a similar problem, you need to proceed in 2 steps:

* create a custom field formatter for your registration fields (described above). This will allow to display the form even when the current user has already registered.
* theme the registration field from your module so as to display it according to the current user and available seats.

---
Tags: entities, theming, users
---


# Question
Title: Is there any way of removing (or unflagging) all of a user's flags?
I have a situation where a privileged user (role that is purchased) can flag content and receive email notifications to comments posted. When the role is expired, I need for them to stop receiving these emails. Is there any way (possibly using rules) to unflag all of the content they have flagged? Or is there another approach I should be taking?

# Answer
> 0 votes
You have to find out the event for expiring the roles, there you can unset the flag programmatically. However with other approach you can also add a check the role of user you are sending email to.

Here goes the steps:

* Install rules\_conditional module. This module allows to add extra conditions inside the rules action.
* Please check the screen shots.

Configurations as in following screenshot.

**Remember to have the nesting structure as in screenshot.**

---
Tags: rules, flags
---


# Question
Title: Database table cache_views_data is extreme large, what size is normal?
I have a Drupal 7 site with ~70,000 nodes and ~500,000 terms. During some investigations for the cause of substantial performance problems, I found out that the database table cache\_views\_data is about 18 GB big. Is this normal?

UPDATE: I am using time based and contend based (Views content cache) caching.

# Answer
There is no normal size, it depends on your site, but I think that there's some error because this table grows exponentially.

My site was down because the size of this table. In my case, with a few views & something like 1000 users this table was 29 Gigabits. I deleted it and then everything went back to normal.

I suggest you to keep an eye on the tables of your database, specifically this table.
> 0 votes

---
Tags: views, caching
---


# Question
Title: Can I host Drupal alongwith Google App Engine?
I am new to Drupal as well as Google App Engine. I want to create a scalable website with few specialized apps in Google app engine and integrate with Drupal. Given both the platforms are extensively used, it seems to me that they should be supporting each other. However, I checked both Google app engine and Drupal website but could not figure out if they support each other. So my question is , is there any way I can host Drupal with Google app engine? Can they work together in the same platform?

# Answer
> 3 votes
Google App Engine now supports PHP, yes you can. But Drupal technically is supposed to run on an Apache server (.htaccess rewrites, restrictions and options) with normal email servers that can be handled using normal PHP's mail(), and PDO, you will need to take care of providing alternatives for the services.

Mainly, GAE has limitations in emails, SQL, and writable file system. Here is a link to a post that helped me a lot: http://blog.boombatower.com/drupal-google-app-engine

---
Tags: performance, google-search-console
---


# Question
Title: In a form, I want subsequent fields depending upon previous field?
I have an entity creation form and I have a radio button as a field. Now what I need is, if while adding the entity, if radio button is set, then one more field just below should appear otherwise not.

# Answer
If looking for a module, you can use the D7 -dev version of conditional\_fields

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

Alternatively, you can tweak the forms directly in code using `hook_form_alter` and the States API

In this example, I show the UPC field when the specified operation value is chosen in a select box:

```
  // Define available batch operation callbacks
  $operations = array(
    'infinity_batch_sync_products' => 'Import and sync product details',
    'infinity_fetch_products' => 'Fetch list of available products',
    'infinity_fetch_product' => 'Fetch detail on single product'
  );

  $form['operation'] = array(
    '#type' => 'select',
    '#title' => t('Select operation'),
    '#options' => $operations,
    '#required' => TRUE,
  );
  $form['upc'] = array(
    '#type' => 'textfield',
    '#title' => t('UPC'),
    '#description' => t('Enter the product UPC code (commerce product SKU)'),
    '#default_value' => 0,
    '#size' => 20,
    '#maxlength' => 20,
    '#states' => array(
      'visible' => array(
       ':input[name="operation"]' => array('value' => 'infinity_fetch_product'),
      ),
    ),
  );

```

The "UPC" field only shows when the operation is "infinity\_fetch\_product"
> 4 votes

---
Tags: forms
---


title: Read the content of a file

text:
# Question
Title: Read the content of a file
I have added a content type in Drupal 7 which contains only a file field. Every file needs to contain an array like the following:

```
'rows' => array(
   array(0,0), //(x,y) values
   array(90,90),
   array(59,70),
   array(65,77),
   array(85,66),
 )

```

I want from the view module to read the content of the file and send the array to the selected graph type; for example, the user select a file and then a pieChart graph.

how can the content of the file be send to the pieChart library? Is that possible from the Views module? What function have to be added to the view plugin in order to send the content of the file to the selected library?

# Answer
You will probably have to create a library, module, or simple a function Wick does the logic of this, and then call the function from where you want (views).

It's a pretty generic question, without more info is difficult to know what you are trying to achieve, but in similar situations what we use to do is create a separate library or module which is called from cron, for example.

This library will keep updated a second content type, with the contents of your files, RSS, XML, etc.

When views saves this content, you'll simply have to link both content types, probably making it faster simply reading contents and leaving the logic to a background process (managed by cron).

But again, maybe you are trying to achieve a different thing.
> 0 votes

---
Tags: views
---


# Question
Title: Tracking an authenticated user's first visit to a Panels page and forward them to another page on subsequent visits
I'm looking to expose authenticated user stat information to CTools / Panels. Basically, I need to have a Panel variant that says: If the user has never visited the page, display this variant, if they have, display this variant.

# Answer
You want an `access plugin`. See What are Ctools plugin (content type, access, etc), and how does one create them? for an intro to how to build one.
> 1 votes

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


# Question
Title: is it possible to have one views-view--VIEWNAME--page.tpl for multiple views?
I have 8 content types and 4 of them are the same and the difference is just their name. they all have a page view and the way I display them on screen is the same. instead of having 8 pages. (VIEWNAME\_i stands for the i-th view.)

* views-view--VIEWNAME\_i--page.tpl
* views-view-field--VIEWNAME\_i--page.tpl

I need a template function to reduce these 8 pages into 2. I want to define a general page for views-view--VIEWNAME\_i--page.tpl. I would assign every view's variables in this function. I also want to do the same for fields page.

# Answer
> 7 votes
## Same template file for multiple view pages

You don't need to use any preprocess function to call the same template file for multiple view pages.

Just edit the view, click on `edit view name/description` and add the `View tag`

Now, create template file `views-view--my-custom-view.tpl.php` and mark any view with the same tag, so all of them will use the same template file.

## Same template file for multiple view pages and displays

If you have multiple views with the number of displays attached to them, and you need to define one template file for any view or display, you can achieve it with the following approaches:

**Non-coding solution**

You can create a separate view for each view display, and mark the view with the appropriate tag, for example:

```
view_custom_pages
  View tag: custom-pages
  displays: Page1, Page2, Page3 ...

view_custom_blocks
  View tag: custom-blocks
  displays: Block1, Block2, Block3 ...

```

Each page from `view_custom_pages` will use `views-view--custom-pages.tpl.php`

Each block from `view_custom_blocks` will use `views-view--custom-blocks.tpl.php`

**Coding solution**

If the above mentioned solution does not satisfy your needs, then you can use template\_preprocess\_views\_view() to define theme suggestion for any view display

```
/**
 * Implements template_preprocess_views_view().
 */
function YOURTHEME_OR_MODULE_preprocess_views_view(&$vars) {

  $view = $vars['view'];

  // an array with views and displays which should use only ONE template file.
  $shared_themes = array(
    'SOME_VIEW_NAME' => array(
      array(
        'displays' => array(
          'page',
        ),
        'theme_suggestion' => 'views_view__custom_pages'
      ),
      array(
        'displays' => array(
          'block',
          'block_1'
        ),
        'theme_suggestion' => 'views_view__custom_blocks'
      ),
    ),
    'ANOTHER_VIEW_NAME' => array(
      array(
        'displays' => array(
          'page',
        ),
        'theme_suggestion' => 'views_view__another_custom_pages'
      ),
      array(
        'displays' => array(
          'block',
          'block_1',
          'block_2'
        ),
        'theme_suggestion' => 'views_view__another_custom_blocks'
      ),
    )
  );

  // use ONE template file for multiple views and displays.
  if (in_array($view->name, array_keys($shared_themes))) {
    foreach ($shared_themes[$view->name] as $key => $data) {
      if (in_array($view->current_display, $data['displays'])) {
        $vars['theme_hook_suggestion'] = $shared_themes[$view->name][$key]['theme_suggestion'];
      }
    }
  }
}

```

## Override or insert variables into the view template

Create common variables for your custom template using template\_preprocess\_views\_view()

```
function YOURTHEME_OR_MODULE_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {

    case 'SOME_VIEW_NAME' :
      // here get some field value from view and create a variable
      $vars['some_variable'] = 'some value';
    break;

    case 'ANOTHER_VIEW_NAME' :
      // here get some field value from view and create a variable
      // use the same names in order to use it by one template file.
      $vars['some_variable'] = 'some value for another view';
    break;

  }
}

```

*Notice: It is the same hook as mentioned in the `coding solution`.*

# Answer
> 1 votes
You probably can use a theme for that

Use hook\_theme() in your custom module and call the `theme()` function directly in your view's .tpl file

With hook\_theme() your can pass arguments to an other `.tpl.php` file

It's probably lighter to have 8 .tpl.php files associated to hook\_theme() than severals view's .tpl suggestions

An example of use of hook\_theme()

```
/**
 * Implements hook_theme().
 */
function yourmodule_theme($existing, $type, $theme, $path) {

return array(

  'my_theme' => array(
      'template' => 'your_theme_file', //your_theme_file.tpl.php in fact
      'variables' => array(
        'your_variable' => array(),
      )
  ),
}

```

Your `your_theme_file.tpl.php` file contains :

```
<?php

print '<div>'. $your_variable .'</div>

```

You can use this theme everywhere even in your views templates :

```
theme('my_theme', array('your_variable' => 'foo'));

```

# Answer
> 1 votes
Pretty quick and dirty way would be to simply have one file under multiple names. Main filesystems for Linux, and NTFS in Windows support both soft and hard links. Only this kind of link is called Junction in Windows. When you do that, Drupal will see these as separate files, but you will be able to edit them as one.

# Answer
> 1 votes
You probably can use a theme for that

Use hook\_theme() in your custom module and call the theme() function directly in your view's .tpl file

With hook\_theme() your can pass arguments to an other .tpl.php file

It's probably lighter to have 8 .tpl.php files associated to hook\_theme() than severals view's .tpl suggestions

An example of use of hook\_theme()

```
function yourmodule_theme($existing, $type, $theme, $path) {

return array(

   'my_theme' => array(
   'template' => 'your_theme_file', //your_theme_file.tpl.php in fact
   'variables' => array(
   'your_variable' => array(),
  )
  ),
}

```

Your your\_theme\_file.tpl.php file contains :

```
print '<div>'. $your_variable .'</div>

```

You can use this theme everywhere even in your views templates :

```
theme('my_theme', array('your_variable' => 'foo'));

```

---
Tags: views
---


# Question
Title: Does the language filter show all languages by default?
I'm looking at a Drupal 6 site with the following modules installed, all of which I think are contributing to translation:

* Internationalization
* Locale
* Content Translation

As I am not experienced with site translation I'm not sure which module is contributing to this, but the "Language Switcher" block shows both English and French for all content, regardless of the language choice assigned in the node, or if there are any translations present.

It is claimed that previously, if there was only an English translation for the node, then only English would be available from the language switcher block. However, if I add a new node, with just an English translation, I can still select French, which, because there is no translated node, takes the user to the internal node path, e.g. instead of:

`/en/mycontent/foo`

it would be

`/fr/node/232`

which of course, breaks contexts and what-not.

So what module does the language switcher block get provided by in this case and should it always show both languages?

# Answer
"Switch Language" block created by "Locale" module which is the most fundamental language handler in drupal. Its purpose it to switch user interface between languages. If translation exists for certain node it will used if not, only interface changes.

"Content Translation" module handles relations and links between translated nodes. The link you need is something like the language link/s that, by default, displayed inside node's links area.

I am not aware of existing module that display these node links in block. But you can display this list using code.

First, get can get an array needed links using translation\_link() that supplied by "Content Translation" module

```
$node_translations = translation_link('node', $node_object);

```

Than, create HTML list out of that array, using theme\_links(),

```
print theme('links', $node_translations, $attributes = array('class' => 'links langs more-classes-if-you-wish'));

```

To display this in block you can create new custom block with php input format or create template file for that block and make your code live there. To get node object in block you can use

```
  if (arg(0) == 'node' && is_numeric(arg(1))) {
   $node_object = node_load(arg(1));
  }

```
> 1 votes

---
Tags: 6, i18n-l10n
---


# Question
Title: Permission to create new users but not to manage them
I need to create a permission that allows any user to create other users without allowing them to manage all users (ie without granting them 'administer users' permission).

My approach was altering menu 'admin/people/create' but it - for unknown reason - doesn't work. Even though the permission for the menu is granted the menu item with link for is invisible and when I go to the specific url it - if I don't have 'administer users' permission - just redirects me to current user profile page.

```
    /**
 * Implements hook_menu_alter().
 */
function fm_users_more_menu_alter(&$items) {
  $add_new_user = &$items['admin/people/create'];

  unset($add_new_user['access callback']);
  unset($add_new_user['access arguments']);

  $add_new_user['access callback'] = 'fmu_add_user_access_callback';
  $add_new_user['access arguments'] = array(1);
}

/**
 * Callback that manages access to create user page.
 */
function fmu_add_user_access_callback($arguement) {
  dsm('test23');
  return true;
}

```

It does the same - redirects you to current user profile page - with User register form.

```
  $register_new_user = &$items['user/register'];

  unset($register_new_user['access callback']);
  $register_new_user['access callback'] = 'fmu_register_user_access_callback';

/**
 * Callback that manages access to create user page.
 */
function fmu_register_user_access_callback() {
  dsm('test23');
  if (user_register_access() || user_access('create users under self')) {
    return true;
  }
  else {
    return false;
  }
}

```

# Answer
> 0 votes
I've found out where the problem was, inside user register form there's this piece of code that - if a user is logged in but is not a administrator - redirects you to your profile page.

```
  // If we aren't admin but already logged on, go to the user page instead.
  if (!$admin && $user->uid) {
    drupal_goto('user/' . $user->uid);
  }

```

More information can be found here: https://api.drupal.org/api/drupal/modules!user!user.module/function/user\_register\_form/7

# Answer
> 1 votes
Don't forget to also give those same users the permission to `access administration pages` -- otherwise they'll be denied anytime they try to access any URI beginning with `admin`.

Also, I don't think it's necessary (or even desirable) to unset the menu items like that... You should just be able to do this:

```
function fm_users_more_menu_alter(&$items) {
  $items['admin/people/create']['access callback'] = 'fmu_add_user_access_callback';
  $items['admin/people/create']['access arguments'] = array(1);
}

```

Finally, remember to rebuild the menus after making such a change.

---
Tags: 7, users
---


# Question
Title: CMS Vs Framework? Is Drupal A CMS, Framework, or CMF (Content Management Framework)?
After Reading a Blog post: http://www.palantir.net/blog/drupal-not-cms It made me curious about the current classification as CMS Vs Framework.

Please use Facts, where possible to justify your response.

**CMS**

A Content Management System (CMS)is a computer program that allows publishing, editing and modifying content as well as maintenance from a central interface. Such systems of content management provide procedures to manage workflow in a collaborative environment. These procedures can be manual steps or an automated cascade. CMSs have been available since the late 1990s. CMSs are often used to run websites containing blogs, news, and shopping. Many corporate and marketing websites use CMSs. CMSs typically aim to avoid the need for hand coding, but may support it for specific elements or entire pages. Source: http://en.wikipedia.org/wiki/Content\_management\_system

Web Application Framework:

A web application framework (WAF) is a software framework that is designed to support the development of dynamic websites, web applications, web services and web resources. The framework aims to alleviate the overhead associated with common activities performed in web development. For example, many frameworks provide libraries for database access, templating frameworks and session management, and they often promote code reuse.

Source: http://en.wikipedia.org/wiki/Web\_application\_framework

If you would not consider Drupal 7 a Framework, do you think Drupal 8 would be?

# Answer
> 4 votes
Drupal is Content Management Framework (for Developers) as well as Content Management System (for Non-Programmers).

Drupal is a `highly configurable open source` and an `application development framework` providing the following features:

* Drupal provides the structure for Web applications which is far more complex than a CMS such as:
    + Extend the functionality (using contributed or custom code).
    + Communicate with other Web applications.
    + Run applications written in PHP and other languages behind the scenes.
    + Provide responsive pages or integrate front-end languages.
    + Scale to handle large traffic numbers by making use of server technologies and provide the foundation for other as yet unthought of innovations.
* Drupal is one of the most highly extensible frameworks available, and has the built-in ability to grow with your organization. Drupal was built from the ground up with a uniquely sophisticated granular level control system that provides unparalleled extensibility. With its vast feature-rich capabilities and growing community you’ll never outgrow Drupal.
* Pre-made functionality in Drupal can be overridden through hooks, or you can find workarounds that Do Not require modifying other modules.
* Drupal maintains a vigilant security community, providing security release updates on an ongoing basis to achieve maximum site security, which is one of the reasons even the U.S. Government and governments around the world use Drupal.
* Drupal's modular architecture allows complex solutions to be "assembled" quickly and reliably. Over Fifteen thousand modules are available for Drupal.

---

CMS (Content Management System) features of Drupal:

* Drupal comes with many tools to help you organize, structure, find and re-use your content. Categorize with taxonomy, automatically create friendly path urls, create custom lists, associate content with other content on your site, and create smart defaults for content creators.
* Manage content with an easy-to-use web interface. Drupal's flexibility handles countless content types including video, text, blog, podcasts, and polls with robust user management, menu handling, real-time statistics and optional revision control.
* Drupal comes with great options for new user accounts and user permissions. Users can be assigned one or more roles, and each role can be set up with fine-grained permissions allowing users view and create only what the administrator permits. The Drupal 7 admin theme makes administering a site easier than ever.
* Drupal's focus on social publishing can help you create sites and applications to help your users express their opinions and engage with one another. You can have tight control over who can create, view, administer, publish and otherwise interact with content on your site.
* Drupal's presentation layer allows designers to create highly usable, interactive experiences that engage users and increase traffic. Use an existing Drupal theme for your site, giving it an instant identity! If you can't find one you like, try designing your own which others can use, too.

# Answer
> 2 votes
My personal answer to this is: Drupal is a CMS based upon a Framework. The framework is certainly not Symfony as Drupal just levarages the components of symfony but not use symfony fullstack.

In general though Drupal will still provide a lot of functionality out of the box, while a framework lets you do things fast from the ground up.

---
Tags: 8
---


# Question
Title: how to display a list of OG content depending on user group membership?
I've set up an OG Group type, and and OG Content type where I want to store some kind of articles. I've provided fields where the author of an article can specify if an article can be:
1. read by anyone, even unauthenticated users.
2. read by all authenticated users, wheter or not they belong to a group to which the article is linked
3. read only by users that belong to a group to which the article is linked.
I understand this has something to do with filters and relationships, but I can't get it to work....
Please help.... :-)

# Answer
> 0 votes
There is a pretty good tutorial of OG at https://drupal.org/node/1603460.

If you already know the basics and have provided proper access fields using the Organic groups access control module, you should next explore the views that come with OG and edit them to your liking.

Also the OG Extras module at https://drupal.org/project/og\_extras has lots of stuff for practical use.

---
Tags: organic-groups
---


title: Render a region in a panel

text:
# Question
Title: Render a region in a panel
What I want to do is to render a region in a panel -\> add content -\> new custom content. I tried `<?php print render($page['region_name']); ?>` but it didn't work.

I'm using panels to be able to create more complex layouts and the Context module to show blocks (with menus) on different pages. Thats why I need to render a region in a panel: to put menus on selected pages.

# Answer
This code is not to supposed to work inside panels. Regions are what you add to your themes and they are ready to use on your theme templates.Panels are used to override your theme templates, its allows to have regions as per the panel layout you choose.$page will not be available to your panels. Using new custom content you can add plain text,html,php but regions will be available here.
> 2 votes

---
Tags: panels, theming
---


# Question
Title: How to disable webform select box with jQuery without resetting selection value to default
I have a webform, below's a section of the form (the selection field)

```
<select id="edit-submitted-bring-alcohol" name="submitted[bring-alcohol]" class="form-select">
    <option value="yes" selected="selected">Yes</option>
    <option value="no">No</option>
</select>

```

I now use jquery to dynamically setup this field.

```
if (age < 19) {
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').prop('disabled', true);
}

```

This works great. When user entered their age, this method automatically change the selection to 'no' (if they are under 19), and disabled by itself. However, the problem I have now is that **the submitted value I received is 'yes' when the selection field is disabled (apparently it chooses the default value).**

So could anyone help me out?

# Answer
> 2 votes
You can do this by removing the 'selected' attribute first, and setting the new selected attribute, prior to disabling.

e.g:

```
if (age < 19) {
    $("#edit-submitted-bring-alcohol option:selected").removeAttr('selected');
    $("#edit-submitted-bring-alcohol option[value='no']").attr('selected', 'selected')
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').prop('disabled', true);
}

```

Here's a jsfiddle link for tinkering: http://jsfiddle.net/AwUwt/

Edit: Alternatively, you can just hide the select box

```
if (age < 19) {
    $("#edit-submitted-bring-alcohol option:selected").removeAttr('selected');
    $("#edit-submitted-bring-alcohol option[value='no']").attr('selected', 'selected')
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').css('display', 'none');
}

```

---
Tags: 7, webforms, javascript
---


# Question
Title: Does a module for real-time data plotting exist?
There are several Drupal modules that allow to plot /chart data stored in database tables. Is there any module that can chart or plot data in real-time? For a specific example, I have a mobile application that is reading sensor data (say from an accelerometer) and sends that to the Drupal server. I want to plot the data as and when updated in real-time or near real-time. Does any specific module that can do this exist?

# Answer
Google Chart Tools

> Display live data on your site using Google Chart Tools Google Chart Tools module provides a simple API to Build custom interactive SVG charts.
>
> **Views integration**
>
> The Google Chart Tools Views module is based on the Views built in aggregation function. For basic instructions of using the Views integration module check the README.txt file

**or**

Quant provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.

> Quant API (**easily provide your own charts**)
>
> The real power of Quant lies in it's ability to generate these charts with very little provided information. Quant offers a simple, yet flexible API to allow developers to include quant charts with their modules.
> 3 votes

---
Tags: views, charts
---


title: Custom views, css syntax

text:
# Question
Title: Custom views, css syntax
I need some help to customize my events list with Drupal 7. I am a newbie to Drupal, css and php, but I am used to programming. I guess I need some help with css syntax here. What I want is an event list from an event calendar with customized format of the titles, which link to the respective event. I got to the point where I can tell the Views structure in Drupal that I want a customized html format for that field and where I can enter a name for a new css class. Now I take it, that I can edit the theme's css file to format the titles. Embarrassingly, I don't get the code right, my experience with css is not sufficient. Can someone help me, please?

I entered "pretty-event-title" as new css class, the resulting page's source code looks like this:

```
<div class="views-field views-field-title"> <span class="field-content pretty-event-title"><a href="/node/27">Test event</a></span> </div>]

```

"Test event" shows up as blue link of 100% font size. I'd like to change size and especially the color (size was just fine by using h3 tags or something in the view).

How would the css snippet look I have to put into my css file?

Any help appreciated! Best, Verena

# Answer
> 1 votes
You can add something like this to your theme style.css file

```
.pretty-event-title a{
  font-size: 14px;
  color: red;
}

```

More info: http://www.w3schools.com/css/

# Answer
> 0 votes
Use firebug or chrome/safari code inspector to see what css is being applied to elements, including browser defaults. Also helps when learning to see the form your css should take.

---
Tags: views, theming
---


title: Upload text file without extension

text:
# Question
Title: Upload text file without extension
I am working in a project where I have to upload files thru a Drupal site. I am having an issue since the files I am trying to upload have not extension. The files are text files, but without the .txt at the end and to be honest I don't mind if Drupal add .txt after the file name.

How do I define a file validator for files without extensions?

# Answer
To be sure you are uploading text files, just without extension, you need two steps:

1. Omit extension validation. You don't want to simply only allow empty extension, as you may have a dot inside legitimate filename. Code would be like:

```
$validators = array('file_validate_extensions' => array());

```

Hint: It's easier to use `#upload_validators` on `managed_file` element when you are using Drupal 7, than to use `file` element and `file_save_upload`.
2. Test if what you got is really a text file. Linux-based hosts are pretty good at it. Code needed in your validator will look like:

```
$file_handler = file_load($file_name);
if(is_null($file_handler) or empty($file_handler->filemime)) {
  // output message like 'Could not validate file type. Please contact site administraotrs.'
}
$mimetype = $file_handler->filemime;
if($mimetype != 'text/plain') {
  // set error
}

```
> 0 votes

# Answer
I found out that leaving the extension with an space instead of empty work, but I wonder how secure it this solution. In my case I remove the file a second after I upload it as I am only interested on its content.

Here is the code that worked for me:

```
$validators = array('file_validate_extensions' => array(' '));
$file = file_save_upload($i, $validators);

```

Thank you.
> 1 votes

# Answer
Allow All File Extensions you can try this module and I'm not tested it.

> lengthens the allowed file extensions box from 128 characters to 2048, allowing you to specify a larger number of extensions.
> 0 votes

---
Tags: 7, files
---


title: Link "My Workbench" no longer visible

text:
# Question
Title: Link "My Workbench" no longer visible
I've always used the Workbench and the Workbench Moderation modules, but recently, the link "My Workbench" in the admin menu has disappeared...

I tried reinstalling the module several times, but no luck there. And all the permissions are checked and double checked, so nothing wrong there.

What else could be the issue?

# Answer
> 1 votes
In order to have it appear in the admin menu. You need to give access to:

"Use the administration pages and help"

Because the My Workbench link is child of admin: /admin/workbench

---
Tags: 7, workbench
---


title: Parent-child facets

text:
# Question
Title: Parent-child facets
I am using facets and I want to have one facet with Parent term and when clicking on one parent term,another facet to appear with the children of the clicked taxonomy term.How is this possible to do?thanks

# Answer
You could do this with your own widget. Making it collapsible. You would need use some Jquery. and facet api.

Together with

Taxonomy Sort

> Add the ability to sort taxonomy facets by their term weight. Essentially takes the code from http://drupal.org/node/1361284 and implements as a standalone module.

Then creating your own widget, you could customize it even more.

```
/**
* Implements hook_facetapi_widgets()
*/
function example_facetapi_widgets() {
  return array(
    'example_select' => array(
      'handler' => array(
        'label' => t('Select List'),
        'class' => 'ExampleFacetapiWidgetSelect',
        'query types' => array('term', 'date'),
      ),
    ),
  );
}
?>

```

and also look into

```
/**
* Implements hook_facetapi_sort_info().
*/
function example_facetapi_sort_info() {
  $sorts = array();
  $sorts['random'] = array(
    'label' => t('Random'),
    'callback' => 'example_facetapi_sort_random',
    'description' => t('Random sorting.'),
    'weight' => -50,
  );

  return $sorts;
}

/**
* Sort randomly.
*/
function example_facetapi_sort_random(array $a, array $b) {
  return rand(-1, 1);
}
?>

```
> 1 votes

---
Tags: search
---


# Question
Title: Link “My Workbench” is no longer visible
I have installed Workbench and the Workbench Moderation modules, but My Workbench(on top with other Administration Menu) link is coming only for when user logged in as Administrator, it is not visible for user with Editor role. I have given following permissions to Editor Workbench

```
Administer Workbench settings

For Editor:
Administer Workbench settings - Yes
Access My Workbench - Yes

```

# Answer
I posted an answer on this question: Link "My Workbench" no longer visible

In order to have it appear in the admin menu. You need to give access to:

"Use the administration pages and help"

Because the My Workbench link is child of admin: /admin/workbench
> 2 votes

---
Tags: 7, workbench
---


title: Gateway timeout error from proxy server

text:
# Question
Title: Gateway timeout error from proxy server
I was recently developed a drupal site for a client who lives in HongKong. The site worked perfectly (is still functional when I access it) But after deploying it for demo, the client compalained that the site wasnt working and constantly getting a 504 Gateway timeout error. Apparently the client was on a proxy server (and I'm guessing the problem is due to that factor). Does anyone know of such problem?? And, of course, the way to fix it?

P.S.

The site is built on Drupal 7.14

This is a screenshot that the client sent me

(The server, while acting as a gateway or a proxy, did not receive a time response from the upstream server it accessed in attempting to complete the request)

Update::

On further investigating with the client, He told me that

* The site first worked fine until he logged in as admin and added content.
* The timeout error showed when submitting the content form.
* After the error, no other page of the site would open.
* The site did function when he tried after waiting for a while (he did not account the time he waited)

UPDATE ::

ON checking the error log on the server, I found a bunch of "Page not found errors". But the weird thing is it was looking for a 406 page (for unacceptable header). Any idea why??

```
[Mon Sep 30 16:45:30 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/404.shtml
[Mon Sep 30 16:45:30 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/favicon.ico
[Mon Sep 30 16:45:29 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/404.shtml
[Mon Sep 30 16:45:29 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/demo
[Mon Sep 30 16:31:17 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/406.shtml, referer: http://ekmauka.com/ekmauka/
[Mon Sep 30 16:20:40 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/406.shtml, referer: http://ekmauka.com/ekmauka/content/mongolian-heart-live-hongkong-2012
[Mon Sep 30 16:20:13 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/406.shtml, referer: http://ekmauka.com/ekmauka/node/22/edit

```

# Answer
> 1 votes
Maybe the PHP memory\_limit, after submit content it take a lot of memory for PHP and it die.

You can request they increase memory\_limit to check. But to get more information correct, can they give the error.log of webserver and error\_log of PHP for easy know what happend.

---
Tags: proxies
---


# Question
Title: How can I integrate the job news API into my site to access data through the API?
I want to integrate the API of job news to display news of different companies. I need to let my system access the data through the API.

How can I integrate it with my website? Can anyone help me by telling me a way or giving some idea for the integration process?

# Answer
With Feeds module you can import data from other sources to your Drupal installation. I would create a new content type for the jobs, and import the data with Feeds module into this newly created content type.
> 1 votes

---
Tags: database
---


# Question
Title: The return property of exclamation in front of array
I am learning the drupal 7 by the example module. In the render\_example, I don't understand the usage of the exclamation mark (!) in front of the !array and !alter.

I am sure that it is not related to the "boolean" nor "negation". Please kindly advise how can I find the detail of the usage.

```
function render_example_info() {
  return t('The render example provides a <ul><li><a href="!arrays">demonstration of of render array usage</a></li><li><a href="!alter">using hook_page_alter()</a> to make various changes on a page.</li></ul>', array('!arrays' => url('examples/render_example/arrays'), '!alter' => url('examples/render_example/altering')));

```

}

When I edit the "!array" to "$array",

```
function render_example_info() {
return t('The render example provides a <ul><li><a href="$arrays">demonstration of of render array usage</a></li><li><a href="!alter">using hook_page_alter()</a> to make various changes on a page.</li></ul>', array('$arrays' => url('examples/render_example/arrays'), '!alter' => url('examples/render_example/altering')));

```

}

the message was changed
from:
demonstration of of render array usage
(with hyper link "http://www.example.com/drupal/?q=examples/render\_example/arrays"
to:
/drupal/?q=examples/render\_example/arrays"\>demonstration of of render array usage
(with hyper link "http://www.example.com/drupal/&5cem&nbspclass=" )

# Answer
> 1 votes
t() uses format\_string(), which uses strtr(). For this reason, your second example snippet works. Since `format_str()` is using the following code, any token that starts with a character different from *!*, *%*, or *@* is treated as if the token started with *%*.

```
  foreach ($args as $key => $value) {
    switch ($key[0]) {
      case '@':
        // Escaped only.
        $args[$key] = check_plain($value);
        break;

      case '%':
      default:
        // Escaped and placeholder.
        $args[$key] = drupal_placeholder($value);
        break;

      case '!':
        // Pass-through.
    }
  }

```

drupa\_placeholder() is the responsible for escaping some characters, since it calls check\_plain().

```
function drupal_placeholder($text) {
  return '<em class="placeholder">' . check_plain($text) . '</em>';
}

```

As side note, since `$arrays` is inside a single-quote string, PHP doesn't replace it with the value of the `$arrays` string. If you wanted to put the content of a string into the string passed to `t()`, you should use a `t()`-placeholder, which starts with *!*, *%*, or *@*.

---
Tags: theming
---


# Question
Title: Search block not showing if not logged in
When I am logged in I can see the the search form block, however when logged out I can not see it, I'm guessing its some sort of user config, but I can't seem to find anything

# Answer
> You have to go to the `Administer › User management` section, under the search module area, you need to give the necessary permission to the user that needs to see the search form. If you want everyone to view this `Search Module` check the box corresponding to `anonymous` and `authenticated` users.

From https://stackoverflow.com/a/17027332/1795426
> 2 votes

---
Tags: search, configuration
---


title: Search and wildcard

text:
# Question
Title: Search and wildcard
Is there any simple way to provide searching with a wildcard using the Drupal core search engine?

I know it's possible with Apache Solr, but I'm looking for something very easy to implement.

I need to use it on i18n site.

# Answer
The closest module I have found for doing this is the porter stemmer module.

> This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.
> 1 votes

---
Tags: search
---


# Question
Title: How to check that cache is working on current page?
Some modules silently turn off caching on certain pages. How is the easiest way to check that this is the case and also identify problematic module?

# Answer
The easiest way is probably to inspect the HTTP response headers.

For example, with your browser DOM inspector tool ( e.g Chrome's "Network" tab )

**Cache Miss**

Here's some sample response headers from drupal.org showing a cache miss. In this case, using Varnish however core Drupal cache also sets similar headers.

**Cache Hit**

Here's one showing a standard Drupal cache hit:
> 13 votes

# Answer
## Adding cache headers to Drupal 6 default cache

Sadly, it's involving some core hacking.

In file `includes/bootstrap.inc` change lines from

```
      // If there is a cached page, display it.
      if ($cache) {
        drupal_page_cache_header($cache);
        // If the skipping of the bootstrap hooks is not enforced, call hook_exit.
        if ($cache_mode != CACHE_AGGRESSIVE) {
          bootstrap_invoke_all('exit');
        }
        // We are done.
        exit;
      }
      // Prepare for non-cached page workflow.
      drupal_page_header();
      break;

```

to

```
      // If there is a cached page, display it.
      if ($cache) {
        header('X-Drupal-Cache: HIT');
        drupal_page_cache_header($cache);
        // If the skipping of the bootstrap hooks is not enforced, call hook_exit.
        if ($cache_mode != CACHE_AGGRESSIVE) {
          bootstrap_invoke_all('exit');
        }
        // We are done.
        exit;
      }
      // Prepare for non-cached page workflow.
      header('X-Drupal-Cache: MISS');
      drupal_page_header();
      break;

```

and the rest of instructions it's exactly as in David's answer.
> 0 votes

---
Tags: caching
---