title: Get the url of image field

text:
# Question
Title: Get the url of image field
I am using this solution to print the image for a node in the html.tpl.php file. This works, except it has the full markup. I need just the url for the image. Any ideas of how to print this out?

For instance, I am using this:

```
 if ($node = menu_get_object() ) {
  if ($node && isset($node->nid)) {
    $node = node_load($node->nid);
    node_build_content($node);
    $variables['field_image'] = render($node->content['field_image']);
     }
   }

```

# Answer
> 3 votes
If you just want the path to the original file you can use file\_create\_url() like this:

```
if ($node = menu_get_object()) {
  if ($items = field_get_items('node', $node, 'field_image')) {
    $variables['field_image_path'] = file_create_url($items[0]['uri']);
  }
}

```

Note that I've done away with some redundant if statements, the extra node\_load (the get object call already loads the node) and the building of the node content.

If you want to use an image style insead of the original image you can use image\_style\_url() like this:

```
if ($node = menu_get_object()) {
  if ($items = field_get_items('node', $node, 'field_image')) {
    $variables['field_image_path'] = image_style_url('style_name', $items[0]['uri']);
  }
}

```

If you wanted to get the image style from the content type display settings you can do this using field\_info\_instance() like this (this example assumes a content type called "article" and a display mode of "default"):

```
if ($node = menu_get_object()) {
  if ($items = field_get_items('node', $node, 'field_image')) {
    // Set a default style name as fallback.
    $image_field_style = 'original';
    // Use the image style from the field settings if we have it.
    if ($image_field_instance = field_info_instance('node', 'field_image', 'article')) {
      if (isset($image_field_instance['display']['default']['settings']['image_style'])) {
        $image_field_style = $image_field_instance['display']['default']['settings']['image_style'];
      }
    }

    $variables['field_image_path'] = image_style_url($image_field_style, $items[0]['uri']);
  }
}

```

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


# Question
Title: I'm creating a form in a module but when I try to add a radio group the title displays but not the options
```
$form['todo'] = array(
'#type' => 'fieldset',
'#prefix' => '<div id="todo">',
'#suffix' => '</div>' . $image,
'thot_dialog' => array(
  '#type' => 'fieldset',
  '#prefix' => '<div id="thot_dialog">',
  '#suffix' => '</div>'
),
'add_thot' => array(
  '#type' => 'fieldset',
  '#prefix' => '<div id="add-thot">',
  '#suffix' => '</div>',
  '#title' => t('Add New Thot, Related to Current Thot'),
  'new_thot_nid0' => array(
      '#type' => 'hidden',
      '#default_value' => "",
  ),
  'new_thot_name' => array(
      '#type' => 'textfield',
      '#title' => 'Name Your New Thot:',
      '#default_value' => 'Type Name Here',
  ),
  'new_thot_rel' => array(
      '#type' => 'select',
      '#title' => 'Select One:',
      '#options' => $t_rels,
  ),
  'new_thot_reverse' => array(
      '#type' => 'checkbox',
      '#title' => 'Reverse the direction?',
      '#attributes' => array('#id' => 'new-thot-reverse'),
  ),
  'new_thot_options' => array(
      '#type' => 'radios',
      '#title' => 'Choose One',
      '#title_display' => TRUE,
      '#options' => array(0 => 'Create the Thot', 1 => 'Edit the Thot (Add text, etc.)'),
      '#access' => TRUE,
      '#default_value' => 0,
  ),
  'new_thot_submit' => array(
    '#type' => 'submit',
    '#value' => 'Submit Thot',
  ),
);

```

# Answer
Your `#options` setting only has keys, but no values. You need something like

`'#options' = array(0 => t('Closed'), 1 => t('Active'));`

Example from Radios form API reference.
> 1 votes

# Answer
It looks like you're dealing with Drupal 7. Take a look at the Form API Reference for the radios element type.

Make sure **#access** evaluates to `TRUE` if you want to have it display on the page.
> 0 votes

# Answer
I ran this in a test module:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['todo']['add_thot']['new_thot_options'] = array(
    '#type' => 'radios',
    '#title' => 'Select One',
    '#title_display' => TRUE,
    '#options' => array('a','b','c'),
  );
}

```

And this appears on all forms (as it should):

You have something else going on here outside of this code snippet I'm afraid. Could you give us more code to look at possibly?

Another idea would be to run that exact same test and see if that appears on your Node Edit forms. If it does, then something else is happening in your custom form that's breaking the radio.
> 0 votes

# Answer
I know this is a little far fetched, but have you tried putting your keys in ''?

Like:

```
    'new_thot_options' => array(
      '#type' => 'radios',
      '#title' => 'Choose One',
      '#title_display' => TRUE,
      '#options' => array('0' => 'Create the Thot', '1' => 'Edit the Thot (Add text, etc.)'),
      '#access' => TRUE,
      '#default_value' => '0',
),

```

Like I said, a little far fetched.
> 0 votes

# Answer
This is very old, but I have had the exact same issue / symptoms. I forgot to use `drupal_get_form`, in my case it was not looking as this :

```
$block['content'] = drupal_get_form('my_form');

```
> 0 votes

# Answer
i am getting the option for radio buttons. please check the above code or provide more detail what you want to achieve.

and you are missing one closing bracket for below code

```
'add_thot' => array(
  '#type' => 'fieldset',
  '#prefix' => '<div id="add-thot">',
  '#suffix' => '</div>',
  '#title' => t('Add New Thot, Related to Current Thot'),
  'new_thot_nid0' => array(
      '#type' => 'hidden',
      '#default_value' => "",
  ),

```
> -2 votes

---
Tags: 7, forms
---


title: Cache API troubleshooting

text:
# Question
Title: Cache API troubleshooting
I'm trying to cache an object returned after a 3rd party API call via HTTP. The API charges based on calls, so I'm trying to cache the information returned for some period of time.

However I don't seem to be able to get cache\_set() to ever store anything. I've enabled "Cache pages for anonymous users" and "Cache blocks" in the performance configuration, as I read somewhere that the cache API may depend on those being set.

I'm using code inside a function called in hook\_block\_view():

> $cache\_key = 'custom\_module'.$index;
>
> $conditions = cache\_get($cache\_key);
>
> if (!$conditions) { $conditions = API\_CALL($index); cache\_set($cache\_key, $conditions, 'cache', REQUEST\_TIME + (60 * 10)); //stores in cache table and expires after 10 minutes }

However this still results in an API call per page load with testing from a logged out browser. I added some minimal test code:

> cache\_set('testing','foo','cache',CACHE\_PERMANENT);
> var\_dump(cache\_get('testing'));

And the output is "bool(false)".

Looking in the database shows the 'cache' table is empty.

I'm about to start digging through the function calls being cache\_set() to see what is happening, and intend to report back what I find. However if this is a common problem perhaps someone already has an answer?

# Answer
> 0 votes
I'm an idiot, and I had configured up the DrupalFakeCache earlier in development to prevent caching. Clearly this results in no caching.

---
Tags: 7, caching
---


title: Omega theme is not adding livereload.js

text:
# Question
Title: Omega theme is not adding livereload.js
I'm setting up Omega 4 using SASS / Compass for the first time, I have:

* Linux VM running apache and guard
* Windows machine for code editing and browser

Whatever I do I cannot find livereload.js in the page source.

* Guard is running fine
* I have cleared the cache several times
* I can view the script at `ip.ad.dr.ess:35729/livereload.js` and at `my_site.com:35729/livereload.js` in my browser
* I've tried changing the settings at `admin/appearance/settings/my_theme` to various different things but I don't think that makes a difference if the script is not included in page source

Any *gems* of wisdom would be greatly appreciated.

# Answer
> 1 votes
From what it seems, your website is probably looking for the file in the wrong location. Or it may be overriden by another module. Where and how is the file specified in your theme?

Meanwhile, here's what I would do to track down the issue.

# Enable Error Logging

This way you can see the errors happening in the backend, such as Drupal attempting to fetch a file from a wrong directory.

1. Make sure the `Database logging` module is enabled, it manages Drupal related errors.
2. Check the log messages for errors (`/admin/reports/dblog`).
3. If you still do not see an error, you might need to login as an admin. If you're not an admin, adjust permissions.
4. Enable PHP `display_errors` and `log_errors` to log errors on the PHP side. You can then check the log file to see which error is being thrown. You may need to create a `phpinfo.php` file to see if the error log is enabled and the location of the error log.

# Disable Caching

Sometimes the way caching works, may interfere with your setup. It also helps you see every `*.js` file that is called.

1. Make sure you do not have any other 3rd party caching modules enabled, e.g. Boost.
2. Make sure you have all caching disabled, including `Aggregate JavaScript files.` (Not CSS Aggregate) and `Cache pages for anonymous users` (`/admin/config/development/performance`).

# Try Alternative Solutions

This doesn't necessarily fix the issue, but may provide a solution for the time being.

1) Attach javascript in `template.php`

```
<?php
  function MYTHEME_preprocess_html(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/script.js', 'file');
  }

```

2) Attach javascript in `page.tpl.php`

```
<?php
drupal_add_js(path_to_theme().'/js/script.js');

```

3) Attach javascript in `html.tpl.php`.

I would try to avoid this option, since it's the least Drupal way, and you might not be able to use drupal\_add\_js(). But if you have to, you can specify the script, by putting the following between your `<head></head>` tags.

```
<script type="text/javascript" src="path/to/file/scripts.js"></script>

```

# Check Module by Module

As a last option, I would make a new install of the website and see if everything works there. If it doesn't, it's more likely that there's a bug in the few modules that you have installed. If everything does work with the new installation, then the problem is in your website; so duplicate the original site and uninstall modules one by one to see what's causing the issue.

There are many other ways you can crack down the problem, by installing a Devel Module and passing `dpm($variable)` throughout files.

Hope it helps!

# Answer
> 1 votes
Livereload will only be added to the page if the Drupal instance can reach out to the livereload.js specified. Note that loading it in your browser (remotely from the server) is different than Drupal loading it from the machine. Drupal is running under Apache as a process on the machine. What it sounds like is Drupal/Apache/PHP cannot access the settings you have in Omega.

If you are familiar with Linux command line. Log into the machine and attempt to load the livereload.js file using wget from the machine using the exact URL you are using in Omega. If you do not get a return, you have found the problem.

# Answer
> 0 votes
Check if the protocol of the website as you view it and the url that points to livereload.js are the same. They should be both the same either HTTPS or HTTP.

---
Tags: theming
---


# Question
Title: Views list with picture as left, title and content as right
How to make such a layout as on example screenshot? Picture on left, Title and truncated content on right.

What view format i need to use?

# Answer
I have achieved this by setting up my view in this way.

**View format:** ***Grid***

**View show:** ***fields***

In settings for Grid view select ***no. of colums*** to 1

After adding your required fields, suppose image, title, description. Add one more field **Global:custom text**

Make sure this field should be the last field. And '***exclude from display***' all fields except **Global:custom text** field

Now I added this into the custom field

**CSS Style:**

```
.custom-left, .custom-right{
  float:left;
}

```

You can add more fields and style them accordingly. Hopes this will help you to get exactly what you want.
> 1 votes

# Answer
If you are just trying to create a layout for a node, not a view, then take a look at Display Suite. You can choose a simple layout in the settings e.g Header with left and right columns, then drag and drop which node fields you want into those areas.

There are lots of good help videos too.
> 1 votes

# Answer
You want to create a new view of View type = Node. Then

1. Add a Page display
2. Filter the nodes you want to display, eg. Node Type = article
3. Add the fields you want to display, eg. Image, Title and Teaser
4. Specify the path of your new HTML page.
5. Save

Now you just edit the CSS in your theme to float the image left, and the title and teaser will appear on the right. I use the CSS Injector module to quickly specify the required CSS.

I would also use the Imagecache module to automatically create the appropriate size of image, that is selected in your View image field.

If you were lazy, you could specify a display style of Table, to place the image in the left column, and the Title and Teaser in the next column, but this wouldn't be mobile freindly.
> 0 votes

---
Tags: views
---


# Question
Title: How do you use tabledrag API in a multi-page environment?
As you can see in the image below, I'm using `drupal_add_tabledrag` to allow admin to sort node order by dragging. But how do I drag the items from one page to another? Is there additional Drupal API, or if not, how would you go about this?

There can be hundreds of nodes, I cannot fit them on a single page.

# Answer
I doubt anyone else will have a useful answer. But the DraggableViews module for Drupal 6 showed 3 items from the previous and next Page(s) in paged results. Allowing you to drag an item from the previous page into the previous or next page.

Now if you have hundreds of items I'm not sure how you would skip multiple pages at once -- but looking at how they did this could help you to extend the Drupal 7 Draggable Views module to achieve the functionality you want.

Unfortunately the Drupal 7 DraggableViews does not support this yet.

Proof of this is in this issue queue: https://www.drupal.org/node/1458870
> 1 votes

---
Tags: 7, paging, forms
---


# Question
Title: Service request with OAuth (Invalid signature error)
I'm making a service request(POST) with curl and OAuth signature.

I have created a signature with the following code:

```
$signature_method = new OAuthSignatureMethod_HMAC(strtolower('SHA1'));

$consumer = new DrupalOAuthConsumer($consumer_credentials['c_key'], $consumer_credentials['c_secret'], array());

$request = DrupalOAuthRequest::from_consumer_and_token($consumer, NULL, $options[$op]['method'], $options[$op]['url'], NULL);

$request->sign_request($signature_method, $consumer, null);

```

And added to the curl header the OAuth credentials. The problem is that when on the server side the signatures don't match. For example on the server:

> rsXZTiGBRYU+8WjxfnxZQ1g3IPA=

and client:

> rsXZTiGBRYU 8WjxfnxZQ1g3IPA=

and because of this it's giving me an "Invalid signature" error. I think it's related to some encoding but can't figure it out.

Anybody has any ideas as to what should I do?

# Answer
> 0 votes
The solution to my problem was the way i was sending the signature in the header of the curl method:

```
$oauth_signature = $request->get_parameter('oauth_signature');

$header = array('Authorization: OAuth '
    . 'oauth_consumer_key="' . $consumer_credentials['c_key'] . '", '
    . 'oauth_nonce="' . $oauth_nonce . '", '
    . 'oauth_signature="' . urlencode($oauth_signature) . '", '
    . 'oauth_signature_method="HMAC-SHA1", '
    . 'oauth_timestamp="' . $oauth_timestamp . '", '
    . 'oauth_version="1.0"');

```

I had to **urlencode** the signature before sending it.

---
Tags: services, authentication-authorization
---


# Question
Title: How to display search query in view's results page?
I'm using views 3 with drupal 7.

I have a views page listing content of a certain content type 'Clothes'. I have a exposed form(in a block) that filters this list by size(small,medium,large) and color(red,blue).

When I click submit, is it possible to show in the header of my results page like the following?

> Showing results for Small size and Red color:

# Answer
> 1 votes
Yes, ultimately all the filters send the data using HTTP methods GET/POST. If you are not using AJAX with views then HTTP method GET is used to send the data.

To display the information in header add *Global:Custom Text field* and add below line in it.

```
<div>Showing results for $_GET[X] size and $_GET[Y] color.</div>

```

Where : X - name of size field Y - name of color field You will get the names from the url generated after search in address bar.

# Answer
> 0 votes
I'm not aware of a simple way of doing this with *exposed* filters. *Contextual* filters, or arguments, on the other hand, have an option for this, that allows you to use tokens to set the title like

> Showing results for \[size\] size and \[color\] color

but that would on the other hand require you to find a different way of showing the exposed filters.

The easiest way I can think of to solve this, is to have *both* exposed and contextual filters. After that a form submit hook could do

```
$path_to_view = 'store/';
drupal_goto($path_to_view . $_GET['id_of_filter_1'] . '/' . $_GET['id_of_filter_2']);

```

to create a redirect from the exposed filters to the contextual ones. This way you could get the best of both worlds.

# Answer
> 0 votes
I don't know whether this will help you or not but you can try this, For the title of the expose filter result you can try to add in between `Global: Result summary` or `Global: Text area` from `add header` and the expose filter call the `views_exposed_form` on result use the

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id=='views_exposed_form')
    {
        $form['#submit'][] = 'call_ur_form_state_function';
    }
}

function call_ur_form_state_function($form, &$form_state){
    //dpm($form_state);
}

```

to alter the `$form_state` value, there you will get the all array and object of the current view to alter, by this way probably you can reconstruct your string for output page.

---
Tags: 7, views
---


# Question
Title: Two different sites, two installations, no database or core sharing
I've finished configuring a Drupal site using localhost (Mamp) but I have to wait some weeks until it gets uploaded to external host.

Now in the meantime I'd like to start developing another site that has nothing to do with the first one (different database, users, modules, etc). That is: I'd like to 'park' the old site and start creating the new one (new Drupal 7 installation) without affecting the first one.

I'm using Mamp 3.0.7.2 and the server route is default (Mamp--- htdocs)

Any hint on what to begin with?

Thank you

# Answer
> 0 votes
1. put your drupal sites in separate subdirectories of htdocs, e.g .../htdocs/site1, ...htdocs/site2
2. access your sites using the mamp localhost url, e.g. `http://localhost/site1`

If you know how, you can also create virtualhosts in /Applications/MAMP/conf/apache/httpd.conf and edit /etc/hosts on your mac, so that you can access the sites with whichever url you choose, such as:

```
http://site1.local

```

Databases: just upload your databases using MAMP's phpmyadmin, and edit your sites' settings.php to use the respective databases.

---
Tags: installation, multi-sites
---


# Question
Title: Drupal 7 - How to loop foreach in multiple value in custom view
I'm customizing a view (in views-view--myview.tpl.php) based on a node which has a field with multiple value (field\_galerie\_image).

I'm trying to list in a foreach loop that particular field, and I am wondering how to write it down.

In the following code, I can access a value with `$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"];` but I need to loop through it.

```
$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][1]["filename"];
$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][2]["filename"];

```

The code I am using is the following one.

```
<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php print $vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"]; ?>
  <?php endif; ?>
<?php endforeach; ?>

```

# Answer
I found it out; the correct code is the following one.

```
<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php foreach ($vue->_field_data["nid"]["entity"]->field_galerie_image['und'] as $val): ?>
      <?php print $val['filename']; ?>
    <?php endforeach; ?>
  <?php endif; ?>
<?php endforeach; ?>

```
> -1 votes

---
Tags: views, entities
---


# Question
Title: How to set up a 'review-like' view that connects users to nodes?
I want to be able to add to my panel, described here, a view of an 'advocate' that 'endorses' an item.

Each item (unique by NID) has one Advocate (a user, unique by UID) and each User can have multiple endorsements (but still one per item).

In my view I have these settings:

Click to view

I've annotated them to show how I think things link together

* NID from the URL connects to the, 'Entity Reference: Endorsement'.
* The Entity Reference: Endorsement connects to the '(Content entity referenced from field\_tech\_endorsement) Entity Reference: Endorser'.
* The (Content entity referenced from field\_tech\_endorsement) Entity Reference: Endorser connects to the 'User: Name (Name) and User: Picture'

These settings all seem 'right' to me. but I'm getting no output on my panel.

I think the crux is in the Argument input, that it feeds from the NID selected on the panel (see link), and the UID of the associated (via the relationship `Entity Reference: Advocate`). But I don't know if I'm doing the 'feeding' right at all.

Nothing comes up on the preview, and nothing come up on the page.

This is what I'm hoping for:

What am I doing wrong on this view? Is my set up right at all?

What I'm trying to do is reflect this set up:

Here is the SQL generated by the query.

```
<!-- lang-sql -->

SELECT      node.nid AS nid, #The node of the item that has this endorsement (?)
            users_field_data_field_endorser.name AS users_field_data_field_endorser_name, #The username of the advocate who has endorsed the item
            users_field_data_field_endorser.uid AS users_field_data_field_endorser_uid, #The UID of the advocate who has endorsed the item
            users_field_data_field_endorser.picture AS users_field_data_field_endorser_picture, #The picture of the advocate who has endorsed the item
            users_field_data_field_endorser.mail AS users_field_data_field_endorser_mail, #No idea why this is generated
            node.created AS node_created, #No idea why this is generated
            'node' AS field_data_body_node_entity_type #No idea what this is
FROM
            {node} node #A Table of all nodes?
LEFT JOIN   {field_data_field_tech_endorsement} field_data_field_tech_endorsement ON
                    node.nid = field_data_field_tech_endorsement.entity_id AND
            (field_data_field_tech_endorsement.entity_type = 'node' AND
            field_data_field_tech_endorsement.deleted = '0')
            #Left Join our endorsements, where they're not deleted, and they're NID matches their NID (well duh)
LEFT JOIN   {node} node_field_data_field_tech_endorsement ON
                field_data_field_tech_endorsement.field_tech_endorsement_target_id = node_field_data_field_tech_endorsement.nid
             #Left join on Where the NID of the target matches the endorsement (????) That's not right
LEFT JOIN   {field_data_field_endorser} node_field_data_field_tech_endorsement__field_data_field_endorser ON
                node_field_data_field_tech_endorsement.nid = node_field_data_field_tech_endorsement__field_data_field_endorser.entity_id AND
                (node_field_data_field_tech_endorsement__field_data_field_endorser.entity_type = 'node' AND node_field_data_field_tech_endorsement__field_data_field_endorser.deleted = '0')
              #Left join on the endorser/advocate where the Endorsements NID is the same as the NID of the endorser/advocate's endorsement AND where the endorserment is endorsing the right kind of node, AND where the endorser is not deleted
LEFT JOIN   {users} users_field_data_field_endorser ON
                node_field_data_field_tech_endorsement__field_data_field_endorser.field_endorser_target_id = users_field_data_field_endorser.uid
            #Left join on the user details that match the endorser
WHERE (( (node.nid = '13' ) )AND(( (node.status = '1') AND (node.type IN  ('endorsement')) )))
ORDER BY node_created DESC
LIMIT 1 OFFSET 0

```

I think my understanding of what it's doing it right, but it seems like what it's doing is wrong. What do I do to fix it?

# Answer
> 3 votes
I've created these types:

* Item (node) : has entity reference field to node of type endorsement.
* Endorsement (node) : has entity reference field to user (which I guess has role advocate in your case)

The View: Base table of nodes, filtered by type 'Endorsement'

Two relationships:

1. A bridge to the Content entity that is referencing Content via field\_endorsement (as we have nodes of type endorsements in our base table, we need to link it to 'Item'. 'Item' has the entity reference field containing endorsement, hence we go in reverse: ie referencing)
2. A bridge to the User entity that is referenced via field\_advocate (as we have nodes of type endorsements in our base table we need to link it to User. Endorsements has an entity reference to user, hence it is a simple forward relationship, ie referenced)

Now add the Contextual filter of type nid. Set its relationship to 'Content referencing Content from field\_endorsement', which was the first relationship added. The nid we are passing it is of type 'item', hence we must link it via the relationship to 'items'. Set 'hide view' 'when filter value is not available'.

For argument input: From panel argument, First argument.

Add your fields as you want. There is no need to add nid as a field unless you need to do so for a specific reason.

done with the view, back to the panel: add the view to the panel content for the page, and tick 'Send arguments'

---
Tags: 7, views, panels, entities
---


# Question
Title: Faceted Search Block displays values from other facet blocks
I'm using the Faceted Search API (drupal 7) and followed this Tutorial: Part 1 and Part 2

All worked fine but there's a little Problem with the Values each Block displays

"Kategorie" and "Serie" are both showing all selected Fields instead just the related. But if i check one Value, which is not related to the "Kategorie" Field, I don't get any results so the search works fine but displaying the values doesn't.

I deleted all and made the search page from scratch like the tutorial described but i've got the same issue all over again. Also i checked the CSS settings for my facet blocks. Indexing all again didn't help, neither does running Cron again.

Does someone have any clues?

# Answer
I finally got the answer by myself. Never thought it would be such a little setting:

If you're going to index a "text field" (and maybe going to enable the related facet block), make sure the text field is declared as **string** instead of **fulltext**.

Just go to -\> **Search API** \>\> edit the correlating index \>\> **Fields**

and check the textfields. Following this you just have to re-index the items.
> 0 votes

---
Tags: 7, entities, blocks, search
---


title: Add value to every user in data field

text:
# Question
Title: Add value to every user in data field
I'd like to do simple thing, but because of drupal serialized data field don't know how to. I'd like to set for every user a variable in "data" field, I do it manually when user edits its profile, like this:

```
$edit['data']['profile_bg_active'] = 1;

```

I want to do it now for all users, so the "profile\_bg\_active" exists in every user data field.

The code I am using is the following one.

```
$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->execute();

foreach ($updateAllDudes as $dude) {
  $existingUser = user_load($dude->uid);
  $edit = array();
  $edit['data']['profile_bg_active'] = 1;
  user_save($existingUser, $edit);
}

```

I get the following error in the log:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, name, pass, mail, theme, signature, signature\_format, created, access, login, status, timezone, language, picture, init, data)\`

It seems it is creating new users instead of updating the existing ones.

# Answer
This is because you're not filtering the users when you grab them using `db_select`. This will also grab the "Anonymous" user (uid 0). When you try to save that user, this error happens most likely. Putting a simple `if(!empty($dude->uid))` within your foreach loop should fix this issue. Or excluding uid 0 from your db\_select query using the NOT EQUALS `condition` like so:

```
$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', 0, '<>')

```

Or by using the NOT IN condition:

```
$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', array(0), 'NOT IN')

```

See here

> if you need to edit all users (I am setting a default value for a custom field), you need to strip uid=0 from the list and deal with it as a special case.
> 1 votes

---
Tags: entities, users
---


# Question
Title: Access to preprocess variables in a custom block
I have created a custom block to display some contact information.

I have a preprocess function that sets a contact variable like so:

```
function atstump_preprocess(&$vars, $hook) {
    $vars['contact'] = array(
        'name' => 'Doug Gillum',
        'business' => 'Portland Stump Grinding',
        /...
    );
}

```

I enabled the PHP filter, and set this as the text:

```
<ul>
  <li><?php print $contact['name']; ?></li>
  <li><?php print $contact['phone']; ?></li>
  <li><?php print $contact['email']; ?></li>
</ul>

```

However it doesn't recognize $contact as a proper variable and generates the PHP error E\_NOTICE:

```
Notice: Undefined variable: contact in eval() (line 2 of C:\xampp\htdocs\stumpgrinding\modules\php\php.module(75) : eval()'d code).
Notice: Undefined variable: contact in eval() (line 3 of C:\xampp\htdocs\stumpgrinding\modules\php\php.module(75) : eval()'d code).
Notice: Undefined variable: contact in eval() (line 4 of C:\xampp\htdocs\stumpgrinding\modules\php\php.module(75) : eval()'d code).

```

Is it even possible to access the preprocess variables in a PHP filter? if not, is there a better way than hard coding them? maybe `variable_set` and `variable_get` and how would I set that up via the theme, I'd rather not make a module for this.

# Answer
> 2 votes
It won't work.
If you use a preprocess function, the variables will be available in the template of the block.

I think that, in your case, you should edit the settings.php file and add the following line:

```
$GLOBALS['email1'] = 'example@email.com';

```

You'll be able to use the variable `$email1` through the whole site.

Have in mind that it's not a good Drupal practice.

# Answer
> 1 votes
Another alternative is to **add variables** in the **site information** variables table using the hook hook\_form\_FORM\_ID\_alter as follows:

```
function mymodule_form_system_site_information_settings_alter ( &$form, &$form_state ) {
    $form['contact'] = array(
        '#type' => 'fieldset',
        '#title' => t('Contact'),
    );
    $form['contact']['contact_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Contact name'),
        '#default_value' => variable_get('contact_name', ''),
        '#size' => 40,
    );
}

```

Then in the **php filter** input you can get these variables using:

```
<?php echo variable_get('contact_name', '');?>

```

---
Tags: 7, blocks, theming
---


# Question
Title: how does context mobile detect module work?
I cant find the documentation as to how to use the context mobile detect module. Is it used the same as the mobile detect module? With these parameters?

```
$detect = mobile_detect_get_object();
  $is_mobile = $detect->isMobile();

```

https://www.drupal.org/project/context\_mobile\_detect doesnt have any documentation

# Answer
> 1 votes
I am the author of Mobile Detect. The modules have two different goals.

Mobile Detect is primarily for coders, hence functions like `mobile_detect_get_object()`. There is also support for using the detection rules via ctools (because I was developing a Panels based site at the time). There is also some simple support for making this available in preprocess functions.

Context Mobile Detect creates mobile/tablet/desktop contexts (ie, it integrates with the Context module). So, if this is the approach you want to take, either use the Context UI for creating and using your contexts, or use the Context API in your own code.

---
Tags: 7
---


# Question
Title: Modal form with CTools opened in several different pages
I have a working module which opens a modal form with CTools. However, I must use the URL example.com/mymodule/page . There the module creates the link which opens the modal window with the form. How can I use the link in other pages? I have tried to just put the link and it does not work, it redirects to the page of the link (example.com/mymodule/nojs/) instead of opening the modal window.

# Answer
I have finally solved the problem and now everything works: the modal window, the form and the submit, sending the email in final step. The problem was that the raw URL included the class **ctools-use-modal-processed** and apparently that simple css was making it not work. Now more or less understand the process, thank you for your help, it has been very valuable.
> 0 votes

---
Tags: chaos-tool-suite
---


# Question
Title: Migration failed with source plugin exception
I'm getting the following error:

```
Migration failed with source plugin exception Migration failed with source plugin exception: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'posmsoftllc' for column 'sourceid1' at row 1

```

I can't figure out why I'm getting this error.

It has something to do with my MigrateSQLMap - there's no real primary key on the source database, but I suppose username would probably work. I've got the MigrateSQLMap setup as follows:

```
$this->map = new MigrateSQLMap($this->machineName, array(
  'Username' => array('type' => 'varchar',
    'length' => 75,
    'unsigned' => FALSE,
    'not null' => FALSE,
  )
    ), MigrateDestinationEntityAPI::getKeySchema('commerce_line_item', 'recurring')
);

```

But I'm receiving this error - what could be causing this? Why is it expecting an integer value? Do I even need this map for a successful migration?

# Answer
I find when I get these errors it is because initially I make an sqlmap using an integer key -- then see I don't have an integer key and try to change it. The migration still expects the *initial* configuration of an int key. You likely have to clear it out as seen in this issue comment.

> Everything looks OK to me. Is it possible that when you initially defined your migration, you had an integer key in the MigrateSQLMap call? Changing the key in the code will not automatically change the associated tables. What you can do is:
>
> 1. Rollback the AttSubject migration, so the map and message tables are empty.
> 2. Drop the migrate\_map\_attsubject and migrate\_message\_attsubject tables.
> 3. Run "drush ms". This should call the ensureTables() method and recreate the map and message tables using your ca\_varchar1 key schema.
> 4. Check the structure of the map and message tables and make sure sourceid1 is a varchar in both.

Also see this issue which describes the same problem and solution with more examples/details.
> 1 votes

---
Tags: 7, database, migrations
---


# Question
Title: Expose some administrative functions on the front-end
I'm developing a web-app for managing non-profit organizations by extending the functionality of the Drupal CMS. What I want is to have only one administrator account (call it super-admin if you prefer), which should be used only by the developer, next there will be a set of roles (coordinator, director, employee).

The idea is that non of those should be able to perform administrative tasks that may broke the site functionality (like managing blocks or menus), but not just that, to provide a cleaner and more compact interface I would like to expose some functions of the admin side to the front-end (accessible only for determined roles), for example, the coordinator should be able to change the role of an employee in order to upgrade him to director.

Is that possible?

# Answer
> 0 votes
Your question is a little broad -- *anything* is possible given time, effort and perseverance!

I find the Role Delegation module and similar modules help to give out permissions to trusted users.

I also have been creating an Administrative Panel page using the Panels module with embedded Views and Blocks for centralized site admin options for users. I usually call this page the `staff dashboard` for my admin-type users.

Without specific problems you're having, these general tips are all I can provide. Happy coding!

---
Tags: 7, users
---


# Question
Title: How can I export all my blog posts as CSV?
I'm migrating my website from Drupal to WordPress, and the only content I have left to migrate over are all my blog posts.

From my research, the easiest way to do this would be to export my blog posts from drupal as a CSV and then import the CSV file to my Wordpress site.

However, I'm having trouble figuring out how to export ALL my blogposts. The only thing I've managed to find (from myPhP Admin) is 'content\_type\_blog.' However, that only gives me the 'front page tease' and not the whole blog post.

Where can I find ONLY my blog posts to export?

# Answer
If I was going to try to create a CSV of my sites content I would try to use the Views Data Export module and filter on your `blog` content type and include all the fields you want.

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft XLS
> * Microsoft DOC
> * Basic TXT
> * XML
> 2 votes

# Answer
If you want to do it with PHPmyAdmin: Browse to the database, select SQL tab and enter:

```
Select t1.nid, t1.vid, t1.title, t2.body_value from `node` as t1 left join `field_revision_body` as t2 ON t1.vid = t2.revision_id where t1.type = 'blog'

```

That will get you the title and body - if you want dates those are also recorded in those tables so easy to get with minor editing of that SQL statement.

Then run it (click `GO`). Then to export as CSV scroll to the bottom of the page and click Export.

That'll take you to the Export page with that query as the source and you can then select any export format that PHPMyAdmin Supports.
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: Connecting views to another Drupal database
I have a need to display views using an old Drupal database. These views are already created, so I exported them and dropped the export code into a custom module `hook_views_default_view`, put in the necessary `return`, changed the view name, updated the paths, etc. So, now I have two Views showing exactly the same dataset.

I need the newly created one to query against an old database; both databases have exactly the same structure. I have the old database setup in settings.php and, I thought, all I needed to do was add `$view->database = "oldlife"`. That's not working - I'm getting the exact same data in both views (two different paths).

This is the code, minus all the handlers and unnecessary stuff:

```
function lwg_old_db_views_api() {
    return array(
            'api' => 3,
            'path' => drupal_get_path('module', 'lwg_old_db'),
    );
}

function lwg_old_db_views_default_views() {
    $view = new view();
    $view->name = 'commerce_vbo_views_orders_oldlife';
    $view->description = 'Display a list of orders for the store admin.';
    $view->tag = 'commerce';
    $view->database = 'oldlife';
    $view->base_table = 'commerce_order';
    $view->human_name = 'Orders';
    $view->core = 0;
    $view->api_version = '3.0';
    $view->disabled = FALSE;
    /**
      * many lines of $handler-> stuff
      */
    $handler = $view->new_display('page', 'Page', 'page_1');
   $handler->display->display_options['path'] = 'list-all-nodes';
   $views[$view->name] = $view;
   return $views;
}

```

# Answer
It's `$view->base_database`, not `$view->database`.
> 0 votes

# Answer
Have a look at this module, it can do the job for you.

https://www.drupal.org/project/web\_widgets
> 0 votes

---
Tags: 7, views
---


title: Bulk translate a single node

text:
# Question
Title: Bulk translate a single node
Using the Internationalization Module I have configured multiple languages (all English, but different countries). We are using the languages to present variable data on pages but don't necessarily want to translate the body. For example, Canada and the US have different phone numbers and currency but the language is still English and the copy may or may not need to be changed.

For the most part a node is Language Neutral (und) but when we need a single translation for the node, we still need to create the remaining translations as well. This is a lot of extra clicks and we have to do this hundreds of times.

Is there a way to create all of the translations with the click of a button? I spent a good deal of time searching with no luck and any help would be greatly appreciated.

# Answer
After the Language Fallback Module stopped working, I created my own:

Alternative Language

> Allows a language to specify an alternative language so if a node translation for a specific language does not exist, Drupal will try to load the translation for the alternative language before throwing a 404.
>
> This module is useful if you have multiple languages and only one language is typically translated. Rather than create all of the other translations and maintain those, the non-translated languages can load the node from the alternative language.
> 0 votes

# Answer
The Language Fallback Module solved this for me. Rather than translate a dozen nodes, this module allows you to translate only those nodes that require it and have the others fallback to a default.
> 0 votes

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


title: Email validation in a custom module

text:
# Question
Title: Email validation in a custom module
I am using the form API to create forms. How can I validate the email address without needing any separate module? I am just looking for out of the box functionality.

# Answer
> 1 votes
In a custom module, consider using PHP's built function for email validation: `filter_var()`.

```
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
}

```

This code will go into a validation function. A validation function can be added as an element to the form array (see the form API for details) that you linked to. If your module is named *spade*, for example, your form may be in `function spade_form()`. Your submit may then be put in `function spade_form_submit()`, and your validation would be in function `spade_form_validate()`. This is the default handler for validation.

See the following links for more information.

The first example is exactly what you're looking for (and the example that I copied above). The last link contains the examples module, which has a lot of great form examples.

# Answer
> 0 votes
Out of the box the form API for Drupal 7 has the functions listed in https://api.drupal.org/api/drupal/includes%21form.inc/7, which includes `element_validate_integer()`, `element_validate_number()` and `element_validate_positive_integer()` for textfields.

You are free to provide your own element validate function for any form element you wish to provide custom code for, which is not provided by Drupal Core. You do this by providing an `#element_validate` key and creating the custom function. see the official form API documents on #element\_validate.

You can also give in, and install the Email field module.

---
Tags: 7, emails, forms
---


# Question
Title: How to fix active-class problem in minicalendar with calendar / exposed filters
I have a calendar view for events. The events are categorized by taxonomy terms. I use the minicalendar for the selection of days and filter the result list with an exposed list of the categories.

This is all working fine.

But user interface lacks a bit of coherence. There's no indication of which day is picked on the minicalendar (which only has a class for "today").

This snippet helped me getting an "active" class for the datebox, so users can see, which date they have chosen:

```
<?php
function YOURTHEME_preprocess_calendar_datebox(&$vars) {
  $url = $vars['url']; // The (absolute) URL of the item.
  $current = url(request_path(), array('absolute' => TRUE)); // The absolute URL of the page being viewed.
  if ($url == $current) {
    $classes = explode(' ', $vars['class']); // Extract the current classes as a list.
    $classes[] = 'active'; // Add 'active' to the class list.
    $vars['class'] = implode(' ', $classes); // Concatenate and attach the updated class list.
  }
}
?>

```

But here's the problem: when i select a taxonomy term, the url changes from:

```
/myview/2014-11-27

```

to

```
/myview?field_category_tid_selective=8 (e.g)

```

and my active class is gone. How can i achieve that the class stays, even when a filter is active on the results?

Any help appreciated! Thx

# Answer
> 1 votes
Try next, that work without using urls, using *second argument*:

```
function YOURTHEME_preprocess_calendar_datebox(&$vars) {
  $arg = arg();

  // If no second argument provided - that's mean today.
  // Please check how argument date supplied for next day: 2014-12-01 or 2014-12-1 and change date() to appropriate.
  $url_date = empty($arg[1]) ? date('Y-m-d') : $arg[1];

  if ($vars['date'] == $url_date) {
    $classes = explode(' ', $vars['class']); // Extract the current classes as a list.
    $classes[] = 'active'; // Add 'active' to the class list.
    $vars['class'] = implode(' ', $classes); // Concatenate and attach the updated class list.
  }
}

```

# Answer
> 0 votes
You can add extra parameters to a path if you use Page Manager (part of ctools) and Panels.

1. Go to `structure -> pages` in the admin menu (`admin/structure/pages`) and click +add custom page
2. Set the \[Path\] to something like `myview/%selected-date`
3. Set the \[Variant type\] to `Panel`, don't worry about the \[Optional features\]
4. Choose a `one column` layout (for starters at least)
5. In the content area click the cog and choose `add content`

6. Find your view and place it as content

Voila!

Now you can use your current method to set the url to `myview/2014-11-27` and when they choose a filter it will look like `myview/2014-11-27?field_category_tid_selective=8`.

Hope this helps =)

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


# Question
Title: Do I need a custom content type, entity, module or field?
I'm working on a product information manager, and I have a content type of product which needs to reference stock and price levels for each supplier from a different database - these are stored as separate sqlite databases (one for each supplier) and managed outside of drupal.

I would like to reference the prices and stock levels without actually importing them all into the drupal database, instead pulling from the external database, but I'm a little confused how to structure this? One product can have many suppliers.

Do I need a separate entity to manage the pulling of the data (possibly one entity for each supplier) then somehow attach to the product node (manufacturer and part number would be used to search the supplier db), or, would it be considered a field, or a module with options set specifying the database location for each content type. Each product node shouldn't have to specify its list of suppliers.

The data would need to be shown when a node is displayed - I would like the data to be accessible from within views, but also searchable, e.g. display products where stock level \< 3 for supplier xyz.

I'm thinking an entity wouldn't be correct as an input of manufacturer and part number would be needed before the data can be pulled?

# Answer
> 1 votes
> The data would need to be shown when a node is displayed - I would like the data to be accessible from within views, but also searchable, e.g. display products where stock level \< 3 for supplier xyz.

How can you say *I want the data to be integrated into my website -- but not imported into Drupal*. Your goal sounds like alot of work.

You could try something like Remote Entity. But honestly I would take some time to learn the Migrate module and use Rabbit Hole to insert the data as "hidden" data to drupal entities or content types in my site. Migrate is super powerful for this type of syncing of data (*syncing* being a topic I think you're glossing over).

**EDIT**

You could try to:

... all of these in my opinion would be harder to maintain in the long run, rather than a recurring interval of updates or syncing of data using Feeds, Migrate, and storing a copy of the data locally in a drupal friendly format (eg a content type or entity).

---
Tags: 7, nodes, entities
---


# Question
Title: How to add unique classes to FlexSlider slides? (default behavior in v 7.1.x - not in v 7.2.x)
I just upgraded the flexslider module from 7.1.x to 7.2.x and it broke my styling because the old version gave unique classes to each slide (also odd and even row classes to every other slide), but the new version gives each slide the same classes.

I really need to style each slide differently so I was using these unique classes.

This "feature request" is in the module's issue queue but it hasn't been touched in a long time and I lack the skills to fix it myself.

Does anyone know how I can give each Flexslider slide a unique class, either using jQuery, PHP or maybe some other module?

# Answer
OK - I was over thinking this. This script will add id 1, 2, 3 etc to my slides. The slides are just list items - I was all intimidated because only one li is visible at a time, but jQuery doesn't care...

```
/*Script for assigning each flexslider slide a unique class*/
(function($){
$(document).ready(function(){
    $('.slides li').each(function(i,el){
        el.id = i+1;
        });
    });
})(jQuery);

```
> 0 votes

# Answer
You cannot start an ID with a number, which means that Anne's jquery will not work. Instead, assign the li a class - in this case, "slide-1", "slide-2", etc...

(having problems figuring out how to type a code block in this answer - what am I missing?)

/\* --- Each flexslider slide gets it's own class ---\*/ (function($){ $(document).ready(function(){ $('.slides li').addClass(function(i){ return "slide-" + (i + 1); }); }); })(jQuery);
> 0 votes

---
Tags: theming
---


title: Simple LDAP 7.x-2.0-alpha1+3-dev

text:
# Question
Title: Simple LDAP 7.x-2.0-alpha1+3-dev
Is this a stable version? I am having to many troubles trying to configure Simple LDAP 7.x.02. It recognize my domain controller but it doesn't talk to it.

Does anyone has a suggestion to have a better configuration? Or any other module that configure LDAP on Drupal 7 ??

Thanks

# Answer
Looks like you're having a bind issue, I don't know how that module works but did you give it a service account and password to use?

I have used the LDAP module successfully. It has many options so it can look a bit scary but it has very good documentation.
> 1 votes

---
Tags: authentication-authorization
---


# Question
Title: Load Preceding Nodes in a View Block Sorted by Date in Relation to the Current Node
Currently I have a basic View block just showing a bunch of articles in a teaser format. I added this view block to show up below the content of each article page. What I want is to be able to show the preceding articles in relation to the node you are currently viewing by the next future date.

The only extra thing in this view is that I added in contextual filters for NID. I am passing in multiple values into this view block, so YES i do have it "multiple values" checked off.

But I'm not sure why its not working. Technically it should be as it is in fact returning a string of NID's as outputted below:

```
if (arg(0) == 'node') {
  $node = menu_get_object();
}
$curNode = $node->nid;
$curNodeDate = $node->created;

dsm($node);

$type = "article";
$nodes = node_load_multiple(array(), array('type' => $type));

dsm($nodes);

$finalNid = array();

foreach($nodes as $products):
  if( intval($products->created) > intval($curNodeDate)  ){
dsm($products->created .'>'. $curNodeDate .'---'. $products->nid .'~~'. $products->title );
    $finalNid[] = $products->nid;
  }
endforeach;

foreach($nodes as $products):
  if( intval($products->created) < intval($curNodeDate)  ){
dsm($products->created .'<'. $curNodeDate .'---'. $products->nid .'~~'. $products->title );
    $finalNid[] = $products->nid;
  }
endforeach;

dsm(implode("," , $finalNid));

return implode("," , $finalNid);

```

---

When running that code I get the following dsm output:

```
1416508384>1416508382---65~~Rimmel's Georgia May Jagger & COTY partner with DBC
1416508383>1416508382---66~~Daisy Marc Jacobs Tweetshop Grabs the Attention of the Industry
1416508390>1416508382---68~~COTY's Mario Reis
1416508386>1416508382---71~~Beauty Trends for this Holiday Season
1416508385>1416508382---72~~COTY’s Catherine Walsh Honored
1416508388>1416508382---74~~ONE COTY - Looking at COTY as a Whole
1416508387>1416508382---75~~Roberto Cavalli
1416508389>1416508382---80~~A modern story of seduction
1416764226>1416508382---86~~Sir Ken Robinson
1416810455>1416508382---87~~COTY’s Svetlana Omelchenko makes the 2014 Top 100 OUTstanding LGBT Business Leaders List
1413318695<1416508382---2~~philosophy bringing hope & grace to mental health efforts
1413318711<1416508382---3~~Q&A with Ann Gottlieb
1413402303<1416508382---6~~Meet COTY CMO of Skincare
1416508381<1416508382---67~~Spotlight On Leadership: David Booth
1415666899<1416508382---73~~Creative Collaborations: COTY and Avon
65,66,68,71,72,74,75,80,86,87,2,3,6,67,73

```

# Answer
```
<?php

$curnode = menu_get_object();
if (!$curnode) return '';

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('created', $curnode->created, '<=')
  ->propertyOrderBy('created', 'DESC')
  ->range(0, 10); //CHANGE RANGE FOR YOUR LIMITS

$result = $query->execute();

$items = array();
if (isset($result['node'])) {
  $nodes_nids = array_keys($result['node']);
  $nodes = entity_load('node', $nodes_nids);
  foreach ($nodes as $node) {
    $items[] = l($node->title, 'node/' . $node->nid);
  }
}

return theme('item_list', array('items' => $items));

?>

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Create a rule to send confirmation email message after anonymous/authenticated user has created content
I have created a custom content type (CCK) called `apply` (machine name) and installed the **Rules** module. How would I go about sending the user an email (they could be anonymous or authenticated) after they have created content. I understand that I have to create a rule of some sort, could someone please walk me through it?

I want to capture the content of **field\_email\_address** somehow, as that is the field in which the user will be entering their email address.

This is my rule so far, not sure what to put in the **Conditions** and **Elements** section.

# Answer
> 3 votes
1. Rules works with the token module. If you haven't installed it, do so now.
2. In your "apply" content type ("application" would be a better name), ensure that your email field is required, and set the default to use token \[current-user:mail\] so that it fills with the current user's details if they're logged in.
3. "Conditions" is the "if" part of your rule. You use it to narrow down when the rule fires and by whom. Given that you're not needing auth, you can leave this empty. You could test for various node / field properties here e.g. node is published / field has value etc. Because you specified a content type in your "Event", the fields from that content type will become available to the subsequent "Conditions" and "Actions".
4. "Actions" are what happens when you trigger your rule. This is where you specify the email action. Click "Add an action", and from the supplied dropdown, choose "System \> Send mail" or "Send HTML email".
5. In the "to" field, you can now add a token referencing the user email - probably something like \[node:field\_email\_address\]. Click the "Replacement patterns" accordion to see available tokens for each mail param.
6. It you're wanting to templatize & theme your HTML emails, that's possible through other modules (mimemail + mailsystem) but requires a separate discussion.

---
Tags: 7, rules, entities
---


# Question
Title: What is the syntax for using a token on webform confirmation page for Drupal 7 Webform 4
I have an Email field on my webform with the key email\_address. On successful webform submission, I would like to display the confirmation message as.

Further instructions have been sent to xyz@yahoo.com \[Email Address which is submitted on the webform\]

I tried using

> \[webform:val-email\_address\]
> \[submission:values:email\_adddress\]

With no luck. The text format is Safe HTML. Not sure if this is causing that This is on Drupal 7 - Webform version 4.1

Thanks.

# Answer
Use Webform tokens module

> Webform Tokens provides tokens for user form submissions for forms created with the module Webform 3.

But Webform4 has this feature inbuilt, you might try this patch to fix it.

**OR**

You can try writing webform-confirmation.tpl.php to achieve the same.
> 1 votes

---
Tags: 7, webforms, forms
---


# Question
Title: How to disallow users from changing their emails?
I need this because it makes life a bit more difficult for 'professional' spammers who just change their emails after logging in, so that the can use that very email for the next registration, after being blocked.

Appreciate your hints.

# Answer
> 5 votes
You can either force users to confirm email change or protect the email field from changes. Both modules have D6/7 versions. Second module can lock password and some other fields as well.

# Answer
> 2 votes
There is a new module which is made to handle this situation perfectly.

The module User Account Permissions add the following new permissions for user accounts:

1. edit own user account
2. edit own email address
3. edit other user's email address
4. change own password
5. change other user's password

# Answer
> 0 votes
Or try to use Field Permissions module (D6 or D7). set custom permission to allow create but disallow to edit own field..

---
Tags: users, emails, advertising
---


# Question
Title: drupal 7.34 cannot rearrange form component and others
I have a fresh installation drupal 7.34 the install module ctools views and webformm. I cannot rearrange the form component. Both weight and the + symbol appear. Normally in the previous version I can switch using weight or drag the component to rearrange. How can I rearrange the form components. This problem also in other similar list, such as menu.

# Answer
Very lucky...., I found the answer to solve the problem (related to missing misc/jquery.cookie.js) from this discussion https://www.drupal.org/node/1052372

To solve that: Configuration \> Development, enable Aggregrate Javasript file

Now it just works perfectly as in the previous versions. Thanks Drupal developers.
> 1 votes

---
Tags: webforms
---


title: Location map in colorbox

text:
# Question
Title: Location map in colorbox
I am using **'Location map module'** and I have made a block of it displaying my required map. My requirement is to view that map in colorbox when some user clicks on **'Map'** link.

I need to use Location map module only. I tried to achieve above using views but didn't worked.

Can anyone help ?

# Answer
> 1 votes
Found this module Colorbox Node which allowed me to view **Location Map Block** in colorbox.

Follow this simple steps (to show only map block).

* Enable **Colorbox Node** module. (Make sure colorbox module is already installed)
* Create a Basic page and render Location Map Block in content region.
* In this page display only **Location Map Block**.
* Create a **Global:Custom text** or any custom link and add below code as a text in it.

`<a class="colorbox-node" href="/your-path?width=600&height=600">Map</a>`

By this you can render any block which you want to.

---
Tags: javascript
---


# Question
Title: Autofill texfields based on select option in dynamic fieldset
In my custom form i am dynamically generating multiple fieldsets.Each field set has select option(dropdownlist) and textfield generated dynamically. The value for textfield is dynamically generated based on user selected value from select option.

My problem is that if i select species from fieldset2 then density texfield1 in fieldset1 is overwritten and density textfield2 in fieldset2 is empty which is wrong. Each time the ajax callback return value is overwriting textfield1 in fieldset1(Field#1)

```
function fuel_design_tool($form, &$form_state) {
$form = array();
$form['#tree'] = TRUE;

if (empty($form_state[FIELDS_NUM])) {
    $form_state[FIELDS_NUM] = 1;
}

for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++) {

    $form['field'][$i] = array(
        '#type' => 'fieldset',
        '#title' => t('Field #@num', array('@num' => $i)),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,

    );

    $form['field'][$i][FORM_FIELD_SPECIES] = array(
        '#type' => 'select',
        '#required' => TRUE,
        '#title' => 'Choose Species',
        '#options' =>  _load_species1(),
        '#default_value' => 0,
        '#ajax' => array(
             'callback' => 'fuel_design_tool_callback',
             'wrapper' => 'fuel_design_tool-wrapper',
             'event' => 'change',
           )

       );

      $profile = isset($form_state['values']['field'][$i]['FORM_FIELD_SPECIES']) ? ($form_state['values']['field'][$i]['FORM_FIELD_SPECIES']) : NULL;
    $form['field'][$i][FORM_FIELD_DENSITY] = array(
        '#type' => 'textfield',
        '#prefix' => '<div id="fuel_design_tool-wrapper">',
        '#suffix' => '</div>',
        '#title' => t('Density'),
        '#value' =>$profile,

    );
    $form['add_field'] = array(
    '#type' => 'submit',
    '#value' => t('Add More fieldet'),
    '#submit' => array('fuel_design_tool_add_name')
    ),

     $form['submit_button'] = array(
     '#type' => 'submit',
     '#value' => t('Submit'),
     "#submit" => array("fuel_design_tool_submit"),
    );

     return $form;
 }

 function fuel_design_tool_add_name($form, &$form_state) {

    $form_state[FIELDS_NUM]++;
    $form_state['rebuild'] = TRUE;
   }

function fuel_design_tool_callback($form, &$form_state)
 {
   for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++)
   {

  $form['values']['field'][$i]['FORM_FIELD_DENSITY'] = $form_state['values']['field'][$i]['FORM_FIELD_SPECIES'];
  return array (
    $form['field'][$i]['FORM_FIELD_DENSITY'],

   );
  }

 }
 }

```

My callback function returns only one value and that by default filled to fiedset#1 textfield.I guess i need to modify my callback function.

I am looking forward for your kind help.

If my question is not clear please let me know. I am finding bit difficult to explain this problem

# Answer
> 0 votes
Give the textfield wrappers unique ids, e.g. fuel\_design\_tool-wrapper-1 and fuel\_design\_tool-wrapper-2, and assign accordingly in the FAPI array.

---
Tags: ajax, forms
---


# Question
Title: Adding JS to a form within Omega 4 theme
I need to add some JavaScript to forms within my Omega 4 theme. My code right now is:

```
function mytheme_preprocess_form(&$vars) {
    $vars['element']['#attached']['js'][] = 'path/to/myjs';
}

```

This isn't working, but it seems like it should. I need to do this from my theme. I don't want to use drupal\_add\_js(), since that's being deprecated.

# Answer
> 2 votes
You cannot do what you want to do in the form preprocessor.

Try using hook\_form\_alter() instead.

Keep reading for more information on why your current code doesn't work.

If you look at drupal\_render() you can see that it runs this to theme the element:

```
if (isset($elements['#theme'])) {
  $elements['#children'] = theme($elements['#theme'], $elements);
}

```

This call to theme() is pretty much where your preprocess code code is running.

The output of that theme function (theme\_form() outputs a string of form markup) is then going into $elements\['#children'\].

Then further down in drupal\_render() it does this:

```
if (!empty($elements['#attached'])) {
  drupal_process_attached($elements);
}

```

But the #attached code you added never ended up back in the $elements of the drupal\_render() function though so nothing happened.

# Answer
> 1 votes
You can specify it in the .info file of your theme using `scripts[] = 'path/to/myjs'`

---
Tags: 7, forms, theming
---


title: How to search in field collection item?

text:
# Question
Title: How to search in field collection item?
I want the Drupal Default Search to look into Field Collection items.

I currently have a field\_resources collection with a field\_description and a field\_file, and the search should be looking into both.

Is this possible? What simple alternative could I use instead? An external search module seems a bit overkill.

# Answer
> 1 votes
As say in Search interface the search system already indexes all visible output of a node; i.e., everything displayed normally by hook\_view() and hook\_node\_view().

You can activate and configure in the display settings of your content type the custom display "Search index" than will be used for indexing.

If this doesn't works in you case, you can implement hook\_node\_update\_index to add any information you want on the node before is indexed.

# Answer
> 0 votes
Search API Attachments Module helps you search through file attached in field collection

> This module is an add-on to the Search API which allows the indexing and searching of attachments.

---
Tags: search, entities
---


title: Alternatives to hook_init()

text:
# Question
Title: Alternatives to hook_init()
I use `hook_init()` to check the users' last access time. If the last access time is yesterday, I increment a counter and set some variables.

The problem is that `hook_init()` is sometimes executed more that once (i can see this using `dsm()`) for the same page load, so my code is executed multiple times resulting in wrong variables.

Why is `hook_init()` executed more than once?
What would the best approach to my problem be? Should I use another hook?

**I did some more digging on this:** I search for calls to the hook\_init() (searched for string `module_invoke_all('init');`) but found only the core call). I dont know if this can be called differently.

This is my hook\_init()

```
function episkeptis_achievements_init(){
    dsm('1st execution');
    dsm('REQUEST_TIME: '.format_date(REQUEST_TIME, 'custom', 'd/m/Y H:i:s').' ('.REQUEST_TIME.')');
}

```

and this is the output:

```
1st execution
REQUEST_TIME: 09/07/2012 11:20:32 (1341822032)

```

then, changed the dsm() message to `dsm('2nd execution');` and executed again, this is the output:

```
1st execution
REQUEST_TIME: 09/07/2012 11:20:34 (1341822034)
2nd execution
REQUEST_TIME: 09/07/2012 11:22:28 (1341822148)

```

You can see that the code is executed twice. However, the first time executes an old copy of the code, and the second time the updated copy. There is also a 2 sec time difference.

This is a d7 version with php 5.3.10

# Answer
`hook_init()` is invoked by Drupal only once for each requested page; it is the last step done in \_drupal\_bootstrap\_full().

```
  // Drupal 6
  //
  // Let all modules take action before menu system handles the request
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    module_invoke_all('init');
  }

```

```
  // Drupal 7
  //
  // Let all modules take action before the menu system handles the request.
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
    // one for this page), so that:
    // - Modules with hook_init() implementations that call theme() or
//   theme_get_registry() don't initialize the incorrect theme.
    // - The theme can have hook_*_alter() implementations affect page building
//   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
//   ahead of when rendering starts.
    menu_set_custom_theme();
    drupal_theme_initialize();
    module_invoke_all('init');
  }

```

If `hook_init()` is being executed more than once, you should discover why that happens. As far as I can see, none of the `hook_init()` implementations in Drupal checks it is being executed twice (see for example system\_init(), or update\_init()). If that is something that can normally happen with Drupal, then `update_init()` would first check if it has been already executed.

If the counter is the number of consecutive days a user logged in, I would rather implements `hook_init()` with code similar to the following one.

```
// Drupal 7
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_date($timestamp) {
  $date_time = date_create('@' . $timestamp);
  return date_format($date_time, 'Ymd');
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  if ($last_timestamp == REQUEST_TIME) {
    return array(FALSE, 0);
  }

  $result = array(
    mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME),
    REQUEST_TIME - $last_timestamp,
  );
  variable_set("mymodule_last_timestamp_$uid", REQUEST_TIME);

  return $result;
}

```

```
// Drupal 6
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  $result = array(FALSE, time() - $last_timestamp);

  if (time() - $last_timestamp < 20) {
    return $result;
  }

  $result[0] = (mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME));
  variable_set("mymodule_last_timestamp_$uid", time());

  return $result;
}

```

If `hook_init()` is invoked two times in row during the same page request, `REQUEST_TIME` contains the same value, and the function would return `FALSE`.

The code in `mymodule_increase_counter()` is not optimized; it is just to show an example. In a real module, I would rather use a database table where the counter, and the other variables are saved. The reason is that Drupal variables are all loaded in the global variable `$conf` when Drupal bootstraps (see \_drupal\_bootstrap\_variables(), and variable\_initialize()); if you use Drupal variables for that, Drupal would load in memory information about all the users for which you saved information, when for each requested page there is only one user account saved in the global variable `$user`.

If you are counting the number of page visited from the users in consecutive days, then I would implement the following code.

```
// Drupal 7
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_date($timestamp) {
  $date_time = date_create('@' . $timestamp);
  return date_format($date_time, 'Ymd');
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  if ($last_timestamp == REQUEST_TIME) {
    return array(FALSE, 0);
  }

  $result = array(
    mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME),
    REQUEST_TIME - $last_timestamp,
  );
  variable_set("mymodule_last_timestamp_$uid", REQUEST_TIME);

  return $result;
}

```

```
// Drupal 6
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  $result = array(FALSE, time() - $last_timestamp);

  if (time() - $last_timestamp < 20) {
    return $result;
  }

  $result[0] = (mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME));
  variable_set("mymodule_last_timestamp_$uid", time());

  return $result;
}

```

You will notice that in my code I don't use `$user->access`. The reason is that `$user->access` could be updated during Drupal bootstrap, before `hook_init()` is invoked. The session write handler used from Drupal contains the following code. (See \_drupal\_session\_write().)

```
// Likewise, do not update access time more than once per 180 seconds.
if ($user->uid && REQUEST_TIME - $user->access > variable_get('session_write_interval', 180)) {
  db_update('users')
    ->fields(array(
    'access' => REQUEST_TIME,
  ))
    ->condition('uid', $user->uid)
    ->execute();
}

```

As for another hook you can use, with Drupal 7 you can use hook\_page\_alter(); you just don't alter the content of `$page`, but increase your counter, and change your variables.
On Drupal 6, you could use hook\_footer(), the hook called from template\_preprocess\_page(). You don't return anything, but increase your counter, and change your variables.

On Drupal 6, and Drupal 7, you could use hook\_exit(). Bear in mind that the hook is also invoked when the bootstrap is not complete; the code could not have access to functions defined from modules, or other Drupal functions, and you should first check those functions are available. Some functions are always available from `hook_exit()`, such as the ones defined in bootstrap.inc, and cache.inc. The difference is that `hook_exit()` is invoked also for cached pages, while `hook_init()` is not invoked for cached pages.

Finally, as example of code used from a Drupal module, see statistics\_exit(). The Statistics module logs access statistics for a site, and as you see, it uses `hook_exit()`, not `hook_init()`. To be able to call the necessary functions, it calls drupal\_bootstrap() passing the correct parameter, such as in the following code.

```
  // When serving cached pages with the 'page_cache_without_database'
  // configuration, system variables need to be loaded. This is a major
  // performance decrease for non-database page caches, but with Statistics
  // module, it is likely to also have 'statistics_enable_access_log' enabled,
  // in which case we need to bootstrap to the session phase anyway.
  drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);

```

```
  if (variable_get('statistics_enable_access_log', 0)) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

    // For anonymous users unicode.inc will not have been loaded.
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
    // Log this page access.
    db_insert('accesslog')
      ->fields(array(
      'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
      'path' => truncate_utf8($_GET['q'], 255),
      'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
      'hostname' => ip_address(),
      'uid' => $user->uid,
      'sid' => session_id(),
      'timer' => (int) timer_read('page'),
      'timestamp' => REQUEST_TIME,
    ))
      ->execute();
  }

```

### Update

Maybe there is some confusion about when `hook_init()` is invoked.

`hook_init()` is invoked for each page request, if the page is not cached. It is not invoked once for each page request coming from the same user. If you visit, for example, http://example.com/admin/appearance/update, and then http://example.com/admin/reports/status, `hook_init()` will be invoked twice: one for each page.
"The hook is invoked twice" means there is a module that executes the following code, once Drupal has completed its bootstrap.

```
module_invoke_all('init');

```

If that is the case, then the following implementation of `hook_init()` would show the same value, twice.

```
function mymodule_init() {
  watchdog('mymodule', 'Request time: !timestamp', array('!timestamp' => REQUEST_TIME), WATCHDOG_DEBUG);
}

```

If your code shown for `REQUEST_TIME` two values for which the difference is 2 minutes, as in your case, then the hook is not invoked twice, but it is invoked once for each requested page, as it should happen.

`REQUEST_TIME` is defined in bootstrap.inc with the following line.

```
define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);

```

Until the currently requested page is not returned to the browser, the value of `REQUEST_TIME` doesn't change. If you see a different value, then you are watching the value assigned in a different request page.
> 20 votes

# Answer
I remember this happening a lot in Drupal 6 (not sure if it still does in Drupal 7), but I never found out why. I seem to remember seeing somewhere that Drupal core does not call this hook twice though.

I always found the easiest way around it was use a static variable to see if the code has already been run:

```
function MYMODULE_init() {
  static $code_run = FALSE;

  if (!$code_run) {
    run_some_code();
    $code_run = TRUE;
  }
}

```

That'll ensure it only gets run once in a single page load.
> 8 votes

# Answer
You might find hook\_init() is called multiple times if there is any AJAX happening on the page (or you're loading images from a private directory - though I'm not sure about that as much). There are a few modules that use AJAX to help bypass page caching for certain elements for example - easiest way to check is to open up the net monitor in your debugger of choice (firefox or web inspector) and having a look to see if any requests are made that could be triggering the bootstrap process.

You'll only get the dpm() on the next page load though if it is an AJAX call. So say you refresh the page 5 minutes later, you'll get the AJAX call from 5 minutes ago's init message as well as the fresh one.

An alternative to hook\_init() is hook\_boot() which is called before any caching is done at all. No modules are loaded in yet either, so you really don't have much power here apart from setting global variables and running a few Drupal functions. It's useful for bypassing regular level caching (but won't bypass agressive caching).
> 5 votes

# Answer
In my case, this behaviour was caused by the Administration Menu module (admin\_menu).

hook\_init wasn't getting called each request but admin menu would cause /js/admin\_menu/cache/94614e34b017b19a78878d7b96ccab55 to be loaded by the user's browser very shortly after the main request, triggering another drupal bootstrap.

There will be other modules that do similar things but admin\_menu is probably one of the more commonly deployed ones.
> 1 votes

---
Tags: 7, hooks
---


title: Pop up Information windows D7

text:
# Question
Title: Pop up Information windows D7
I am new in Drupal 7. What i am trying to do is to show pop up information windows for the following case:

I have a view with links (internal links to drupal site). I want by clicking on them:

1.To show an information pop-up window with the message "Redirection to the official position..."

2. This message to be showing for 3 seconds and
3. The message to disappear after 3 seconds and the redirection to be completed.

How can i show specific pop-up windows by clicking a link and before the redirection takes place?

# Answer
> 0 votes
I am not aware of a contrib module to achieve this, but you can always use jQuery in your theme or custom module.

Something like this might work (not tested, but that's the main idea - out of scope for Drupal Answers):

```
jQuery(document).ready(function() {
  // on link click (jQuery 1.4)
  jQuery('#my-link').click(function(e) {
    // preventDefault otherwise browser will go to link
    e.preventDefault();
    // show the pop-up layer which is assumed hidden with css or sth.
    jQuery('#my-popup-layer').fadeIn();
    // here you can possibly chain up more actions in order to
    // update the contents of the pop-up
    // now delay 3sec
    jQuery(this)
      .delay(3000)
      .queue(function(next) {
        // redirect
        window.location.href = jQuery(this).attr('href');
        next(); // prob redundant
      });
  });
});

```

---
Tags: views, rules, navigation, redirection, javascript
---


title: How to create a custom menu

text:
# Question
Title: How to create a custom menu
I have created a menu called "navbar". In this menu, there is 4 links at level 1. Each of these links has 3 sublinks (level 2). All links in the menu point to a different page. For example, I have on lvl 1 "Projects" (that points to /projects). That parent links contains 3 lvl 2 subsections : "News" (projects/news), "Photos" (projects/photos) and "Maps" (projects/maps). Then I create an article, I check the "Provide a menu link" and I select "News" in the dropdown list. I have "menu block" installed, and I configured a "navbar" block to be bound to the "navbar" menu. I also installed "menu node" to have a table with the mapping between nodes and menus. Now, how do I customize the menu to display all lvl 1 & 2 and all associated articles ? What function do I need to create and where ? I have tried the following code to no avail (where business is my theme's name and 2 is the menu id) :

```
function business_menu_link__menu_block__menu_navbar($variables)
function business_menu_tree__menu_block__menu_navbar($variables)
function business_menu_link__menu_block__2($variables)
function business_menu_tree__menu_block__2($variables)

```

What should I do ?

# Answer
Ok I found what was wrong : I needed to register the function in the template.php :

```
function business_theme_registry_alter(&$theme_registry) {
    $theme_registry['menu_tree__menu_block__menu_navbar']['function'] = 'business_menu_link__menu_block__menu_navbar';
}
function business_menu_link__menu_block__menu_navbar($variables) {

}

```
> 1 votes

---
Tags: blocks
---


# Question
Title: User_save is very slow for no apparent reason
As you could see on picture, saving data for users is very slow. Queries run fast, but for some reason it takes up to 2 minutes to save user data. The same happens with logging in.

What is more strange, I have DB versions of this site and have a previous version where this works normally and all of a sudden this started to happen.

* I checked errors in log
* Disabled modules
* Cache reseting
* Exported DB tables from working DB (user, user\_roles, variables) to non working
* Checked for missing modules
* Tried older version of drupal (7.33).
* Disabled some custom code modules

Tried everything I could come up, but still user\_save is slow like on image and no errors or warnings appear. Really don't have a clue anymore what could be wrong, something in DB level must been wrong, not sure what to try anymore and where to look?

# Answer
I found the answer, well the reason. I had a in a module hook\_user\_update()

that has a CURL that connects to remote site and beacuse of it took much time to save, well to connect and then to save. Need a way to make this CURL connection not affect the user save.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Gmap Location in views - exposed filter by distance/proximity and post code
I am currently working with **Drupal 7** and **Location 7.x-3.4** module

I have created a **view**, choose the **Gmap** format, and added the **post code** and **distance** field in **filter** section, so that the visitors are able to search for the locations they want.

Gmap Settings:

> Data Source = **Location.module**
>
> Marker handling = **Use single marker type**

Here is my configuration for the **Location: Distance / Proximity** :

> Expose this filter to visitors, to allow them to change it = **1**
>
> Filter type to expose = **Distance / Proximity**
>
> Operator = **Proximity (Circular)**
>
> Postal code = **Blank**
>
> Distance = **Blank**
>
> Origin = **Postal Code (assume default country)**
>
> Filter identifier = **distance**

After saving the changes, the result is not changing. Is anyone knows what's wrong with my configuration above? Please help..

# Answer
> 2 votes
It's a bit hard to say for sure but my guess is that you have missed a step when installing the location module.

For post code proximity searching the location module uses a database of postcodes and their coordinates to convert the postcode to the lat/lon coordinates that are then used to calculate whether other locations fall in the request distance.

See installation step 6 in the INSTALL.txt file of the location module.

> 6. (Optional) Import a postal codes database for the countries served by your website, to support proximity searches and other useful features. Postal code databases may be found in the "databases/" sub-directory of the Location module directory. The files are in the format of zipcodes.CC.mysql, where CC is a two-letter country code such as 'us' or 'de'.
>
> Note: If your site is using table prefixes, you will need to adjust for this manually, by opening the file in a text editor and replacing 'zipcodes' with 'prefix\_zipcodes' throughout.
>
> To import the files from the command line, enter the following:
>
> cd sites/SITENAME/modules/location mysql -u username -p database-name \< database/zipcodes.us.mysql

Note that this proximity functionality may not work for some countries if the data is not available.

---
Tags: views, google-maps
---


# Question
Title: How to pass contextual filter to a view pane?
I have a taxonomy page where different view panes of a single view are displayed. I want to pass contextual filter to only kind of View pane. I wrote this code but this passes the contextual filter to all the view panes on the page. How can I pass contextual filter to a single specific view pane? Thank you for your time.

`function intrakicalendarrss_views_pre_view(&$view, &$display_id, &$args) {
 $arg0 = arg(0);
 $arg1 = arg(1);
 $arg2 = arg(2);
 if($view->name = 'current_event_list') {
 if($arg0 == 'taxonomy' && $arg1 == 'term' && ($arg2 == 1 || $arg2 == 2)) {
 $Cfilter = $arg2;
 $args[0] = $Cfilter;
 }
 }
}`

# Answer
> 1 votes
Add another condition to check the specific display name

```
if($view->current_display == 'display_name')

```

Here `display_name` of particular display can be found in *Advanced Option* -\> *Machine Name*

# Answer
> 1 votes
Try using $view-\>current\_display like this:

```
function intrakicalendarrss_views_pre_view(&$view, &$display_id, &$args) {
  $arg0 = arg(0);
  $arg1 = arg(1);
  $arg2 = arg(2);
  if ($view->name == 'current_event_list' && $view->current_display == 'your_display') {
    if ($arg0 == 'taxonomy' && $arg1 == 'term' && ($arg2 == 1 || $arg2 == 2)) {
      $Cfilter = $arg2;
      $args[0] = $Cfilter;
    }
  }
}

```

You are also using a single equals sign in your if statement instead of a double or triple equals, which means that if statement will always return true.

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


title: Pledge cannot be clicked(no link)

text:
# Question
Title: Pledge cannot be clicked(no link)
Have a look at this screenshot:

After creating a crowdfunding reward, it appears on the event page as for example "*Pledge $10 for Test Run"*.

When I checked the source code, I found that this line should be linked with a link `<a href="/drupal/crowdfunding/pledge/2/5">` which redirects to the pledge so that the user can make the payment.

But this link is not clickable from the page. I need to go to "inspect element" in google chrome and then click on the link.

My question is, why can't I click on the link? Why doesn't it appear on the page?

# Answer
Because there is no link content so there is nothing to click on.

A link should be of the form

```
<a href="/url-of-page-being-linked-to">Link content</a>

```

In that example there would be the text "Link content" that you could click on.

For your code I would expect it should be something like this:

```
<h3><a href="/drupal/crowdfunding/pledge/2/5">Pledge RM10.00 or more</a></h3>

```

For more information see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

To modify the pledge markup do no modify the crowd funding module. For more information on why it's a good idea not to hack modules see Why don't we hack core?

The correct way is to override the template that prints the markup.

In this case crowdfunding-reward-options-node-view.tpl.php is the relevant template file.

So copy that template file from the tpl directory of the crowdfunding module and put it in your theme. Then clear the drupal cache and the site will start using the template file in your theme instead of the one in the module. Then modify the markup of the template that you put in your theme to suit your needs.
> 1 votes

# Answer
Surround "Pledge" between the elements, like this:

```
<a href="/yourlinkhere">Pledge</a> RM 10.00...

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Views PHP: Getting field values and generating link
I want to generate the RSS feed of my calendar as:

```
PHOTO (uploaded photo)

BODY

http:://www.example.com/content/the-title (Link of feed to the content page)

```

For this I use a "Global: PHP" field in the calendar view I created, entering code in "Output code".

I didn't succeed in printing the node body using:

```
<?php echo $row->body; ?>

```

With this, I get the ID.

The following gives no result:

```
<?php
$node = node_load($row->nid);
print_r($node);
?>

```

Using:

```
<?php print_r($row); ?>

```

I got:

```
stdClass Object
(
[title] => The title
[body] => 1311
[rendered_entity] => 1311
[php] =>
)

```

How to I get the real content of the body, image link (field\_photo) and the content link?

Thanks,

# Answer
> 1 votes
Try using these code

```
$body = $data->_field_data['nid']['entity']->field_image['und'][0]['body'];

```

**OR**

```
$node = node_load($data->$nid);
$body = $node->body[0]['value'];

```

This may be because of the issue here

---
Tags: views, feeds, datetime
---


# Question
Title: How to pass default values on node form through form_alter when using confirm_form?
My confirm form should consists part of node form but with disabled fields. I mean after I submit node form I rebuild it and append confirm form in `hook_form_alter()`(Before it I change submit callback and set 'reduild' flag in `form_state` in it).

But this form not containing filled values. I guess this is because I make rebuild but as I know there is no other way to display confirm form. So the question is how to do it? How to fill values filled on previous step?

First phase submit callback:

```
function mymodule_content_confirm_form_submit($form, &$form_state) {
  $form_state['storage']['confirm'] = 'save';
  $form_state['storage']['values'] = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  return;
}

```

Form alter the part where confirm form appends:

```
  $show_confirm_form = isset($form_state['storage']['confirm']);
  if ($show_confirm_form) {
    // We need this form for panels and we can't remove it so we just hide.
    foreach (element_children($form) as $id) {
      $element = &$form[$id];
      if (!empty($element['#type']) && in_array($element['#type'], array('hidden', 'value'))) {
        continue;
      }
      $element['#disabled'] = TRUE;
    }
    $message = t('Are you sure you want to save all these changes?');

    $form = confirm_form($form, t('Levels & Content'), current_path(), $message, t('Confirm'), t('Cancel'));
    $form['actions']['cancel']['#href'] = current_path();
    $form['actions']['cancel']['#attributes']['class'][] = 'button';
    $form['actions']['cancel']['#options']['path'] = current_path();
    $form['actions']['cancel']['#options']['query'] = $destination;

    $form['actions']['submit']['#submit'] = array('mobitek_custom_content_node_form_insert_values_submit', 'node_form_submit');
    return;
  }

```

# Answer
This is my dirty solution of the problem, I use `$form_state['complte form']` instead `$form`:

```
$refill_fields = array(
  'form_build_id',
  'form_id',
  'form_token',
  '#id',
  '#token',
  '#build_id',
);
foreach ($refill_fields as $refill_field) {
  $form_state['complete form'][$refill_field] = $form[$refill_field];
}

```
> 0 votes

---
Tags: forms, nodes
---


# Question
Title: How do I hide Bartik Main Menu on front page from unauthenticated users?
I have a private website in which content can only be viewed by authenticated users. All I want is the login box for non authenticated users. I am using NodeAccess and also Rules module to do this. Seems to work fine with one exception. The pages which should only be visible after login show their links to the anonymous user on the Bartik theme main menu right on the home page. All menu items appear including those for pages specifically limited to administrator viewing. True, clicking on them merely brings up the login dialog box so the individual can't see the page, however, I don't want the menu itself to appear at all until the person is authenticated. How do I make the entire menu disappear if unautenticated? Thanks in advance.

# Answer
> 1 votes
The main menu in Bartik theme is being output directly (you can see it in 'themes/bartik/templates/page.tpl.php' - starts with `<?php if ($main_menu): ?>`). In order to hide the menu from anonymous users you could do the following:

```
<?php if ($logged_in): ?>
  <?php if ($main_menu): ?>
    // Code that prints the menu.
  <?php endif; ?>
<?php endif; ?>

```

Modifying core should be avoided though so the proper way to handle this would be to create a copy of the theme inside the 'sites/all/themes' folder with a different name. Then renaming necessary files, modifying the code and making your site use that theme instead of the core Bartik.

# Answer
> 2 votes
In case you are using D7, when you configure your menu block, you have a section called "visibility settings".There select the Roles tab and check the option "authenticated user" under "show block for specific roles". Then click save block.

# Answer
> 0 votes
Beat, Just wondering, has anyone tried turning off the checkbox for Main Menu under: Appearance\> Theme (eg. Bartik Settings)\> Toggle Display\> Remove checkbox from "main menu". that worked for me. Good luck.

# Answer
> -1 votes
You can insert the Menu as a block and then use the Visibility \> Roles settings to hide it for anonymous users.

---
Tags: routes
---


# Question
Title: List nodes of children using taxonomy_select_nodes
I want to list nodes from children terms using or editing taxonomy\_select\_nodes function. Actually I added these few lines but I get an infinite loop or slow response:

```
function taxonomy_select_nodes_ext($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'),$promote) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
  $query->condition('tid', $tid);
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');

      // This block of code is the custom code I added.
      //SELECT only promoted article
      if($promote==1){
        $query->join('node', 'no', 'no.nid = t.nid');
        $query->condition('promote', 1);
      }
      $taxonomies=array();
      $taxonomies = taxonomy_get_children($tid);
      $taxonomies[]=$tid;
      $query->condition('t.tid', $taxonomies,'IN');

  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    // ORDER BY fields need to be loaded too, assume they are in the form
    // table_alias.name
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

```

# Answer
I would say these are your problems:

taxonomy\_get\_children() returns term objects, not term IDs, so that is going to break that query. This I would say is your main issue. Instead you could do this:

```
  $taxonomies = array();
  $taxonomies = taxonomy_get_children($tid);
  // Get the child term tids.
  $taxonomies = array_keys($taxonomies);
  // Add the parent tid.
  $taxonomies[] = $tid;
  $query->condition('t.tid', $taxonomies,'IN');

```

Your IN statement with the children won't work currently because earlier in the function is this line:

```
$query->condition('tid', $tid);

```

So that will only ever return values for $tid, never for the children unless you remove that line also.

Also I would recommend giving the new $promote parameter a default value, like this:

```
function taxonomy_select_nodes_ext($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'), $promote = 0) {

```
> 0 votes

---
Tags: database
---