# Question
Title: Join a select form with the number of the database to check
I have this select form:

```
$options = array(
      'twenty' => '20',
      'hundred' => '100',
      'five_hundred' => '500',
      'thousand' => '1.000',
      'five_thousand' => '5.000',
      'ten_thousand' => '10.000',
      'hudred_thousand' => '100.000',
      'million' => '1.000.000',
      'two-million' => '2.000.000',
  );

  $form['number_select'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#description' => t('Select the number of values that you want to check.'),
  );

```

I want according to what number the user has selected to limit the same number how i can solve this problem?

my DB code is this:

```
function something_cron()

  $number = variable_get(number_select)
  $query = db_select('watchdog', 'wa')
    ->orderBy('wid')
    ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
    ->condition('wid', $last_id, '>')
    ->range(0,$number);
  $result = $query->execute();

  // Loop through each item and add to $row.
  foreach ($result as $row) {
    someother();
  }

```

# Answer
> 0 votes
Change your options to this:

```
$options = array(
      '20' => '20',
      '100' => '100',
      '500' => '500',
      '1000' => '1.000',
...
  );

```

Then you can use the value directly. It'll be a number. Also you need a #default\_value:

```
#default_value => variable_get('number_select', '20')

```

---
Tags: forms
---


title: Show current date in a view title

text:
# Question
Title: Show current date in a view title
Is there a way to insert a PHP date into a title of a view block like so?

Thanks!

# Answer
> 1 votes
I'm not sure if this solution works and I'm not able to test it right bow, but download and install views\_php module. it allows you to add a field which is fill by any php code. so in your views you must select `fields` instead of `content`. search for `php` then you can add this field. in this field try

```
drupal_set_title('TITLE');

```

if this works then you can put your php code there. If not you must modify the template file.

---
Tags: views
---


title: Alter value of field before loading

text:
# Question
Title: Alter value of field before loading
I'm just wondering if its possible to alter a field before loading.

Here is the situation.

Im using commerce kickstart.

When I'm in a product page(inner page or product details page), I want to change the value of **field\_my\_field** before it load up to the page.

In pseudocode: If **field\_my\_field** == "something" change **field\_my\_field** to "my custom value"

# Answer
> 0 votes
It is very easy! where do you want to display the field?

If it is a view, then you can use `template_preprocess_views_view` if it is a node, you can use `hook_preprocess_node` function to alter the values. where your content is going to be displayed?

---
Tags: entities
---


# Question
Title: How can I remove content from the front page?
Made page--front.tpl.php. Created the view for content-type: news for example. Then put the view block in a block region. View block - only display news type limit at 1 or 2.

But when viewing the front page, all content types' content shows up on the front page along with the view block. I checked that it was managed by Display Suite but it shouldn't show show all contents on front page.

Why does this happen?

**Update**

Uncheck "promoted to front page" checkbox on all entries and it worked.

Other question:

"No front page content has been created yet. Add new content"

How can I remove this text above on front page? I am using blocks most of the time, so text shouldn't be there.

# Answer
It sounds like you have your content type to "Publish to front page". Edit your content and un-check "Promote to front page":
> 1 votes

# Answer
If you're trying to remove the feature that automatically adds all your content to the front page, you'll need to go to `Configuration -> Site Information -> Front Page` and set an individual piece of content to be displayed as your front page ie.. `node/xx`
> 0 votes

# Answer
If you want to display very specific contents on front page, then you shouldn't write

```
print render($page['content']);

```

in the front page. remove this code. If it is not there, then update your question and put the `page--front.tpl.php` code in the question.
> 0 votes

# Answer
This what I do on most of my project. I used the Empty Front Page module and this would give me a blank front page. From here I can organize anything into blocks. If you wish to have a the latest new or blog you can created a block view and add it to the front page.
> 0 votes

---
Tags: theming
---


# Question
Title: Missing my custom ajax field values by image field in node form alter
I have created new content type and added two taxonomy reference field (select list) both referenced to same vocabulary "car" and one Image field with cardinality = 6,

In car vocabulary listed brands and models like:

```
Brand 1
- model 1
- model 2
- model 3
...
Brand 2
- model 1
- model 2
....

```

In my content type, first reference select list depth setting is 1, so displays only brands, In Second reference select list (Models) content\_taxonomy\_opt\_groups =\> 1,

I have created simple module, for altering on node form and creating custom ajax on Brands and Models select list,

When select a brand, models field displays only models of selected brand...

My ajax has worked

Problem is: when upload an image (Ajax upload) and click Publish this error is shown:

**An illegal choice has been detected. Please contact the site administrator.**

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function car_info_form_car_info_node_form_alter(&$form, &$form_state, $form_id) {
  $brand_options  = $form['car_brand'][LANGUAGE_NONE]['#options'];
  $selected_brand = isset($form_state['values']['car_brand']) ? $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] : key($brand_options);

  $form['car_brand'][LANGUAGE_NONE]['#default_value'] = $selected_brand;
  $form['car_brand'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'car_info_dependent_model_callback',
    'wrapper' => 'dropdown-model-replace',
    'effect' => 'fade',
  );

  $form['car_model'][LANGUAGE_NONE]['#prefix'] = '<div id="dropdown-model-replace">';
  $form['car_model'][LANGUAGE_NONE]['#suffix'] = '</div>';

  if ($selected_brand > 0) {
    $model_options  = _car_info_get_model_dropdown_options($selected_brand);
    $selected_model = isset($form_state['values']['car_model']) ? $form_state['values']['car_model'][LANGUAGE_NONE][0]['tid'] : key($model_options);
    $form['car_model'][LANGUAGE_NONE]['#options'] = $model_options;
    $form['car_model'][LANGUAGE_NONE]['#default_value'] = $selected_model;
  }
  else {
    // Remove default options (All models of brands) if brand not selected
    $form['car_model'][LANGUAGE_NONE]['#options'] = _car_info_get_model_dropdown_options('');
  }

  // $form['#validate'][] = 'car_info_form_car_info_node_form_validate';
}

function car_info_dependent_model_callback($form, $form_state) {
  return $form['car_model'];
}

function _car_info_get_model_dropdown_options($brand_id) {
  if (isset($brand_id)) {
    $car_models_tree = taxonomy_get_children($brand_id);

    $models[''] = t('Select model');
    foreach ($car_models_tree as $model) {
      $models[$model->tid] = $model->name;
    }
  }
  else {
    $models[''] = t('First select brand');
  }

  return $models;
}

function car_info_form_car_info_node_form_validate($form, &$form_state) {
  $car_brand = $form_state['input']['car_brand'][LANGUAGE_NONE];
  $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] = $car_brand;
}

```

If I dont add image or add image without click on upload button (upload handled when clicked on publish directly) in both way my form is submitted correctly

But if click upload button in image field (Upload handled by ajax), this issue is happened and $form\_state\['values'\]\['car\_brand'\] is empty when using ajax image upload.

# Answer
In your form an AJAX call is made when your car\_brand element is changed but also when upload image button is clicked. Your problem is the AJAX call that is made when upload button is clicked. In that call car\_info\_form\_car\_info\_node\_form\_alter() is called, and probably is modifying the allowed options array for the model select element in a wrong way.

In your form altering function check for the element that fired the AJAX call modifying the select element options only when your first select (brands). You can check for that element in the $form\_state\['triggering\_element'\].
> 0 votes

---
Tags: nodes, taxonomy-terms, ajax, forms
---


title: how to Search profile type in drupal 7

text:
# Question
Title: how to Search profile type in drupal 7
I created a profile type for users to upload their data using fields and I want other users (registered or anonymous) to have access to a search form and they can search for anything on any user's profile (name, jobtype, gender, etc)

if a another user searches for a string in job search, the entire information should be accessible?

# Answer
> 0 votes
I have an idea. This can be done by "Webform". Use a form as user profile, and set limit 1 form per user in "Form settings". Then use "Permission per webform" to make this form access webform results for all user. To display in search, it can simply be done by Views.

---

Update: another idea I found is to use "View profiles permissions". This module provides permission to view user profiles depending on what roles the profile requested to be viewed.

---
Tags: users
---


title: How do I schedule a post in Drupal?

text:
# Question
Title: How do I schedule a post in Drupal?
I was just wondering how one should go about scheduling a post in Drupal so that it posts at a point in time later then when you are posting? Is it as simple as changing the post time on the author information to a future point in time or is it more difficult then that?

# Answer
Yes as simple as changing the post time at the point time that you would like to released that post
> 1 votes

# Answer
If you want to post a page or article during a particular period of time. You can use the "Scheduler" module. This module allows nodes to be published and unpublished on specified dates. Very useful!
> 0 votes

---
Tags: nodes
---


# Question
Title: Getting terms for only one taxonomy from services module
I have the services module installed, and I have both `taxonomy_term` and `taxonomy_vocabulary` checked. However I'm having problems getting just the terms for one vocabulary. when I do `curl -g "http://domain.com/endpoint/taxonomy_term?args[0]=machine_name_of_vocabulary"` or `curl -g "http://domain.com/endpoint/taxonomy_term?args[0]=2"`

I get an xml result like this:

```
<result>
  <item>
    <tid>2</tid>
    <vid>2</vid>
    <name>Blue</name>
    <description/>
    <format>filtered_html</format>
    <weight>0</weight>
  </item>
  <item>
    <tid>1</tid>
    <vid>5</vid>
    <name>Apple</name>
    <description/>
    <format>filtered_html</format>
    <weight>0</weight>
  </item>
</result>

```

which is the terms of all the vocabularies. In other words, I have the argument wrong, or the request wrong, or something else wrong.

How do I configure services and make a request to it to get only one vocabulary?

# Answer
I was working on exactly the same thing the other day, the format is like this:

```
http://domain.com/endpoint/taxonomy_term?parameters[vid]=2

```

To explain that a bit further...

If you look at the code in `_taxonomy_resource_definition()` the *index* resource defines a few arguments:

* page (int)
* fields (string)
* parameters (array)
* pagesize (int)

The way to pass any of those is:

```
http://domain.com/endpoint/taxonomy_term?arg_name=value

```

Since `parameters` is an array you need to format it as if it was an associative array in the URL, so you use (e.g.) `parameters[vid]=2`.

It will also work for other parameters, e.g. `parameters[name]=TermName`.
> 9 votes

# Answer
For Services 3.x on Drupal7, this also works:

```
curl -i -X POST \
 -H Cookie:SESSabcdefg12345baadbeef=ovQpBase62SessionIdHere_45AUSJ \
 -H X-CSRF-Token:v6j7r9RactujAHY-mYYZa \
 -H Accept:application/json \
 -H content-type:application/json \
 'http://services.example.com/rest/taxonomy_vocabulary/getTree' \
 -d '{ "vid" :"1" }'

```

Why?

Not sure. Not sure why they duplicated the capability. Also not sure why this is a POST. Someone on a drupal board said that it is because retrieving these things is "an action" and "actions" need to be done with POST. It didn't make sense to me. It looks like a query, not an action. But whatever.

But I like the other answer better.
> 0 votes

---
Tags: taxonomy-terms, services
---


# Question
Title: Drupal View of CiviMember troubleshooting
I've created a Drupal View of our current members in CiviMember

```
SELECT civicrm_contact.organization_name AS civicrm_contact_organization_name,    civicrm_website.url AS civicrm_website_url
FROM
{civicrm_membership} civicrm_membership
LEFT JOIN {civicrm_contact} civicrm_contact ON civicrm_membership.contact_id =  civicrm_contact.id
LEFT JOIN {civicrm_website} civicrm_website ON civicrm_contact.id = civicrm_website.contact_id
WHERE (( (civicrm_membership.status_id IN  ('4', '5', '6')) AND   (civicrm_contact.contact_type NOT IN  ('Individual', 'Household')) ))
ORDER BY civicrm_contact_organization_name ASC
LIMIT 50 OFFSET 0

```

But it keeps on returning duplicate results, sometimes 3 or 4 in a row and yet they're all single contact records with one current membership? Can anyone see where I've gone wrong?

# Answer
Is there nothing to give you a clue in the actual table of results? Eg are the duplicates ones that have multiple websites (since that field has not filtering in field for ' website type' afaik but you should be able to apply a Views Filter) That seems the most likely reason. If not, have you tried setting the Query Settings (under Advanced) to Disinct or Pure Distinct. If none of that helps, can you attach the view?
> 1 votes

---
Tags: views, civicrm
---


# Question
Title: How do I modify a menu link title dynamically?
This seems so simple, there -must- be a way, right?

I want to modify the title of a menu link dynamically. I've tried the techniques in this question:

Change menu link title dynamically?

...The last one ( using menu\_token() module) seemed promising, but that threw an error when I tried to apply it to the menu item in question.

I also tried the technique here: https://www.drupal.org/node/1538094

...but that only modifies the Page title... not the link of the -menu-.

So I tried the following code, which doesn't appear to do anything (although I am sure that the variable is being assigned.)

Any other ideas? I must be missing something -obvious-, right?

`function MY_THEME_preprocess_menu_link(&$variables) {
 if (isset($variables['element']['#original_link']['menu_name'])) {
 if($variables['element']['#original_link']['menu_name'] == 'secondary-navigation') {
 if($variables['element']['#title'] == 'Cart') {
 $new_title = 'Cart(4)' ;
 $variables['element']['#original_link']['link_title'] = $new_title;
 $variables['element']['#title'] = $new_title;`

````
    }

}

````

`}
}`

EDIT: I also tried this:

`function MYMODULE_menu_link_alter(&$item) {
 // add in an if statement here to just target the links you want to change on the fly
 $item['options']['alter'] = TRUE;
}`

`function MYMODULE_translated_menu_link_alter(&$item, $map) {
 if($item['mlid']==1166) {
 // the watchdog fires properly
 watchdog('test', '

```
' . print_r($item, 1) . '
```
');
$item['link_title'] = 'Cart(x)';
 $item['title'] = 'Cart(x)';
}
}`

...and the above did not work either.

This has gotta be something obvious, right?

# Answer
It looks like the other answer on that post you linked to is quite relevant. It references `hook_menu_alter()` as a tool to:

> ... add a title callback that will be called every time a link to the menu item will be rendered

However, I'm not sure if that solution would work for manually-created menu links items with custom title text. The other, possibly more universal, option that I can think of is using `hook_menu_link_alter()` along with `hook_translated_menu_link_alter()`. The former is used to "flag" a link as alterable (when the link is saved), and the latter is used to actually alter it (at render time).

Actually, it looks like this post covers both these options in even more detail, so I won't repeat any of their code samples here.

This distinction about which alter hooks fire at save/cache-clear time vs. render time is important as it often means that you have to leverage a hook + callback, or 2 hooks, to implement dynamic alterations. For example, if you choose the second option you use `hook_menu_link_alter()` to declare the link as alterable, and though that hook does not fire each time the link is rendered, it "registers" the fact that `hook_translated_menu_link_alter()` should in fact be called at render time for that specific link.
> 1 votes

---
Tags: routes
---


# Question
Title: How to organize webforms on (admin/content/webform) into groups
**Goal**: I want to be able to organize the list of webforms on the admin/content/webform page, which is in a View to my understanding, in groups. Either via visual groups (using some header or box) or add a filter to the page so that I can specifically look up a term ID that is associated with one or multiple webforms (like you can on the admin/content page).

So for example: if I had several webforms about housing, I would like to be able to create the header 'Housing' and have associated webforms underneath. Or be able to select the Vocab or TID associated with one or multiple webforms and filter the results.

I'm a very new user to Drupal (couple months experience on the job only). I've spent the last ~4 days searching the internet to find info to help me and have found some promising things but haven't gotten anything to work. Many things are over my head.

The best two things I've tried are the following:

**1)** I've tried editing the Webform View. I've tried adding a TID field but that's not listed as an option to add. My plan was to add a Contextual Filter for TIDs.

**2)** I've tried adding a Term Reference field and Node Reference field to a Webform. This seemed promising until I realized they became Select List options on the actual webform presented to the user. Obviously this will not do what I want to do on the developer side of things.

I've heard about creating custom admin pages with views but I was hoping for a simpler way to accomplish this. If that is the only way to do so, so be it.

I'm using Webforms 7.x-4.4 fyi.

Thanks for any help! Sorry this is long and probably newbish.

# Answer
> 0 votes
I solved my own question.

Ended up creating a new Administration View of type content for only webforms. I then added the field 'Content: Term Group' which I added to the Webform Content type which is a term reference. I should mention I already created a new Taxonomy Vocabulary and gave that vocabulary three children taxonomy terms. From then it was as simple as noticing that 'Term reference' showed up when I hit Edit on a specific Webform so I can select one of the taxonomies. Then I changed the Format Setting 'Grouping field Nr.1' to 'Term Group' and thats it! Now my custom link (/admin/content/webform-groups) page shows all the webforms separated into separate boxes with their respective Term ID name above.

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


# Question
Title: standalone rsync and ssh work, but drush gets me a "Permission denied (publickey)"
I've got a production site (on shared hosting for now) of which I just want to have backups at this stage. and I've got a backup instance which I want to overwrite with the prod site.

This is my /etc/drush/aliases.drushrc.php:

```
<?php
$aliases['bak'] = array(
        'root' => '/var/www/',
        'uri' => 'testvm',
        'db-url' => 'mysql://user:pass@localhost/drupal',
        'path-aliases' => array(
        '%dump' => '/var/bak.sql',
        '%files' => '/var/drupal_files',
      )
);

$aliases['prod'] = array(
        'root' => 'livesite.com:/home1/ruser/public_html/',
        'uri' => 'livesite.com',
        'db-url' => 'mysql://ruser:pass@localhost/drupal_drp3',
        'remote-user' => 'ruser',
        'path-aliases' => array(
        '%dump' => '/home1/ruser/prod.sql',
        '%files' => '/home1/ruser/drupal_files',
      )
);
?>

```

And all I'm getting through drush is:

```
Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]
rsync error: error in rsync protocol data stream (code 12) at io.c(605) [Receiver=3.0.9]
Could not rsync from livesite.com:/home1/ruser/public_html// to /var/www/        [error]

```

Even though I can rsync/ssh/scp with no issue to and from the live site. Certificates are in place, and working fine, but not for drush...

What I'm not seeing here???

PS I've seen What could cause remote drush commands to fail with ssh errors when ssh works in all other cases?, but the accepted answer does not make any difference for me.

**Update:**

I was using drush as root, so I tried creating a local user with same name as the remote user. I chowned the backup instance to the remote user.

```
ruser@drupal:~/.drush$ drush -v rsync @prod @bak
$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/ruser/.ssh/id_rsa';

Loaded alias @prod from file /etc/drush/aliases.drushrc.php [notice]

Loaded alias @bak from file /etc/drush/aliases.drushrc.php [notice]
You will destroy data from /var/www/ and replace with data from livesite.com:/home1/ruser/public_html//
Do you really want to continue? (y/n): y
Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --exclude="settings.php" --stats --progress livesite.com:/home1/ruser/public_html// /var/www/);
receiving incremental file list
rsync: failed to set permissions on "/var/www/.": Operation not permitted (1)
rsync: failed to set permissions on "/var/www/.htaccess": Operation not permitted (1)
./

Number of files: 14547
Number of files transferred: 0
Total file size: 92209263 bytes
Total transferred file size: 0 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 313420
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 1017
Total bytes received: 316801

sent 1017 bytes  received 316801 bytes  42375.73 bytes/sec
total size is 92209263  speedup is 290.13
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1536) [generator=3.0.9]
Could not rsync from livesite.com:/home1/ruser/public_html// to /var/www/ [error]
Command dispatch complete

```

This user has certificates in place in the live site as well. But still no luck...

# Answer
> 1 votes
You are not specifying a `remote-user` on `@bak` so who are you performing operations as on the server at @bak? You are also not specifying any ssh config options. In this case, you are asking @bak to authenticate with @prod via ssh/rsync but you are not using agent forwarding so @prod can't see your private key. Try specifying something like

```
'remote-user' => 'user_on_bak',
'ssh-options' => '-T',

```

So that drush will execute as 'user\_on\_bak' and ssh will pass along your local key to @bak so when it opens a session with @prod it will have a key to pass along.

# Answer
> 0 votes
I would like to see what the permissions on `/var/www` and `/var/www/.htaccess` are. try:

> ls -l /var/www /var/www/.htaccess

they should be writable. You should be able to:

> touch /var/www/anewfile; touch /var/www/.htaccess

if you can't, then your local `ruser` user does not have permissions to those files.

> sudo chown -R ruser:ruser /var/www

to change ownership of all files under /var/www

---
Tags: drush
---


# Question
Title: How to display results tagged with just one term ID when there are multiple filters
I have a blog in Drupal 7 and used Views to display the fields. I have 2 sets of tags displayed on the sidebar:

```
1) SHAPES

Triangle

Square

Rectangle

2) COLOR

Red

Blue

Green

```

I created the 2 groups of tags via Structure \> Taxonomy \> Vocabulary \> Add Term

For the View, I created one View with two exposed filters (similar to what was done in this tutorial)

VIEW:

```
Path: '/blog/tag'

Filter Criteria:
    1) 'Content: Shape (exposed)'

        Exposed form in Block: 'Yes'

        Filter identifier: 'shape_id'

    2) 'Content: Color (exposed)'

        Exposed form in Block: 'Yes'

        Filter identifier: 'color_id'

Exposed form style: BEF

```

The exposed filters are set to the appropriate block region in Structure \> Blocks.

If I click 'triangle', only blog posts tagged with 'triangle' should be displayed. Then if I click 'red', only posts tagged with 'red' should be displayed.

It looks like the correct blog posts are being displayed when I click on the terms. The URL gets appended with IDs from both vocabularies, but I can't seem to get the right combos to display.

Desired URL when 'triangle' is clicked: '/blog/tag/?shape\_id=1&color\_id=All'

Desired URL when 'red' is clicked: '/blog/tag/?shape\_id=All&color\_id=1'

So, essentially the results should display items tagged with just one term ID.

However, how it is currently working is that if I click 'triangle', and then 'red', both 'triangle' and 'red' have the 'selected' class (are both bolded) and the url is: '/blog/tag/?shape\_id=1&color\_id=1'

The only way I was able to get the desired URLs is if I have the '-Any-' option displayed. However, the use case I have is to NOT have '-Any-' listed in the list of tags.

Is this even possible without '-Any-' listed in the list of terms? I have never used multiple exposed filters before, so any guidance would be great as I've researched this for almost a week now. I read in another post that contextual filters would allow me to create separate path aliases that are clean urls, but I have not been successfully able to do this.

Any help would be greatly appreciated. Thank you for your time.

# Answer
When I tried using the taxonomy term pages approach, I could not figure out how to get the fields displaying properly. The fields displayed were based on the teaser in my Blog content type. And using exposed filter option was not a solution since my use case was to only display results based on one tag. What worked for me:

1) Add new view to existing Blog View

2) FORMAT: 'Unformatted list' SHOW: 'Fields'

3) FIELDS: \[add fields that you need displayed\]

4) FILTER CRITERIA: 'Content: Published (Yes)'; 'Content: Type (= Blog)'

5) PATH: '/blog/\[YOUR VOCABULARY NAME\]/%'

6) CONTEXTUAL FILTERS: 'Content: Has Taxonomy Term ID'

WHEN THE FILTER VALUE IS NOT IN THE URL: 'Display all results for the specified field'

WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED: select 'Override title' and in the input field, enter: '\[YOUR VOCABULARY NAME\]/%1'

select 'Specify validation criteria'

Validator drop-down, select 'Taxonomy Term'

Vocabularies: select appropriate Vocabulary name

Filter value type drop-down: 'Term name converted to term ID'

select 'Transform dashes in URL to spaces in term name filter values'

Action to take if filter value does not validate: select appropriate one that works for your needs (in my case: 'Display contents of "No Results found"')

If you need to display the term name in the heading on the results page, in the same view \> HEADER \> Add 'Global: Unfiltered Text' \> then in text area, add something like "VIEWING RESULTS FOR \[YOUR VOCABULARY NAME\] / %1"

Save the View. Since I had multiple filters, I cloned the above view and renamed everything. So, I ended up adding 3 additional views to my existing Blog View.

I had previously set URL aliases for Taxonomy Term Paths, so I removed these

Also, I had to go back to my Taxonomy Terms individually and delete the URL alias that was generated from the pattern

To have the list of tags displaying on the right with the desired URL structure of /blog/\[YOUR VOCABULARY NAME\]/\[YOUR TERM NAME\], I created a separate new view:

SHOW: 'Taxonomy Terms' of type '\[YOUR VOCABULARY NAME\]'

Create a Block

'Unformatted list' of 'Fields'

FIELDS: 'Taxonomy: Term Name' \> click this and unselect 'Link this field to its taxonomy term page'. Then expand "Rewrite Results" section and select 'Output this field as a link' \> in the Link path: 'blog/\[YOUR VOCABULARY NAME\]/\[name\]' (the \[name\] at the end of the url structure should appear as you see it with the square brackets) \> select 'Replace spaces with dashes' \> Transform the case to 'lower case' \> click Apply

FILTER CRITERIA: 'Taxonomy vocabulary: Machine Name (= \[YOUR VOCABULARY NAME\])'

Save the View

Then in Structure \> Blocks, place the block in the appropriate region

Hope this helps someone!
> 0 votes

---
Tags: views
---


title: Fast 404 module and Drupal core

text:
# Question
Title: Fast 404 module and Drupal core
I can see that Fast 404 module has been added to drupal core since 7.9 version. So in order to use it on my drupal site(without installing Fast 404 module),is there I need to do in the settings.php module? thanks

# Answer
> 4 votes
Go to the sites/default directory. Open up to the setting.php file. Around line 500 uncomment this `drupal_fast_404();` by removing `#`

Source

---
Tags: performance
---


# Question
Title: How to Display a pdf, rft, doc, txt on a overlay?
I collect user resumes by using a file field. That field is been display it on view and when you click on it it would download the resume file (either pdf, rft, doc, txt). I would like to open that document a overlay instead of downloading the document.

How can I achieve this ?

# Answer
You chekced pdf or pdf\_reader modules? in order to display it on an overlay open its link in lightbox
> 1 votes

---
Tags: files, modal-dialogs
---


# Question
Title: base_url in settings.php with mobile version
I've both www.example.com and m.example.com pointing to the same directory in Ubuntu and there was in the settings.php with this line:

```
$base_url="www.example.com";

```

**I want to ask what will happen in this case in Drupal where sites are accessed as www. or the m. versions?**

In the hook\_custom\_theme I'm returing a mobile theme whenever the URL is starting with "m.".

I was getting some wierd mix up of mobile and the desktop versions.

I was not able to find any cid with "http://m." URLs in the cache\_page mysql table. After I removed this $base\_url now both mobile and the desktop versions seem to be showing fine now and also cache\_page table is having rows with cid with "http://m...".

**I'm not fully sure this but could $base\_url cause this?**

# Answer
How is your `/sites` folder structure? You can create subdomain `m.example.com`, and implement the mobile version in there.

There are different approaches in implementing the subdomains in drupal. it may be *multisite and shared database* or *multisite with different databases* and *single code and different databases* .

what you are looking for is a shared database but different themes (multiple codes), Here is good discussion about this.
> 2 votes

---
Tags: 7, caching
---


# Question
Title: permissions to allow role to edit the posted date
in drupal 7 - I have given a role the permissions to edit, add delete and modify content but he doesn't see the authored date in order to modify it. how can I give him permissions to modify that ?

# Answer
> 2 votes
Updated date is set automatically by the system, if you want to edit that you will need to write some custom code. Your user *should* be able to see the 'authored date' though.

Alternatively, if you need a date field that the user can edit (say, a publication date), just create a date field on your content and render it appropriately.

---

\[edit based on additional info\]:

I went digging in the code and found this in node.pages.inc:

```
$form['author'] = array(
  '#type' => 'fieldset',
  '#access' => user_access('administer nodes'),
  '#title' => t('Authoring information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  '#attributes' => array(
    'class' => array('node-form-author'),
  ),
  '#attached' => array(
    'js' => array(
      drupal_get_path('module', 'node') . '/node.js',
      array(
        'type' => 'setting',
        'data' => array('anonymous' => variable_get('anonymous', t('Anonymous'))),
      ),
    ),
  ),
  '#weight' => 90,
);

```

As you can see, access is tied to the 'administer nodes' permission which I'm guessing you haven't, and probably don't want to give to that role.

Luckily this is quite easy to change using `hook_form_BASE_FORM_ID_alter(&$form, &$form_state, $form_id)`, here's the API for that function.

Create a custom module and put this in it:

```
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id){

    // You may wish to add some logic here to test for a specific role

    $form['author']['#access'] = TRUE;

    // Otherwise this will simply give everyone who can create nodes the
    // ability to change author and date.

}

```

---
Tags: users
---


# Question
Title: A large amount of Tokens slows down everything - Placeholder Tokens
had anyone of you had a problem with too large amount of tokens? Because of having few content types (~8) with bunch of fields (~5-10 each) Token module generates too big table with replacement tokens. This is why I had to increase in settings.php available memory to avoid drupal from php error. I set 512M so it generates the output table now but it is so slow that it freezes Chrome.

It happens where I have this preview of available tokens. So it can be found in Pathauto or Custom Breadcrumbs.

This is how it looks like in Google Chrome HTML preview:

# Answer
> 6 votes
You can find some solutions for such a problem on Node references + Entity Tokens creates HUGE Token Tree UI table HTML.

Using the Token tweaks module also helps. I've tried and it works fine.

> Provides tweaks for tokens (mostly to improve performance)
>
> * Disable token types or specific tokens.
> * Modify the default depth limit for the token tree UI.

# Answer
> 1 votes
Token Tweaks worked for me, but if you have a general disdain for adding more modules you could try the patches at Prevent recursive tokens.

You can also change `TOKEN_MAX_DEPTH` in `token.module`. For me, changing the value to `1` led to a load time of 1 second. `2` made it 5.23 seconds. `3` or more pretty much crashed the browser. You'd still probably want to make a patch of the change in this case and/or keep a backup of the `token.module` file, or make Hacked a part of your module update process.

# Answer
> 1 votes
You can stop `token_help` rendering in Drupal 7.

If you don't need tokens on a given form and too many fields on too many content types is causing performance issues, you can replace the theme function for the list of avaiable tokens and replace it with a link back to the same page with a variable set where you would like to see the tokens.

By default, it won't render the tokens, but if you want to view a page with the tokens you can:

```
function nys_utils_theme_registry_alter(&$vars) {
  $vars['token_tree']['function'] = 'nys_utils_theme_token_tree';
}

function nys_utils_theme_token_tree($variables) {
  if(isset($_GET['show_tokens']) && $_GET['show_tokens'] == 1) {
    return theme_token_tree($variables);
  } else {
     return l('show tokens',$_GET['q'], array('query' => array('show_tokens' => '1')));
  }
}

```

---
Tags: tokens, path-aliases
---


# Question
Title: Chart & graph as content type? is it possible with any module
I want to create content type as chart and graph, any module which can render my data into chart form ?

# Answer
As mentioned in the previous answer, **charts** is indeed a module that might be considered. In response to the comment in it about "not using views" you need to know that using views for creating charts is only one of the available use cases for the charts module, as explained in the charts community documentation. Here is the relevant quote of it:

> Various options are available to actually create charts via the **charts** module:
>
> 1. Use the charts module directly e.g. to create a chart as part of the body of a node (using data that are hard-coded in such node).
> 2. It can be used as a views style (views integration).
> 3. Take advantage of the charts API to integrate it into your module, using a single function as the point of contact: charts\_chart();.
> 4. Visualize data stored in a database table (more dynamically), as explained in Chart some data stored in a database table (dynamically).

So from the above options, I believe that option "1." could perfectly address the original question. All you'd need is to enable the PHP filter (input format), and then add the relevant PHP code related to the charts render array (which is used to specify any of the desired options supported by the Charts API). As a variation of such "content type", you may also use a custom block (in which you include the same PHP code related to the charts render array).

To create charts in Drupal, there are actually dozens of modules to pick from (really!). Consider the comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the **charts** module mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module. I recently created quite a lot of new Chart documentation, and Charts documentation. Though there are other alternatives in that comparison that might be a better fit for this specific case.

The **license** that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Recently I extended the above mentioned comparison with Maintenance Scorecards for all Native Charting Modules. These **Maintenance Scorecards** should help to further narrow down the available charting options if you're concerned about how well some module is maintained (or not).

Disclosure: I'm a maintainer of both module 'chart' and 'charts' (confusing names, I didn't invent those names), and the author of the comparison (+ some charting modules mentioned on my profile). I hope this does not violate the site's policy on self-promotion.
> 2 votes

# Answer
You can achieve that using Charts module

> Transform Data into Information. Charts are a very good way to visualize a lot of data in a way that can be quickly digested.
> 1 votes

---
Tags: charts
---


# Question
Title: Is it possible to create a graph out of collected information stored in a Drupal database?
I am new to Drupal. As a beginner I want to create a website which needs to store lots of information. And from the collected information (statistics), I want to map a graph (or chart) out of it.

**My Question**: Can it be done using Drupal?

# Answer
You can also use Charts: Charts

> Transform Data into Information. Charts are a very good way to visualize a lot of data in a way that can be quickly digested.
> 2 votes

# Answer
You can use **Charts & Graphs**, **Charts** or **View Charts** module. Through this you can show information in the form of graph.
> 2 votes

# Answer
Since the other answers to this question were posted, many things have happened regarding the documentation of the Charts module. So here is an updated version of what is available today.

The Charts module is one of the typical charting modules that can use Google Charts as one of its Supported Charting Libraries. Here is part of what's currently included on the Charts project page:

> Transform **Data** into **Information**. Charts are a very good way to visualize a lot of data in a way that can be quickly digested.
>
> **Features**
>
> 1. **Wide chart type support**: Pie, Line, Bar, Column, Area or Scatter charts.
> 2. **API**: A Drupal-friendly syntax for creating charts easily, regardless of the underlying library.
> 3. **Views integration**: Display the Views results as charts.
> 4. **Examples**: The module includes lots of example charts for you to reference when building your own charts or chart library integration.
> 5. **Supported charting libraries**: out of the box, you may use either (the new) Google Charts (**GC** for short) or Highcharts (**HC** for short) as the charting library.

To address the OPer's comment about 'step by step procedures' and 'documentation':

- Start from the Community documentation about the Charts module.
- There are around 10 child pages there, with topics such as:

This should help a bit "to get started" ...

Disclosure: I'm a co-maintainer of the Charts module,
I hope this does not violate the site's policy on self-promotion.
> 1 votes

---
Tags: database, charts
---


title: Meta Tags on Frontpage

text:
# Question
Title: Meta Tags on Frontpage
It doesn't seem I can get my meta tags to appear on the `page--front.tpl.php` on a Drupal 7 site.

I feel like I have all the correct settings in the Meta tags module configuration, and I have cleared all caches. It works perfectly fine for all pages, just not the front page. This is driving me bonkers.

Any ideas?

# Answer
Below are the steps without touching the files and using the drupal admin interface.

1. Go to admin/config/search/metatags/config/global:frontpage/edit
2. Add the Page title, Description etc and Save
3. Refresh the front page and check. Done !!
> 13 votes

# Answer
Try printing

```
<?php print render($page['content']['metatags']); ?>

```

in your `page.tpl.php` or `page--front.tpl.php` if youre using Meta tags
> 4 votes

# Answer
What module are you using for Metatags?

I believe the most popular one is metatags\_quick. If you are using this I think you need to set the homepage metatags with the "Path-Based Metatags". You should be able to find this at site.com/admin/config/search/metatags\_quick/path\_based
> 1 votes

# Answer
Found a quick and easy solution that shows meta tag description on page view source HTML for anonymous visitor, also Bing SEO Analyzer detects.

1. Go to Meta Tag (Quick) settings from Configuration admin menu.
2. Under the section Create and Attach, check box for Description for Taxonomy Term
3. Click Attach
4. Click Submit
5. Go to admin Structure menu, Taxonomy, Section, List terms
6. Edit Home to add a description in the (Meta) Description field.

Works
> 1 votes

---
Tags: 7, meta-tags
---


# Question
Title: What does "sanitized" mean (in api documentation)?
Hi I see the word "sanitized" quite often in Drupal API documentation.

For example, this page: theme\_username($variables)

> $variables An associative array containing:
>
> account: The user object to format.
>
> name: The user's name, **sanitized**.
>
> extra: Additional text to append to the user's name, **sanitized**.

What does **sanitized** mean in the context?

# Answer
'Sanitization' is the removal of malicious data from user input, such as form submissions or maybe more simply...

The cleaning of user input to avoid code-conflicts (duplicate ids for instance), security issues (xss codes etc), or other issues that might arise from non-standardized input & human error/deviance.

Depending on the context, sanitization will take on a few different forms. Could be as simple as removing vulgarities & odd symbols from text to removing SQL injection attempts and other malicious code intrusion attempts.

You can get the idea of what Sanitization is generalized to drupal core by looking at: http://api.drupal.org/api/drupal/includes--common.inc/group/sanitization/7

For instance, the check\_plain() function will:

> Encode special characters in a plain-text string for display as HTML.
>
> Also validates strings as UTF-8 to prevent cross site scripting attacks on Internet Explorer 6.

or filter\_xss() which:

> Filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.
> 8 votes

# Answer
The key idea with Drupal input handling is that *any* data is accepted from the user, but we make sure to output to the screen (or use in database queries) only "sanitized" data - which will do no damage, provide no XSS and related opportunities, etc.

To understand the excellent answer above you need to make sure you understand that strategy. You may be interested in reading the excellent little book "Cracking Drupal" or the resources from http://crackingdrupal.com/.
> 3 votes

# Answer
Two meanings here, one is properly encoding characters like & or ', the other to prevent code injection.
> 2 votes

# Answer
'Sanitization' is the removal of malicious data from user input, such as form submissions
> 0 votes

---
Tags: 7
---


# Question
Title: Removing posted by admin date from a contact form
I am making a contact form in Drupal with using panels but in contact form it is showing posted by admin date. I want to remove these two things as shown in image.

# Answer
There are multiple ways you can do it

1. For all content of same content type

* Go to the content type for which you want to hide Author info.
    * Scroll down to see the tabs at the bottom and select Display settings.
    * Uncheck Display author and date information.
    * Save content type
2. For Single Node

* Go to node.tpl.php and search for $submitted
    * Give below condition for you case

    ```
    if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE AND arg(1)==7) {  print $submitted; }

    ```
> 0 votes

---
Tags: panels, emails
---


title: Programmatically add a views

text:
# Question
Title: Programmatically add a views
I'm writing a little module which should simplify creating a new view proccess for my site manager. What I want to do is to create a form, where the editor can fill some options (like title, path, some specific values for filtering etc) and then my code has to insert those options in my view template and import it to the database like a noraml view created via UI.

But as I understood, hook\_views\_default\_value just loads the ready view item which is conteined in the module. But i want to create a new one each time with the same template. How can i do this?

Will be very appreciated for any advice.

# Answer
I would suggest You to check views export functionality (admin/structure/views/view/name-of-some-view/export). There you should get the view object.

Then, copy this object to your form\_submit function, replace desired values with form values and call $view-\>save() function. The view should be created (or updated, if such machine name exist.)
> 2 votes

---
Tags: views
---


# Question
Title: I want to show the limited amount of products using JCarousel module?
I am using Jcarousel module for products to show the front page. So I want to show the limited amount of products. I mentioned in views **Use pager: Display a specified number of items | 5 items** .But it doesn't work it.. It shows the all produtcs in the front page.. How to configure it..

# Answer
The solution is to add the following code around line 147 of jcarousel.views.inc

```
if ($view->query->pager->options['items_per_page'] != 0){
    $count = min($view->query->pager->options['items_per_page'], $count);
}

```

You can read more about the issue at https://www.drupal.org/node/2408883
> 1 votes

---
Tags: views, javascript
---


# Question
Title: Google Map will not show on new ajax page load
I have added a styled google map V3 to a block using full html this all works fine and displays on page refresh. I'm have trouble with the map loading after linking to another page in conjunction with the ajax pages module.

All of my main menu links are ajax calls and pages load via ajax. On a page refresh the map will show, but if I click back and forth through the ajax pages the map will fail to load. I'm guessing this has something to do with this line?

```
google.maps.event.addDomListener(window, 'load', initialise);

```

Is there something I can do to make the map load even after a ajax page change? I have tried to change the load to on.load but that doesn't make a difference.

Here is the code in my block:

```
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

<div id="map-canvas" style="height:400px; width:600px;"></div>
<script>
function initialise() {
var myLatlng = new google.maps.LatLng(53.068165,-4.076803); // Add the coordinates
var mapOptions = {
zoom: 8, // The initial zoom level when your map loads (0-20)
minZoom: 6, // Minimum zoom level allowed (0-20)
maxZoom: 17, // Maximum soom level allowed (0-20)
zoomControl:true, // Set to true if using zoomControlOptions below, or false to
remove all zoom controls.
zoomControlOptions: {
style:google.maps.ZoomControlStyle.DEFAULT // Change to SMALL to force just the +
and - buttons.
},
center: myLatlng, // Centre the Map to our coordinates variable
mapTypeId: google.maps.MapTypeId.ROADMAP, // Set the type of Map
scrollwheel: false, // Disable Mouse Scroll zooming (Essential for responsive sites!)
// All of the below are set to true by default, so simply remove if set to true:
panControl:false, // Set to false to disable
mapTypeControl:false, // Disable Map/Satellite switch
scaleControl:false, // Set to false to hide scale
streetViewControl:false, // Set to disable to hide street view
overviewMapControl:false, // Set to false to remove overview control
rotateControl:false // Set to false to disable rotate control
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); //
Render our map within the empty div
var image = new google.maps.MarkerImage("http://www.creare.co.uk/wp-content/uploads
/2013/08/marker.png", null, null, null, new google.maps.Size(40,52)); // Create a
variable for our marker image.
var marker = new google.maps.Marker({ // Set the marker
position: myLatlng, // Position marker to coordinates
icon:image, //use our image as the marker
map: map, // assign the market to our map variable
title: 'Click to visit our company on Google Places' // Marker ALT Text
});
// google.maps.event.addListener(marker, 'click', function() { // Add a Click
Listener to our marker
// window.location='http://www.snowdonrailway.co.uk/shop_and_cafe.php'; // URL to
Link Marker to (i.e Google Places Listing)
// });
var infowindow = new google.maps.InfoWindow({ // Create a new InfoWindow
content:"<h3>Snowdown Summit Cafe</h3><p>Railway Drive-through available.</p>" //
HTML contents of the InfoWindow
});

google.maps.event.addListener(marker, 'click', function() { // Add a Click Listener
to our marker
infowindow.open(map,marker); // Open our InfoWindow
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(myLatlng); }); // Keeps the Pin Central when resizing the browser on
responsive sites
}
google.maps.event.addDomListener(window, 'load', initialise); // Execute our
'initialise' function once the page has loaded.
</script>

```

Thanks,

Terry

# Answer
You can do it this way:

```
var success = Drupal.ajax.prototype.success;

Drupal.ajax.prototype.success = function(xmlhttprequest, options) {
    success.apply(this, arguments);
    initialize();
}

```

This will call initialize (make a note about your init function - it' called initialiSe) just after successful Drupal.ajax call.

Using this code

```
success.apply(this, arguments)

```

we ensuring ourselves that nothing interrupt normal behaviour of the original handler.
> 1 votes

---
Tags: ajax, google-maps
---


title: Adding AJAX to existing node form

text:
# Question
Title: Adding AJAX to existing node form
Creation of new content type by D7 core is intuitive, fast and nice looking. We don't have to worry about db tables and simple validation. We have widgets, displays, etc. And actually we are building a form (company\_node\_form).

*Example:*

Custom content type: Company

Field group: Company address (vertical tab)

* Field (simple text): Street
* Field (simple text): No.
* Field (simple text): Zip code
* Field (simple text): Country

Field group: Company contact (vertical tab)

* Field (check box): Has phone
* Field (simple text): Phone
* Field (check box): Has fax
* Field (simple text): Fax

Field group: Privacy (vertical tab)

* Field (check box): Show address
* Field (check box): Show phone

**Question**

How to add alternation using custom module "my\_module" to provide AJAX behavior **while adding or editing** content type, i.e. to show "Phone" field only if "Has phone" is checked or show text "Sorry, we don't have authority to add companies from selected country." when UK goes to "Coutry" field?

**Exclamation**

I know that the above form is very simple to code inside my\_module, but I wish to use core node constructor to build that form instead of coding.

# Answer
Your module needs to implement hook\_form\_alter() to add '#ajax' arrays to the elements that trigger a change in the form. The #ajax elements will include 'wrapper' and 'callback' elements that specify the html ID of the part of the form to replace and a function in your module that returns the part of the form that is being replaced.

For example, if the element 'my-element' should be replaced, add

```
'#prefix' => '<div id="my-element-id">',
'#suffix' => '</div>'

```

to the form array with key 'my-element'. The element that triggers the replacement will get

```
'#ajax' => array(
   'wrapper' => 'my-element-id',
   'callback' => 'my_callback',
   'method' => 'replace',
),

```

Here is the callback function:

```
function my_callback($form, &$form_state) {
    return $form['my-element'];
}

```

Your hook\_form\_alter() will hide/show elements and generate your custom messaging depending on $form\_state (which it will read when the ajax callback happens).
> 1 votes

# Answer
To add this functionality to the node form, use Conditional Fields module - http://drupal.org/project/conditional\_fields. You will need to create field dependencies to allow a particular field to show only when the previous field's input meets some criteria.
> 1 votes

# Answer
As @sel\_space mentioned hook\_form\_alter trigger once when builds form at first time. I believe you can use #after\_build and add own callback.
> 0 votes

# Answer
For simple Ajax functionality have a look at `#states` in Form API.

```
/**
 *  Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYNODETYPE_node_form') {
    $form['field_telephone_number']['#states'] = array(
      'visible' => array(
        ':input[name="field_has_phone"]' => array('checked' => TRUE),
      ),
    );
  }
}

```
> 0 votes

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


# Question
Title: Node blog dislpay all content type blog in theme
I have content type page with node called blog(page blog) and I want to display all content type blog in it(content of page blog). how can i do this in theme without using block or views.I'm try to do it by using this code:

```
<?php
$build = array();
$query = db_select('node', 'n')->extend('PagerDefault');
$nids = $query
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->limit(3)
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes,'full');
    $build['pager'] = array(
        '#theme' => 'pager',
        '#weight' => 5,
    );
}
else {
    drupal_set_message(t('No blog entries have been created.'));
}

    print render($build);
  ?>

```

and set it in body field for page blog. And when display blog page it's content nothing (or empty page!). I'm test my code and execute it in php code it work and print all blog that I have. Any way to do this in Drupal theme?

# Answer
> 1 votes
if I understand correctly you'll need this query:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'blog')
  ->propertyCondition('status', 1);

$result = $query->execute();

```

then do you foreach($result);

---
Tags: nodes, theming
---


# Question
Title: Install Meta Tags and Meta Tags Quick modules on the same site
Short: Are Meta Tag and Meta Tag Quick incompatible modules?

I am configuring a site that has Meta Tag Quick module but it doesn't allow me to have a meta description tag. It creates an Open Graph description meta tag instead.

Then I want to install Meta Tag module but I am afraid of my site crashing or some error. I know I have to do a backup, and I did.

# Answer
> 0 votes
Couple of things to mention. Meta Tags Quick does have a meta description field - check the module settings and enable the field for the content types.

Metatags and Meta Tags Quick can be installed on the same site - I've done this successfully (I do suggest testing on a mirror development site first). Bear in mind the two modules will duplicate some fields so you need to decide which fields you want each module to use.

The data cannot be imported from one module to the other however - maybe running SQL commands, but not from Drupal admin

---
Tags: 7, meta-tags
---


title: Migration from drupal to platform.sh

text:
# Question
Title: Migration from drupal to platform.sh
I have developed website which is hosted on hostgator now I want to host it on platform.sh. Could anyone give me step by step procedure to migrate my website to platfrom.sh? I am using windows 8.1 for development. Could you please explain how to use git. Could please give step by step procedure how to use it. I am on windows platform. I am bit confused how to use it.

# Answer
> 2 votes
To migrate your existing site into Platform.sh, there are 3 components you need to import: code base, database and files.

## Import code base

If your project already uses Git you've to go to your Git project folder and add platform as a remote and push your local branch to your platform remote.

```
$ cd ~/Sites/platform
$ git remote add platform [PROJECT-ID]@git.[CLUSTER].platform.sh:[PROJECT-ID].git
$ git push platform HEAD:master

```

## Import your database

1. Create drush alias for your platform.sh, e.g.

```
$ cd ~/.drush
$ sudo vi platform.aliases.drushrc.php

```

In your new alias file, you can create aliases for your various Platform.sh projects. For example:

```
<?php
// Platform environment
$aliases['master'] = array(
  'uri' => 'master-[project-id].eu.platform.sh',
  'root' => '/app/public',
  'remote-host' => 'ssh.eu.platform.sh',
  'remote-user' => '[project-id]-master',
);
// Platform branch environment
$aliases['BRANCHNAME'] = array(
  'uri' => 'BRANCHNAME-[project-id].eu.platform.sh',
  'root' => '/app/public',
  'remote-host' => 'ssh.eu.platform.sh',
  'remote-user' => '[project-id]-BRANCHNAME',
);
// Platform local environment
$aliases['local'] = array(
  'site' => 'platform',
  'env' => 'local',
  'uri' => 'platform',
  'root' => '~/Sites/platform',
);

```
2. Backup your database.

$ drush @platform.local sql-dump \> backup\_database.sql
3. Export your local database and then import it into your remote Platform environment.

```
$ drush @platform.local sql-dump > local_database.sql
$ drush @platform.master sql-cli < local_database.sql

```
4. When the process completes, you can visit the URL of your development environment and test that the database has been properly imported.

## Import your files

1. Use drush alias to import your existing local files:

```
$ drush rsync @platform.local:%files @platform.master:%files

```

---

The above steps assume that you're using `drush` and Git scm (which is the easiest way).

More details information can be found at: Migrate an existing site to Platform.sh

---
Tags: 7, migrations
---


# Question
Title: How to get product URL or URL alias using product ID?
I'm using Drupal Commerce and stuck in this problem. I'm creating a custom module that will display a product title and some info.

I want that product to be linked to its node page, and product Object is all I have to my resources. I'm thinking of getting the product URL or alias using `product_id` but I don't know how. I already searched it but there's nothing clear on the search results I got.

Any suggestions?

# Answer
> 1 votes
After trial and error I found a solution. Here's what I did.

```
        //$product is the product object that I mentioned above
        $wrapper = entity_metadata_wrapper('commerce_product', $product);
        $nodes   = $wrapper->field_product_node->value();
        $path    = drupal_get_path_alias("node/".$nodes[0]->nid);
        $product->path = $path;

```

---
Tags: commerce, uri
---


# Question
Title: How do I add a custom class to a field based on another field value(boolean)?
I have a Commerce product and there are two price fields. (Original price and Sale price). I would like to display original price as line-through text when sale price is available. Therefore I would like to add a custom class to a field based on another field value(boolean), I looked at this function, hook\_entity\_view\_alter, but I don't know whether it will be good.

Anyone has idea how do I solve this?

# Answer
I've never used the commerce module but that sounds possible, you need to create a module for the hook to be triggered from.

Then, with the `devel` module installed use `dpm($build, $type)` within the hook to see the correct names (I've put in dummy values in CAPS) and do something like:

```
function MYMODULE_entity_view_alter(&$build, $type){
  if ($type =='product') {
    if (isset($build['SALE_PRICE']['VALUE'])) {
                $build['PRICE']['attributes']['class'] = array('on-sale');
            }
        }
    }

```
> 0 votes

---
Tags: theming, entities
---


title: Where do I translate strings?

text:
# Question
Title: Where do I translate strings?
Where is the interface for translating strings that modules pass to `t()`, in Drupal 7?

# Answer
You can find it here "admin/config/regional/translate/translate"
> 7 votes

# Answer
Ok, my bad. It's located here: **admin/config/regional/translate/translate**

But I was confused by the interface. The search is case sensitive so that got me to start. Then it was showing "fr", which is the language to translate to, NOT the language that it is. Click the "edit" link under **Operations** to add a translation.
> 2 votes

# Answer
I had to enable the Locale and Content Translation Module first. Otherwise there is no page at admin/config/regional/translate/translate.
> 0 votes

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


# Question
Title: Message "Restricted HTML" on node/add page
On node/add page for any content type(Article, Basic page. Custom) message appearing "Restricted HTML" , not able to add content.

What shall a do to resolve this problem?

# Answer
> 1 votes
Please try again after raising xdebug.max\_nesting\_level to 500 or so.

Steps:

**Know where is the php.ini:**

In your drupal site go to admin/reports/status/php

**Then edit your php.ini** in this case, is on /etc/php5/fpm/php.ini

Search the xdebug section:

Change the variable xdebug.max\_nesting\_level to 500 or add it.

**Restart the web server.**

---
Tags: nodes, 8
---


# Question
Title: Views: display entity reference fields as view fields
I have a content type (1) with an entity reference field that point to another content type (2).

I'm trying to create a view where I want to display fields of content type 1 mixed with the FIELDS of the content type 2.

When I go to add fields in my view I can see the fields of content type 2 but the output is empty, the only thing I can do is display the rendered content type 2 with all of its fields.

Is there a way to output single fields of content type 2 as view fields?

# Answer
> 1 votes
Yes you can do it. The Entity view Attachment module is built for such task. Using this module, fields of another content types becomes a filed of another one. this link is a good tutorial of this module.

---
Tags: views, entities
---


title: Get nid inside preprocess function

text:
# Question
Title: Get nid inside preprocess function
My goal is to have an additional region class, when region is rendered on my page--node--9 I am using this `template_preprocess_region()` function to do this.

But how i can get inside my function ID of page, region is rendered on?

# Answer
> 1 votes
From another implementation of the same hook I found out that the node is actually available through the following. Try it out.

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

```

From there you can get node id.

---
Tags: theming
---


# Question
Title: Views different image styles depending on URL
I want get very close Views results, but image style should differ. It should be done by using different URLs or Views arguments. How I can reach that?

**UPD:** final solution:

```
/**
 * Return actual image_style of image depending on URL params.
 */
function _MYMODULE_image_style() {
  $allowed_image_styles = array('image_style_1', 'image_style_2');
  $params = drupal_get_query_parameters();
  if (isset($params['image_style']) && in_array($params['image_style'], $allowed_image_styles)) {
    $image_style = $params['image_style'];
  }
  return isset($image_style) ? $image_style : NULL;
}

/**
 * Implementation of hook_views_pre_execute().
 */
function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'view_1' && $view->current_display == 'services_1') {
    $image_style = _mymodule_image_style();
    if ($image_style) {
      $field_name = 'field_vendor_logo';
      $view->display_handler->handlers['field'][$field_name]->options['settings']['image_style'] = $image_style; // <<< THIS IS the main part of solution
    }
  }
}

```

# Answer
> 2 votes
Create different ImageStyles, If the image field of the content type is `field_image` then you can use this code:

```
        $variables['theme_hook_suggestions'][]='THE_THEME_HOOK_SUGGESTION';
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $photo_field = $wrapper->field_image->value();
        $url = arg(1); // you can distinguish the address by arg(0),arg(1), ...
        if ($url == "URL1") {
                $variables['image'] = theme('image_style',
                     array(
                        'style_name' => 'STYLE1',
                        'path' => $photo_field['uri'],
                    )
                );
        } else if ($url == "URL2"){
                $variables['image'] = theme('image_style',
                     array(
                        'style_name' => 'STYLE2',
                        'path' => $photo_field['uri'],
                    )
                );
        }

```

Make sure to put such code `hook_preprocess_node`, and also this code is run when the correspondent content type is loaded. then in the THEME\_HOOK page of the content type use `$image` variable to display the image.

---
Tags: views, media
---


title: Change currency code to symbol

text:
# Question
Title: Change currency code to symbol
I'm translating the Drupal Commerce site into Japanese. I want to change the currency code JPY to symbol "円".

But keeping rest of the symbols (￥) as it is:

I referred this question and also made changes accordingly. But it didn't help me. Please guide me.

One more question regarding it, is it possible to use 2 symbols for the same currency? Is there any way to display "円" replacing this "JPY" only? I don't want to use String Overrides.

**Edit:** It is ok if I completely change the symbol from "￥" to "円". I tried doing this by altering **commerce.api.php** file, but it didn't reflect anything.

# Answer
> 0 votes
If it is a form, you can use hook\_form\_alter along with the PHP function str\_replace to replace JPY with 円. Let me know if you need further help.

EDIT:

```
<?php
  function YOURMODULE_form_alter(&$form, &$form_state,$form_id) {
    if ($form_id == 'your_form_id') {
      print str_replace("JPY", "円", render($content));
    }
  ?>

```

---
Tags: i18n-l10n, commerce
---


title: Inline js inside a form

text:
# Question
Title: Inline js inside a form
I'm trying to attach inline js inside a form, but it's not working out. Is there anything wrong with below code

```
$form['#attached']['js'][] = array(
    'data' => 'jQuery(function() { console.log("test"); });',
    'type' => 'inline',
);

```

# Answer
> 0 votes
You seem to be trying to use method for adding settings. I believe this is the correct way as stated on the docs:

```
$form['#attached']['js'] = array(
  'jQuery(function() { console.log("test"); });' => array(
    'type' => 'inline',
  ),
);

```

Docs: `#attached`

---
Tags: forms
---


title: Different domains with same language

text:
# Question
Title: Different domains with same language
**Here is my situation**

We have 2 websites: domain.es (use Spanish language) and domain.co.uk (English). Customer asked us to register new domains: domain.mx (Mexico, so Spanish language) domain.com (English language).

1. We do not want let domain.mx see content from domain.es, but that what will happen, because our views (like all other stuff) are dependent on language.
2. We are considering to filter content by domain using https://www.drupal.org/project/domain however since we never used it before we are not sure if it will cover our needs.

I want to get your opinions guys, how would be best to manage content based on domain level but not a language. So domain.mx and domain.es are completely 2 independent websites and do not share values to each other.

Thanks!

# Answer
> 1 votes
If you want the .es and .mx content to be unique, you should treat them as different languages.

create a new mx-spanish language type. even though it is "spanish" the system has no idea, you can just load the unique content there.

---
Tags: i18n-l10n, domain-access
---


title: Trying to to display form in template

text:
# Question
Title: Trying to to display form in template
I'm trying to display a form in a template (not my first choice, but I'm restricted in what I can do here) and I'm having some trouble figuring out how to do it.

I'm trying to tie into the Ubercart Addresses module to allow the user to select from one of the countries available to them.

I believe this information is located in `uc_addresses_get_address_form`

What I'm trying to do is as follows:

```
<?php  print render(drupal_get_form('uc_addresses_get_address_form'))?>

```

But this doesn't seem to add the form information I want.

How do I get this information into a template file?

# Answer
> 0 votes
Something like the following should work:

```
drupal_render(drupal_get_form('uc_addresses_get_address_form'))

```

Check Render form in template

---
Tags: 7, theming, ubercart
---


title: Entity reference vs. taxonomy

text:
# Question
Title: Entity reference vs. taxonomy
Let's say I have a team, which has members. I have a content type for team and a content type for individual team members. Let's say there are also other relationships, for instance teams can belong to departments, and there are projects that can be assigned to individuals or teams.

As I understand it there are two ways I can define the relationships between these entities - either Entity references, or using Taxonomy terms. When I should use one type over the other? Is it best to choose just one method, or mix them?

It seems to me that Taxonomy is the most flexible, because it is easy to build trees using taxonomy types, or for instance if within a team I then decided I wanted to build a hierarchy in the team the functionality is already there (just drag the taxonomy terms into the hierarchy) whereas if I've used Entity reference I can't think of a simple way to do that (other than adding taxonomy, which then results in redundancy).

It feels as if there is something I'm not understanding here, but I'm not sure what it is!

Any help would be appreciated.

# Answer
> 25 votes
You are talking about two different concepts here. The first question is related to whenever one wants to organize content into different categories or if one wants to build a relationship between existing content types. The other question is, if, when using a taxonomy, will it be better to use a taxonomy reference field or an entity reference field.

---

## Regarding the first concept

It depends on your use case. Taxonomies are great for building hierarchies, as you mentioned, but ideally, you shouldn’t use taxonomies to contain actual content. The reason for that is easy — while you can add fields to taxonomy terms, all hierarchical levels in a taxonomy use the same fields. Taking your example with members belonging to different teams, this might lead to problems. If you want to store more information about a team or member than just the name, If, for example, you want to store information about a member’s first name, last name, and biography, and add this fields to the taxonomy, they would be available on team terms as well. And if you add a team description field for the teams, those will show up for team members.

Taxonomies are best used when *organizing similar items* hierarchically. Like tags, for example:

* vegetable
    + carrot
    + potato
* fruit
    + apple
    + banana

Entity references are excellent for *establishing relationships* between content types. Examples include when you have a node type ‘team’ and a node type’ team member,’ each with their own fields. Or a node type ‘song’ which is referencing an ‘album’ which itself references a ‘musician.’ In this regard, entity references are more flexible than taxonomies, as it allows for more complex relationships. When you use views, you can also utilize these relationships. Taking your example, you could create a view of all team members, and using the entity reference for a relationship, and one could display any field on the team content type along with fields from the member node.

Mixing node referenced and taxonomy fields are legit too. In your example with the teams, both team and member could be a node, referencing each other with an entity reference. At the same time, the department could be a taxonomy with all available departments.

---

## Regarding the second concept

When D.O. released D7, it shipped with a taxonomy reference field to use when referencing taxonomies. Since then, we’ve seen the release of the Entity API module and, consequently, the entity reference module, and since terms and taxonomies are entities, one can reference them like any other entity. At this point, the two are working very similarly, and in many cases, it doesn’t matter which one you use. However, there are still some contributed modules providing field formatters and widgets, which only work for one or the other. So, it mostly depends if you need such a formatter if you should use taxonomy reference or entity reference.

As D.O is replacing the taxonomy reference field with the entity reference field in D8, I prefer to go with the entity reference field to link to taxonomies rather than the field supplied by the taxonomy module.

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


title: Show Content And Webform Same Page

text:
# Question
Title: Show Content And Webform Same Page
I Am Making A Contact Page In Drupal 7 In Which I Have To Show Office Address And A Contact Form Made With Webform Show Together So Can Anyone Suggest Any Idea How To Show A Content And Webform In Same Page

# Answer
In webform, you can go to form settings, and in the advanced tab at the bottom, there is an option expose your form as a block.

Then go to structure \> blocks and place the webform block on the page/region that you want.
> 0 votes

---
Tags: webforms
---


# Question
Title: Help with debugging and fixing errors with SalesForce Mapping Module
For Drupal SalesForce Suite I am having the follwoing Errors show up in my log messages

When I select from the Drupal Entity Type , Drupal Entity Bundle, and Salesforce Object I get these errors

Notice: Undefined index: salesforce\_record\_type\_default in salesforce\_mapping\_form\_validate() (line 520 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce\_mapping/includes/salesforce\_mapping.admin.inc).

Notice: Undefined index: salesforce\_record\_types\_allowed in salesforce\_mapping\_form\_validate() (line 520 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce\_mapping/includes/salesforce\_mapping.admin.inc).

Warning: in\_array() expects parameter 2 to be array, null given in salesforce\_mapping\_form\_validate() (line 520 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce\_mapping/includes/salesforce\_mapping.admin.inc).

For just SalesForce Object I get this additional error

Warning: Invalid argument supplied for foreach() in form\_type\_checkboxes\_value() (line 2337 of /x/x/x/x/x/x/web/includes/form.inc).

In the UI I am unable to add more then the initial field, when I click the button to add additional mapping and select my field type, the second row of fields disappears and it logs this error in watchdog

Notice: Undefined offset: 1 in salesforce\_mapping\_form\_field\_callback() (line 428 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce\_mapping/includes/salesforce\_mapping.admin.inc).

Local Environment on XAMPP Mac OS Yosemite/ Drupal 7.34/ SalesForce Module 7.x-3.0-Dev/PHP 5.6

To further update this issue, it will allow me to create a mapping but with only the first row in the mapping table. If I save it and then go back in to edit, when I click "add another field mapping" I get a popup with this error.

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /system/ajax StatusText: OK ResponseText: Fatal error: Call to undefined function salesforce\_mapping\_form\_validate() in /x/x/x/x/x/x/web/includes/form.inc on line 1513

# Answer
Without being able to find an answer to the issues I was having, I did finally get the mapping module to work by downgrading XAMPP and instead of using PHP 5.6 used PHP 5.3, which enabled the Mapping module to begin functioning properly.
> 0 votes

---
Tags: 7, crm
---


title: What parts of a view can't be changed?

text:
# Question
Title: What parts of a view can't be changed?
Looking at my views listing, I see each has a "Type". The type effects the choices I have when adding fields. I have to create a whole new view if I want something different. Why is this? Many things are editable in the view. What are all the 'base characteristics' about a view that can't be changed?

I'm thinking about 7.x-3, but comparisons welcome.

# Answer
The 'Type' corresponds to the database table used for queries. This option creates the 'FROM' part of the SQL query. That is really the only part of a view that cannot be easily changed after the initial creation.

See https://www.drupal.org/node/2287909 for some more information about the basics of Views 3.
> 1 votes

---
Tags: views
---


# Question
Title: Retrieve the list of posts for a particular forum
From this question, I know how to retrieve a list of forum posts (forum topics?) from drupal.

```
curl -i -X GET  \
 -H Cookie:SESSe6a353351df0bcafe98787beef=B0YAHD3-reWwwW-kzhqw6A-SgeShSYUAAQQjh \
 'http://myserver/rest/node?parameters\[type\]=forum'

```

Now, I'd like to limit the list of forum posts to those belonging to a particular forum. How do I filter the result by forum? I know the forum tid. I just don't know how to format the query.

This doesn't cut it:

```
curl -i -X GET  \
 -H Cookie:SESSe6a353351df0bcafe98787beef=B0YAHD3-reWwwW-kzhqw6A-SgeShSYUAAQQjh \
 'http://myserver/rest/node?parameters\[type\]=forum&tid=4'

```

The above returns all forum posts. This also does not work:

```
curl -i -X GET  \
 -H Cookie:SESSe6a353351df0bcafe98787beef=B0YAHD3-reWwwW-kzhqw6A-SgeShSYUAAQQjh \
 'http://myserver/rest/node?parameters\[type\]=forum&parameters\[tid\]=4'

```

It gives me:

> "Invalid query provided, double check that the fields and parameters you defined are correct and exist. SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'tid' in 'where clause'"

I get the same error if I try to reference `parameters\[taxonomy_forums\]`

Any help?

# Answer
> 0 votes
To get all posts (forum topics) for a particular forum with id=4:

```
curl -i -X POST \
  -H Cookie:SESSe6a3baadbeef=ovQpO6aYeehaw_3W4onya22i9bonusQW \
  -H X-CSRF-Token:v6j7r9RactujA872hSHSKW-mYYWAA \
  -H Accept:application/json \
  -H Content-Type:application/json \
  http://myserver/rest/taxonomy_term/selectNodes \
  -d '{"tid":4}'

```

To find the mapping between forums and tids, refer to this answer.

I don't know how to do a parameterized query (GET) to retrieve forum topics. As far as I can tell you need to use POST, as described here.

---
Tags: 7, services
---


# Question
Title: Drupal 7 + Solr - Importing feeds after website restore leads to 1062 Error
I’m developing on localhost, using Drupal 7 with the Search API with Solr module. After performing a restore from backup, I needed to reimport several items from a feed. I set up my feed importers, using the Node ID as the unique target. However, after conducting the import, it always returns failure. The error report is a long list of:

```
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '62911-1' for key 'PRIMARY'

```

(The Duplicate entry number is different for each line.)

There are no nodes or actual content on the site, which leads me to believe that it is something in the database. Could be wrong, though.

I have done the following things to try and rectify this problem, with no luck:

* Changed “Do not replace existing nodes” to “Update existing nodes” in the Node Processor settings.
* Changed “Update existing nodes” to “Replace existing nodes” in the Node Processor settings.
* One search made me realize that my Solr server wasn’t automatically starting, so I did that and then ran the import; no luck.
* Rebuilt user node access permissions.
* Installed “Delete All” module and deleted all content, resetting the node id counter from 1.
* Cleared the Solr index from within Drupal.
* Deleted all items from within the Solr core itself (although the Index status page at
admin/config/search/search\_api/index/default\_node\_index still has “172/60857 indexed” under the status bar. This was the only partial success, as it managed to import 172 items, but the rest still received the error.)

Not sure where the problem is. I suppose I could just try and use GUID as the unique target, but I don’t know if that will work. (I’d also like to keep using the Node ID if possible.) I could also try to completely remove the Solr module from Drupal 7 and trying again, which I think will be my next step. However, I am really looking for any thoughts on this. Have any of you encountered this problem before? What have you done to fix this?

# Answer
> 2 votes
It turned out it was the Solr module itself. I'm not sure why it wasn't clearly it's index completely, but after disabling and actually removing the module, then reimporting, everything worked.

So if you're having this kind of trouble importing content, and you have the Search API Solr module active, first disable and then remove it so that you have a clean slate on that end. Then you can reimport the content, then later re-add the Solr module and reindex your content.

---
Tags: 7, feeds, importing-exporting, search
---


title: All database settings are set to 'A'

text:
# Question
Title: All database settings are set to 'A'
I'm encountering a very weird problem where my database settings look like this in `database.inc:openConnection()`

```
array(1) {
  ["default"]=>
  array(6) {
    ["driver"]=>
    string(1) "A"
    ["database"]=>
    string(1) "A"
    ["username"]=>
    string(1) "A"
    ["password"]=>
    string(1) "A"
    ["host"]=>
    string(1) "A"
    ["port"]=>
    string(1) "A"
  }
}

```

It's after I moved the site to a new host with Ubuntu 14.04, so PHP and MySQL are now on a different version.

Another related strange thing is that `drush sql-connect` is not returning anything.

The result of `global $databases; var_dump($databases);` looks normal.

# Answer
> 0 votes
Silly me. I copied some lines from D6 settings.php. After adding an extra `['default']` here: `$databases['default']['default'] = array(...` things are working fine again.

---

*Note 1: Probably good to not delete this question as someone else might run into something similar at some point.*

*Note 2: Will be nice if Drupal 8+ will have a more informative way of error reporting.*

---
Tags: 7, database
---


# Question
Title: How do I get a list of Drupal 7 active contexts for the current page/form in hook_form_alter?
I have several contexts defined for my site. In hook\_form\_alter I need to find out which of them are active. I am trying to use context\_active\_contexts, but that is only showing 2 of the (at least) 3 that are active. i.e. I have contexts A, B and C. C has a block reaction and the block is visible. My code only outputs A and B. If I disable C, the block disappears from the output, giving me some confidence that it really is context C that is responsible for it. Why can I not see A, B and C in the output?

```
function MyModule_get_current_location_contexts() {
  $contexts = context_active_contexts();

  $locations = array();
  foreach ($contexts as $context) {
    $locations[$context->name] = $context;
  }

  return $locations;
}

function MyModule_form_alter(&$form, &$form_state, $form_id){
  dsm('Contexts (form):');
  if ($form_id == 'MyForm') {
    $contexts = MyModule_get_current_location_contexts();

    foreach ($contexts as $context) {
      dsm($context->name);
    }

    dsm($form);
  }
}

function MyModule_node_view($node, $view_mode, $langcode) {
  dsm('Contexts (entity):');
  $contexts = MyModule_get_current_location_contexts();

  foreach ($contexts as $context) {
    dsm($context->name);
  }
}

```

# Answer
> 2 votes
The context name is the array key, not it's -\>name field. See my answer here on how to programmatically check if a context is active.

No need for foreach loop on $contexts on the 2nd and 3rd functions. Instead of loopoing on $contexts and printing for each context it's name field, you should simply print the array keys:

```
print_r (array_keys($contexts));

```

# Answer
> 0 votes
I believe the cause is that your form alter function is firing before the node conditions are met, so the context isn't active until a little later on in the Drupal loading.

One solution is to attach an #after\_build callback in your form alter, to can check the active context properly.

```
function example_form_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'example_form_alter_node_after_build';
}

function example_form_alter_node_after_build($form, &$form_state) {
  // Check active contexts here
}

```

---
Tags: 7, forms
---


title: Create A Product On Drupal 7

text:
# Question
Title: Create A Product On Drupal 7
Hello I Am Making A Website So I Want To Add Some Of My Product In My Product Page So I Want To Know That How I Can Add Product With Name Cost Of Product And Description Can Any One Suggest Any Module To Setup Product In D7

# Answer
> 0 votes
You can use either of these ecommerce solutions:

Drupal Commerce

> Drupal Commerce is used to build eCommerce websites and applications of all sizes. At its core it is lean and mean, enforcing strict development standards and leveraging the greatest features of Drupal 7 and major modules like Views and Rules for maximum flexibility.

or Ubercart.

> Ubercart is the most popular Drupal E-Commerce platform for your website. It implements everything you need to start selling products online. Web Developers from all skill ranges can use it to support a variety of E-Commerce industries-- including physical goods, digital downloads, or even subscription based billing services. Ubercart can do it all!

---
Tags: users, 7
---


title: Hide Drupal Web Form until Logged in?

text:
# Question
Title: Hide Drupal Web Form until Logged in?
I am running a competition whereby users must fill in a webform to enter. However, I am also using Facebook connect, and want the web form page to display, with the body and all the rest except for the form itself, unless the user is logged in. What is the best way to:

1. Allow access to the webform if anonymous?
2. Not allow the user to submit the form if anonymous?
3. Hide the form and show my custom Facebook login button if the user is not logged in?

Point 1 is basically using Webforms the default way. And point 3 I can probably do by just editing the template of the node. But I am not sure how I can override the validation of the form to stop the user from actually entering the competition if he is not logged in.

Any ideas on what the best way is to do this?

# Answer
> 1 votes
I haven't done this, but it should work to do something like this: Once you've created the webform, on the settings for your webform, under "Submission access" you can choose to restrict "Roles that can submit this webform" to "authenticated user" and under "Advanced Settings" there's a checkbox to make the webform "Available as a block." Once you have the webform block, restrict the block to authenticated users only. Put the content that should be available to anonymous users on a new page and add your webform block to that page. The webform should then only show up on that page for authenticated users.

---
Tags: webforms
---


title: How to Center Image in View Slideshow

text:
# Question
Title: How to Center Image in View Slideshow
I can't get the views slideshow to center in the div. I tried the following code but with issue:

```
#views_slideshow_cycle_main_content_slideshow-block {
  width: 100%;
  text-align: center;
}
#views_slideshow_cycle_teaser_section_content_slideshow-block {
  display: inline-block;
}

```

The image display in few seconds but disappear afterwards.

Can anybody please help me how to solve this problem?

# Answer
You have to use image styles to get all the images the same size.

Goto **Admin -\> Configuration -\> Media -\> Image styles**

Create new image style & enter style name with a scale and crop with exact dimensions for your slideshow.

Then go back to your views slideshow setting and select **your style name** as image style.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Core Update: Which Is Safer, Patching or Drush?
We have a number of production sites (mostly on one AWS instance) that require an update of Drupal Core from 7.34 to 7.35.

I have tested an update on one development instance using the following drush command:

# drush up drupal

I also have tested an update on another development instance using a patch from this site: http://fuerstnet.de/en/drupal-upgrade-easier The commands were:

# patch -p1 --dry-run \< drupal-7.34-to-7.35.patch

# patch -p1 \< drupal-7.34-to-7.35.patch

There are no db updates involved.

It seems to me that on the one hand, drush backs up the core files but on the other hand, the patch is faster.

So, which would be safer?

# Answer
At the end of the day, by whatever method you use, what you have accomplished is changing the code on your Drupal site. In theory, both methods you mention should produce the same result.

What I recommend is that you first upgrade and test on a dev machine, and then, once you have tested everything and are convinced that the set of code files that you have is correct, move those exact files to production. There are a number of ways you can do that. Some people like to commit all of the files to git, and then use git push / git pull to deploy. Rsync is another common way to move the code files over. Then, you just need to run updatedb (unless you determined in testing that there are no updates required), and bring your site back online.

So, in summary, "safer" depends on your deployment plan, not your upgrade technique.
> 1 votes

# Answer
My website is still "down" (Internal Server Error 500) Because of updating with drush. I have no idea how to solve this, as I have already copied back all the files from the backup and it's still not working.
> 0 votes

---
Tags: drush, updating, version-control
---


# Question
Title: How to use $language array in region--header.tpl.php
I am using Language Switcher Dropdown module for language selection.

Successfully implemented this module and also get `$language` array properly in `page.tpl.php` file based on language selection.

But I am not able to get `$language` array in `region--header.tpl.php` file.

So how can I use this array in region files ?

# Answer
> 1 votes
`$language;` is a global variable in drupal 7. You can get this variable in `region--header.tpl.php` as shown below:

```
global $language;

```

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


title: where is the fault in my join?

text:
# Question
Title: where is the fault in my join?
```
$query = db_select('watchdog', 'wa');
$query->join('distinct', 'di', 'di.wid == wa.wid')
  ->orderBy('wid')
  ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
  ->range(0, 20);
$result = $query->execute();

```

It shows me the error: Call to a member function orderBy() on a non-object in

# Answer
You have join the `distinct` table with `watchdog`. So the all result of watchdog will be displayed and the matching record of distinct table. So try changing query like :

```
$query = db_select('distinct', 'di');
$query->join('watchdog', 'wa', 'di.wid == wa.wid')
  ->orderBy('wid')
  ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
  ->range(0, 20);
$result = $query->execute();

```
> 0 votes

---
Tags: 7, database
---


title: See data completeness in Drupal?

text:
# Question
Title: See data completeness in Drupal?
I am using Drupal basically to store a ton of info on various topics. The problem is, we add data slowly over time.

I would like to get a report that shows which nodes have the least content. I.e. The most empty fields. This way, I can tackle those with the least amount of data first. Is this possible with Drupal?

# Answer
> 3 votes
It seems you're looking for the Content Complete module

> Content Complete is a CCK extension module that allows to tag CCK fields needed for completion (CCK Complete). The module checks the tagged fields against the content provided for those content types, and computes a complete percentage that can be shown to the user.

Image from the project page

Similar module is Field Complete

> In some situations you want to mark an entity field to indicate it should be completed but not enforce its completion at that time. This module extends the choice between Required and Not required to "desirable" completion.

# Answer
> 1 votes
You can use Profile Complete Percentage module also.

> This module allows administrators to select profile fields as mandatory for a user to achieve a 100% profile completeness status.

---
Tags: 7, log-messages
---