# Question
Title: Getting node as authorized user via Services 3 and REST
I am new to Drupal. My goal is to use it for staff to manage their own content, then retrieve their content from nodes via REST to the existing public website.

Using Drupal 7.10, Services 3. Drupal resides in a subdirectory, not at the site root, if that matters. An endpoint named "rest" has been created for the REST server. Anonymous access is not desirable, so a Drupal user has been created for authenticated access requests.

I am building a PHP client based on a post by MichaelCole for auth access. It seems to be talking to the REST server, as at first I was seeing our Drupal site theme along with a Drupal error in my generic PHP page.

At this time I am only trying to log in as my service user, so just the login.php code is running on my page.

PHP is returning this:

> RESPONSE: string(0) "" Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /path-to-my-page/test-drupal-rest.php:36 Stack trace: #0 /path-to-my-page/test- drupal-rest.php(36): SimpleXMLElement-\>\__construct('') #1 {main} thrown in /path-to-my- page/test-drupal-rest.php on line 36

Line 36 is:

```
$xml = new SimpleXMLElement($response);

```

If I just put the full service URL into my browser ( http://www.mydomain.com/drupal-folder/rest/user/login.xml ), I get (XML broken with spaces for display here):

> \< ? xml version="1.0" encoding="utf-8"?\> \< result/\>

I am out of ideas. Can you help?

EDIT/UPDATE: I went into Administration » Structure » Services and discovered that "application/x-www-form-urlencoded " under Request Parsing was disabled. I enabled that, and my requests started going through. However, even though it obviously recognizes my user auth, I still cannot retrieve a node.

=====================

Edit/Update 2012-01-16 15:10 : Here is my current code, based on MichaelCole's code and modified for my workflow and goal. It does not retrieve the node content. The failure appears to be somewhere in the sending of the session authentication with the node request. Logging in always works properly and I always receive my XML user object.

```
loginToDrupal();

$service_url = "http://mysite.com/drupal-folder/resttest/node/10.xml";

$session_cookie = file_get_contents('session_cookie.txt');

print "Ready to send cURL to $service_url";

// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string
curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
curl_setopt($curl, CURLOPT_HTTPGET, true); //do a GET ^^^^added by me...
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line

$response = curl_exec($curl);
curl_close($curl);
print "\n<br />RESPONSE:\n";
var_dump($response);

logoutOfDrupal();

//=======================================================================

function loginToDrupal()
    {
    $service_url = 'http://www.mysite.com/drupal-folder/rest/user/login.xml'; // .xml asks for xml data in response
    $post_data = array(
          'username' => 'myusername',
          'password' => 'mypass',
        );
    $post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded

    // set up the request
    $curl = curl_init($service_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string
    curl_setopt($curl, CURLOPT_POST, true);             // do a POST
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data

    // make the request
    curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
    $response = curl_exec($curl);
    curl_close($curl);
    print "\n<br />RESPONSE:\n";
    var_dump($response);

    // parse the response
    $xml = new SimpleXMLElement($response);
    $session_cookie = $xml->session_name .'='. $xml->sessid;

    file_put_contents('session_cookie.txt', $session_cookie);

    if($xml->sessid!="")
        {
        print "login successful, session $xml->sessid <br />";
        }
    else
        {
        print "Login appears to have failed.";
        }
    }

//========================================================================================

function logoutOfDrupal()
    {
    print "\n<br />Logging out...<br />";
    $service_url = 'http://mysite.com/drupal-folder/rest/user/logout';
    $session_cookie = file_get_contents('session_cookie.txt');

    // set up the request
    $curl = curl_init($service_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string
    curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
    curl_setopt($curl, CURLOPT_POST, true);             // do a POST
    curl_setopt($curl, CURLOPT_POSTFIELDS, ""); // POST this data

    // make the request
    curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
    $response = curl_exec($curl);
    curl_close($curl);
    print "\n<br />RESPONSE:\n";
    var_dump($response);
    print "\n<br />reached end of function logoutOfDrupal()<br />";
    }

```

The debug print call after the loginToDrupal() function always returns XML like this:

```
< ?xml version="1.0" encoding="utf-8"? >< result >< sessid >AU7yWNWPXxORI2DsdJVegdreg2F9rYQxy90dAB5px2s< /sessid >< session_name >SESSd9af11d86664849a8dcda2d6c4af3580< /session_name >< user >< uid >11< /uid >< name >myuser< /name >< mail >me@mysite.com< /mail >< theme >< /theme >< signature >< /signature >< signature_format >filtered_html< /signature_format >< created >1326401726< /created >< access >1326746687< /access >< login >1326748351< /login >< status >1< /status >< timezone >America/Denver< /timezone >< language >< /language >< picture/ >< init >me@mysite.com< /init >< data >< contact >1< /contact >< /data >< roles is_array="true" >< item >authenticated user< /item >< /roles >< rdf_mapping >< rdftype is_array="true" >< item >sioc:UserAccount< /item >< /rdftype >< name >< predicates is_array="true" >< item >foaf:name< /item >< /predicates >< /name >< homepage >< predicates is_array="true" >< item >foaf:page< /item >< /predicates >< type >rel< /type >< /homepage >< /rdf_mapping >< /user >< /result >

```

Even though it clearly returns a successful user object, the code above returns an empty XML string every time I try to retrieve the node.

# Answer
> 1 votes
Today I discovered a simple problem with my sample code: In the node retrieval, the URL is:

```
$service_url = "http://mysite.com/drupal-folder/resttest/node/10.xml";

```

whereas in the login function, it is:

```
$service_url = 'http://**www**.mysite.com/drupal-folder/rest/user/login.xml';

```

I changed it so that all URLs point to www.mysite.com, and I can now retrieve a node as an authenticated user.

# Answer
> 0 votes
So you're saying that you logged in as a user correctly. Which auth method are you using? Session Authentication? If so, the login response should return a user object, from which you need to take the SESSID, store it on your application/other website/client, and use it whenever you need to retrieve a node. You have to send the SESSID as another parameter in your node retrieve request alongside the nid (yes, every time).

---
Tags: 7, services
---


# Question
Title: Special type of nginx redirect: redirect only if $request_uri is empty
I need a special type of redirect for a Drupal 6 website. I'm thinking that the best place to do this is in an nginx config file, but please correct me if I'm wrong. I know I can do it in a template file/module by checking $\_GET\['q'\] and then using drupal\_goto(), but I don't want to load the full bootstrap only to do a redirect.

Basically, I need to redirect www.domain.com and domain.com to subdomain.domain.com ONLY if I don't have anything after the domain part. This means that domain.com/node/3 should NOT be redirected.

I hope it makes sense and thank you in advance for your help :)

# Answer
Ok, I've found the solution. I'm adding this to my existing nginx config:

```
location = / {
  rewrite ^ http://subdomain.domain.com permanent;
  break;
}

```

This redirects the top level domain but leaves all the existing "deep" links intact. If anybody wants to know why I'm doing this, it's good for SEO. I'm keeping the old URLs intact (as an archive) but redirect the domain to my new website.
> 0 votes

---
Tags: 6, redirection
---


# Question
Title: How to validate 3 or more fields when creating content in D7
I have a custom content type with 3 fields (integer). How can I check when content is created or edited that the sum of those three fields are equal to a predefined total. For instance, if the three fields represent percentages of a task to be completed, I would like to issue an error message if the sum of the three fields is not 100%

# Answer
Create a module to add a validation handler to the form by implementing `hook_form_alter()`:

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MY_FORM_ID') {
    $form['#validate'][] = '_MODULE_validate';
  }
}

```

Then define the handler function that checks the field values:

```
function _MODULE_validate($form, &$form_state) {
  // Check that the sum of the fields equals a predefined total
}

```

If you're not familiar with creating your own modules, but are comfortable with PHP, you could probably use the Field Validation module to add a custom PHP validator that does the same thing.
> 0 votes

---
Tags: entities
---


# Question
Title: How to access data from a page on a form hook?
I have a page that has a $\_GET and I would like to use that value on the form that is used on that page, but I do not know how to pass a variable to that form for use. usually I can just get the data from elsewhere, but the $\_GET is NULL when I run it in the form itself.

```
function mymodule_menu() {

   $items = array();

   $items['sample'] = array(
    'title' => 'Title',
    'description' => '',
    'page callback' => 'mymodule_page',
    'access arguments' => array('access content')
  );
}

function mymodule_page() {
    $variable = $_GET['variable'];
    return theme('mymodule_page', array(
       'form' => drupal_get_form('mymodule_page_form'),
       'variable' => $variable
    ));
}
function mymodule_page_form(){
    var_dump($variable); <-- not defined.
}

```

I tried variable\_get and variable\_set, but it's not reliable because it seems to hold values for a while.

# Answer
By default variables defined in one function aren't available in any other functions (see PHP: Variable scope), which is why your variable is undefined in the form function.

You can declare `$variable` as a `global` (see the link above) to make it available in both your functions:

```
function mymodule_page() {
    global $variable;
    $variable = $_GET['variable'];
    return theme('mymodule_page', array(
       'form' => drupal_get_form('mymodule_page_form'),
       'variable' => $variable
    ));
}
function mymodule_page_form(){
    global $variable;
    var_dump($variable);
}

```

But to be honest there's no good reason why `$_GET` would be empty when it reaches your form function, so it might be worth seeing if you can find out why that's happening.
> 2 votes

---
Tags: forms, hooks
---


title: Slow Loading Forms (submission ok)

text:
# Question
Title: Slow Loading Forms (submission ok)
Hello i was wondering if anyone could suggest anything for me with this problem i have with my forms. (add/node) Ive turned CCK and all my modules off but still when i go to the node/add page the form is taking ages to load (20secs+) even for a simple submission form with no fields etc.

Generally my website http://onlinebanter.com runs ok and i do my best to keep my module lust down.

Is there any code or diagnostic tools i could use to see why my forms are talking so long to load.

Thanks

# Answer
> 0 votes
I found that it was because i was using an old version of pressflow it must have had some security problems with the other modules. Updated and things running like a dream :)

---
Tags: forms
---


# Question
Title: Creating a slideshow with images and text overlays
Does anyone know of a module or method to create a node where users can upload an image, add text on top of it through a WYSIWYG, then have the image combined with the text (merge the text and image into one jpg/png)?

We are trying to find a way for users in a school to add slides to our digital signage without using powerpoint, and I was wondering if there was a Drupal module that could do the job or help make it easier.

# Answer
> 2 votes
I don't believe that there's a module that supports the dynamic placing of text on top of an image in a wysiwyg editor. However, you should be able to use the imagecache\_actions module to superimpose a text field onto an image field; IOW, you'd need to have separate fields (or a field collection) for the image and text. It also supports custom actions which should allow you to exploit the imageapi and GD as per your requirements.

# Answer
> 0 votes
If you're displaying slides on your website, you don't have to merge the text with the jpg/png. You can create a js slideshow with images and texts over them using CSS. You can use Views Slideshow for that. Basically, it can create js slideshows using Views. Sou you can create a content type with a body and an image field, create a view to display the nodes for your content type and display them using Views Slideshow.

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


# Question
Title: New URL for the node overrides the URL of existing node using pathauto module
I'm using Pathauto module to set the URL for the nodes in my site. I have already created about 20,000 nodes in my site. Usually, the Pathauto module doesn't allow to the users to create the node with existing URL by giving the error as "Path already in use". But in my case, I can change the URL of a node with an existing URL of a node. For example parks located in same country,

1. Gandhiji Park - /gandhiji-park (located in state1)
2. Gandhiji Park - /gandhiji-park-0 (located in state2)

I can change the URL of the park in state2 as /gandhiji-park and the node is saved in that URL.

If I search for gandhiji park in state2 the search filters out the park but the URL took me to park in state1.

Can anyone help me in this?

# Answer
> 2 votes
I faced the same problem in my website. As you mentioned in your question :

> Usually, the Pathauto module doesn't allow to the users to create the node with existing URL by giving the error as "Path already in use"

This is true only when you hand code the URL alias. If **"Generate automatic URL alias"** box is checked then similar URL's are appended with numbers at the end (like in your case).

The method I used to prevent this problem was to install a module called Unique field which makes sure the no 2 nodes have the same title(and thus unique URL for each node).

In your case, since the damage is already done, the best option for you is to change your title or url to something like **/gandhiji-park-state-2**

**Suggestion :**

This is just a suggestion for URL structure and SEO. A general rule of thumb that I follow when creating URL, is to rank the keywords in the URL. The highest ranked keyword should come at the end of the url. For example **www.example.com/less-specific-keyword/more-specific-keyword**. This way you can rank higher in search engines for the same content and also users can get an idea about your content just by looking at the url. For example, in your site you can structure the URL like this www.example.com/state/park/park-name.

---
Tags: 6, path-aliases
---


title: Actions - What are objects and context

text:
# Question
Title: Actions - What are objects and context
Can somebody explain to me what the difference is between an object and context within the advanced action setup please.

I understand what an object is but am failing to understand what context is.

Thanks.

# Answer
> 4 votes
If you are talking about the $context variable (and I think you do), then the official description is: an associative array containing extra information about what triggered the action call, with $context\['hook'\] giving the name of the hook that resulted in this call to actions\_do() (from here: http://api.drupal.org/api/drupal/includes!actions.inc/function/actions\_do/7)

But if you want to understand it better, this page is very useful: http://www.sysarchitects.com/node/47

# Answer
> 0 votes
The context is used to identify how the action is being triggered so that, if necessary, it can handle the object differently — e.g. an action that has to do different things depending on whether a node is being inserted for the first time or updated.

# Answer
> 0 votes
Drupal supports a trigger/action system. So you can easily give drupal some object id(s) and say I want these Actions to occur to this object, at some time or context.

Here is a small example from some code I run via drush in a php-eval:

```
$q = new EntityFieldQuery();
$types_to_publish = array('page');
$q->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $types_to_publish, 'IN');
$results = $q->execute();
foreach ($results['node'] as $node) {
  $current_node = node_load($node->nid);
  $migrator_user = user_load_by_name('d7migrator_user');
  $current_node->uid = $migrator_user->uid;
  $actions = array('node_publish_action', 'node_save_action');
  $context['node'] = $current_node;
  actions_do($actions, $current_node, $context, NULL, NULL);
}
drupal_set_message('Done publishing content.');

```

I do this because I'm migrating some node via node\_export and then apply the Workbench module and currently need to re-save nodes to that Workbench can properly set the publish state for the given NIDs. We dont need to supply a `$context` here beyond the `node` because I'm not hooking into the lifecycle of a page request or form POST processing.

---
Tags: 7, actions
---


title: How to get facebook user id after login

text:
# Question
Title: How to get facebook user id after login
I am using Drupal for facebook module to login into my drupal site. How can i get facebook user id after user login to my site. I want to store user details and give a chance to edit his profile. I can able to track firstname and Lastname,Email But i can not able to track user id.

# Answer
The mapping information is stored in the fb\_user table in the database.

I'm not aware of any API functions the module provides for querying this data but I wouldn't be surprised if something exists.

If all you are doing is authentication I'd have a look at FBOauth module instead, it provides a similar table and makes the whole process a lot easier.
> 1 votes

---
Tags: users, social-network
---


# Question
Title: Need to flush cache after node translation
I have a Drupal 6 site running with multi language support. When I translate a node and get redirected to the newly translated node only the headline is visible. If I flush the cache using the administration tools I can see the rest of the node.

Why is this happening and I how do I prevent it? I feel like I have tried everything! For example trying:

```
  drupal_flush_all_caches();
  cache_clear_all();
  cache_clear_all('*', 'cache', TRUE);
  cache_clear_all('*', 'cache_content', TRUE);
  cache_clear_all('*', 'cache_page', TRUE);
  cache_clear_all('*', 'cache_menu', TRUE);
  cache_clear_all('*', 'cache_filter', TRUE);
  cache_clear_all('*', 'cache_views', TRUE);
  cache_clear_all('*', 'cache_views_data', TRUE);
  cache_clear_all('*', 'cache_update', TRUE);
  cache_clear_all('*', 'cache_block', TRUE);
  cache_clear_all('*', 'cache_form', TRUE);

```

Using `function mymodule_node_form_submit($form, &$form_state)` and `function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL)`. I have verified that both hooks works using Devel.

I have also tried looking into the cache tables to try and figure out which rows change when flushing the caching using the administration tools, but without luck.

**UPDATE JULY 18:** Even if I turn off the cache I cannot see the translated node before I flush the cache. How is this even possible?

**UPDATE JULY 18 PT2:** I think I have found the problem. In the table cache\_content a row called e.g. `content:1269:1270` got the value(data) `a:0:{}`. If I delete this row the text appears. To me it seems that it does not cache the new translation correctly, and thus saving an empty cache which makes the translated node empty. But how do I solve this? Even with `db_query('DELETE FROM cache_content');` in the submit hook the row gets created.

Thanks in advance.

# Answer
Run the cache clear in a shutdown function. A little bit of a hack but it should work.

```
<?php
register_shutdown_function('cache_clear_all', 'content:' . $node->nid . ':', content_cache_tablename(), TRUE);
?>

```

Taken from content\_delete()
> 1 votes

---
Tags: caching
---


# Question
Title: How can I speed up a site that is slow because a huge locales_source table?
I'm working on a site that slows down to an unbearable crawl when you view it in a different language (specifically "zh-hans"). When looking at the Devel query log, this appears to be because this query takes about 5 minutes.

```
SELECT s.source, t.translation, t.language
FROM locales_source s
LEFT JOIN locales_target t
  ON s.lid = t.lid
  AND t.language = 'zh-hans'
WHERE s.textgroup = 'default'
  AND s.version = '6.25'
  AND LENGTH(s.source) < 75

```

The reason it takes so long is that the locales\_source table has *almost 1 million rows*, even though there are only 1 thousand nodes on the site. This seems like an extremely large amount to me. So my questions are:

1. Is this normal?
2. If not, how can I go about identifying which of the data in locales\_source is not applicable or bad? I can't find the way to map it back to the original source (node body, title, menu item, etc.) so I'm not sure how to determine if the original source exists and is valid.

The locales\_source table looks like this, if it helps.

| Field | Type | Null | Key | Default | Extra |
| --- | --- | --- | --- | --- | --- |
| lid | int(11) | NO | PRI | NULL | auto\_increment |
| location | varchar(255) | NO |  |  |  |
| textgroup | varchar(255) | NO | MUL | default |  |
| source | blob | NO | MUL | NULL |  |
| version | varchar(20) | NO |  | none |  |

# Answer
> 7 votes
Yes, 1 million is an extremely high amount. That's not normal.

The amount of nodes should have nothing to do with that table, because content translations happens by creating separate nodes for each language that are linked together.

What is added to that table are all strings which are passed through t(), and everything that is registered through the various i18n modules (menus, terms, ...).

t() must not be used for user generated content but this is often done and I suspect that might be responsible for your amount of rows in that table. The problem with something like t($term-\>name) is that the identifier is the term name. If you change your original term name, then your translations are lost and the source entry will stay there forever. See below on how to identify problems here.

The interesting column to check where something is coming from is the location, there are 3 different possible types of values in there:

1. When imported from a .po file (e.g. official translations from localize.drupal.org), the location is filename:line. These are most likely ok and should be much much less than 1 million.
2. Translations managed by i18n\_string have some sort of context/identifier in there, that looks like this: taxonomy:term:1:name. That allows to look up a translation based on a unique identifier of something that won't change. There could be many of these, if you have many taxonomy terms/huge menus but again, not 1 million (except you have 1 million or close terms). You can also identify them by the text group, case 1 and 3 is both textgroup default, while this has a textgroup for each source type (taxonomy, menus, ...).
3. Every string passed to t() that is not yet in that table is automatically added. In that case, the location is the URL of the page where this string first occured. Those will probably be the most interesting ones for you.

What you need to find out is which pages are adding these dynamic translations and then track down the exact module/call and fix it. There two ways to start. First, look at the most recent additions to that table to see what URL's you have in there (last page on the translate overview, or you can look directly in the database). The second option is group by location and then sort by count(), which might forever on a table of that size. But it's likely that a large amount of sources have been added on the same page. Once you know the page, it's time to do some profiling there and track down who exactly is calling t() often.

Two contrib module examples that I recently identified while doing a performance review on a site:

1. The site had two hierarchy/relation select boxes using hierarchical select, which currently falls back to t($term-\>name) if i18n\_taxonomy is not installed. That was a free tagging vocabulary with 10k terms and this resulted in 40k calls to t(), which obviously also makes it extremely slow. This issue is still there, I need to find the time to provide a patch.
2. The other case was the print module, which "translated" the node title on the print page. I think this was recently fixed, but the already added sources will stay in that table.

Once you identified the problem, you need to fix it and then remove the existing strings from that table, e.g with a like 'taxonomy/term/edit/%' condition for the term edit pages. Just removing the strings can be useful to quickly check how it affects the site load time but they will get re-added as soon as the problematic code is executed again.

For the record, the site that I looked into had "only" 40k entries in that table but even that resulted in cache entry of the short translations of 10MB (in PHP, not serialized).

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


# Question
Title: Proper way to delete Images uploaded in Image fields
What is the proper way, through code, to delete images on an entity?

I have a cron function that processes like so:

```
function processQueuedPropertyPhotoset($entity, $photos) {
if (!is_array($photos)) {
  watchdog('mymodule', 'Trying to process photos for a property but it has no photos. Aborting.');
  return;
}

if (is_array($entity->field_property_image) && count($entity->field_property_image)) {
  foreach ($entity->field_property_image['und'] as $key => $value) {
    $photo = file_load($value['fid']);

    if ($photo) {
      file_delete($photo, TRUE);
    }
  }
}

// wipe clean the records in the field_ table

unset($entity->field_property_image);
$entity->save();

// rest of code processes and saves new images

```

I am curious if this is the proper or effective way. Also, do the image derivatives generated get cleaned out by Drupal this way too? I notice there is a 'deleted' field in the database on the Image field table definition. When is this ever used?

This method cleans the entity data, removes the images from the server and files table. I am simply curious as if is an acceptable method that covers all the bases in Drupal or if there is an API function to simplify this. This function is called daily when we run a third party integration web service.

# Answer
If you want to make sure that the image files are definitely deleted (regardless of whether or not another part of the system has declared a vested interest in that file), what you're doing looks spot on to me.

There's already a function run by core on cron (`system_cron()` specifically) that deletes files marked as `FILE_STATUS_TEMPORARY` in the `file_managed` table, but that function consults the `file_usage` table and doesn't delete if the file is reported as being in use (which it will be if the field values haven't been removed from the entity yet).

Passing `TRUE` as the second parameter to `file_delete()` like you're currently doing is the cleanest way to force the deletion (any records in `file_usage` are also cleaned up so there's no stale data).

The image derivatives will be deleted automatically, as the image module implements `hook_file_delete()` and flushes the image cache for the file URI (see `image_file_delete()`).

The `deleted` column in the field tables is just there to mark the fields for deletion at a later date (I imagine so the subsequent page load isn't affected if there's a lot of data to delete). There are identical columns in the `field_config` and `field_config_instance` tables for the same reason.

The field module purges any data marked for deletion in the cron run (`field_cron()`).
> 2 votes

---
Tags: 7, entities, media
---


# Question
Title: Drupal 7 - how to use jw player using videos located on a CDN
We are currently using Drupal 6 and are in the process of upgrading to D7.

When I went to see if the module created by LongTail had a version compatible with D7 I found out that they don't have one, but they recommended to use this one:

http://drupal.org/project/jwplayermodule

The problem I'm currently facing is that I can't figure out how to use this module with videos that we already have in our CDN.

Any way to do this without having to upload my videos to the site?

Thank you,

Onema.

# Answer
> 2 votes
I did something similar for flowplayer. I had nodes created for legacy videos stored in Amazon S3 and added this code to the node--video.tpl.php:

```
 $mediaid = $content['field_mediaid']['#items'][0]['value'];
  if ($mediaid != '') {
      $video2 = '<a href="http://username.s3.amazonaws.com/videos/ka/'.$mediaid.'.mp4" id="player" class="flowplayer"></a>';
              flowplayer_add('#player', array(
                'clip' => array(
                  'autoPlay' => TRUE
                ),
              ));

        print '<BR><BR>';
        print $video2;

```

There are other player options available as well, video.js seems to be more modern.

---
Tags: 7, media, cdn
---


# Question
Title: Displaying fields from my content types in a module
I am learning how to write modules at the moment. The following piece of code simply pulls out of the database some data and selects just the nid, title and created fields

```
function photo_gallery_contents($display){

$max_num = variable_get('photo_gallery_max', 3);

$query = db_select('node', 'n')
->fields('n', array('nid', 'title', 'created'))
->condition('status', 1) //Published.
->condition('type','portfolio') // Only want our photos aka Portfolio content type
->orderBy('created', 'DESC'); //Most recent first.

if ($display == 'block') {
// Restrict the range if called with 'block' argument
$query->range(0, $max_num);
} // Now proceeds to execute().
// If called by pge, query proceeds directly to execute()

return $query->execute();

```

}

This works fine but how do I access the other fields I created for my "portfolio" content type such as "field\_image" or "field\_category" both of which I added? I just cannot work out how to do this. Your help will be so appreciated!

I've written other hooks that represent this information on the page or block, at the moment I am showing a list of links to my nodes. I want them to be images with links instead:

```
function _photo_gallery_page() {
$result = photo_gallery_contents('page');
//Array to contain items for the page to render.
$items = array();
//Iterate over the resultset and format as links.
foreach ($result as $node) {
  $items[] = array(
  'data' => l($node->title, 'node/' . $node->nid),
  );
}

if (empty($items)) { //No content in the last 2 weeks.
  $page_array['photo_gallery_arguments'] = array(
    //Title serves as page subtitle
    '#title' => t('All photos from ever'),
    '#markup' => t('No photos available.'),
  );
  return $page_array;
}

 else {
  $page_array['photo_gallery_arguments'] = array(
    '#title' => t('All photos from ever'),
    '#items' => $items,
    //Theme hook with suggestion.
    '#theme' => 'item_list__photo_gallery',
  );
  return $page_array;
}

```

}

So how do I swap $node-\>title to show the image instead?

# Answer
> 2 votes
The best way would be to grab just the node ids from the table, and use the `node_load_multiple()` function to load the node objects.

The field data will be attached to those objects, and you can use other API functions to extract the data/build the display HTML (`field_get_items()` and `field_view_field()` respectively).

Some sample code that should help:

```
function photo_gallery_contents($display){
  $max_num = variable_get('photo_gallery_max', 3);

  $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('status', 1) //Published.
    ->condition('type','portfolio') // Only want our photos aka Portfolio content type
    ->orderBy('created', 'DESC'); //Most recent first.

  if ($display == 'block') {
    // Restrict the range if called with 'block' argument
    $query->range(0, $max_num);
  }

  // Fetch the results for the nid field into an array
  $nids = $query->execute()->fetchCol();

  // Load the node objects and return
  return node_load_multiple($nids);
}

function _photo_gallery_page() {
  $result = photo_gallery_contents('page');

  //Array to contain items for the page to render.
  $items = array();
  //Iterate over the resultset and format as links.
  foreach ($result as $node) {
    // Build a render array based on the field's display settings.
    $image = field_view_field('node', $node, 'field_image');

    // Render the array down to the image HTML
    $image_html = drupal_render($image);

    $items[] = array(
      'data' => l($image_html, 'node/' . $node->nid, array('html' => TRUE)),
    );
  }
}

```

---
Tags: 7, nodes, database
---


# Question
Title: Links displaying as plain text, and html tags not applying, no matter which text format is selected
I have a text field type, that I'd like to be able to include links within. It appears that all of the formatters should be able to do this by default, and that the full/filtered html formatters should be able to handle html tags. However, for some reason, my text field is not doing either of these things. Links are simply appearing as plain text.

I think that they did work before, although I can't exactly remember where else in the site these filters are used to double-check, but they are no longer honoring links or html. Additionally, if full/filtered html is selected, then any html tags are hidden from view but are not being applied to the text. This leads me to believe that the formatter is recognizing the tags, but for some reason is failing to process them. Any suggestions?

So, just in case I wasn't clear at all:

* Links are displaying as plain text (e.g. typing in http://www.google.com simply renders as `http://www.google.com` \- plain text, no link). This is occurring with all formatters, including the "Plain Text" formatter, even when "Convert URLs into links" is selected. This is occurring with email addresses as well.
* All html tags are being ignored (e.g. entering `<a href="http://www.google.com">Google</a>` or `<a href="/local/links">Local Link</a>` displays only as `Google` or `Local Link`, without rendering the link. Additionally, something like `<strong>Bold</strong>` renders as Bold, without the style applied).

# Answer
It's hard to suggest a solution without examples, but I'd suggest you check the order of your text format filters (/admin/config/content/formats/full\_html) and see if:

1. **Convert URLs into links** is still turned on
2. There are no additional filters acting on links or `<a>` tags that would cause them to be killed or hidden
3. Make sure your links look like links! Obscure ones like `bit.ly/4321` or even `google.com` won't get picked up. If they aren't getting picked up, adding `http://` to the front of it normally triggers the auto URL filter.

If that doesn't work, see if you can post some example code. If we can see how they are being hidden, we might be able to assist better.
> 1 votes

---
Tags: entities
---


# Question
Title: How to make calendar block show site events?
I have a website in which I use the Calendar module in combination with a content type I created. While I manage to achieve the calendar page to show up the events in their dates, how can I make the same for the calendar block? For example when an event has a "from date" of 20 August, I want the calendar block to have that 20 August date as a link to the event.

# Answer
> 1 votes
I think that you probably want to use the views module to create a custom block that contain the calendar items. Here is an example...

http://drupal.org/node/1250714

---
Tags: blocks, datetime
---


# Question
Title: Custom region in theme not on front page?
This is probably (hopefully) a simple question, but I can't figure it out: I'm trying to customize a theme to add a div/region for a "banner" that will display the title of the page on each page...except for the front page. The front page will have a similar "banner" but with different content, more like a promotional thing.

I thought the simplest way to include the banner with the title was simply to move the title rendering in the page.tpl.php:

```
  <div id="banner"><div class="section clearfix">
      <?php print render($title_prefix); ?>
      <?php if ($title): ?>
        <h1 class="title" id="page-title">
          <?php print $title; ?>
        </h1>
      <?php endif; ?>
      <?php print render($title_suffix); ?>
  </div></div>

```

This works fine, but then I will get it on the front page as well, and there I want it replaced by a similar banner but with custom content, preferably inserted by a custom block I will create.

How do I do this separately for the home/front page?

# Answer
> 3 votes
You can differentiate a front page using drupal\_is\_front() API

```
<?php if(!drupal_is_front_page()):?>
 <div id="banner"><div class="section clearfix">
      <?php print render($title_prefix); ?>
      <?php if ($title): ?>
        <h1 class="title" id="page-title">
          <?php print $title; ?>
        </h1>
      <?php endif; ?>
      <?php print render($title_suffix); ?>
  </div></div>
<?php endif;?>

```

Or you can create a new TPL `page-front.tpl.php` and omit this div element in that TPL so that it never gets printed. This TPL will be used for front page only.

# Answer
> 3 votes
You can create a page--front.tpl.php file in your theme. This file is the same as page.tpl.php but only for the front.

Remember clear cache after the creation of the file.

---
Tags: theming
---


# Question
Title: Is there a way to hide the price on a product using Drupal Commerce?
Basically I want to create a commerce site, load all the products but not give a price yet, for competitive reasons.

Instead of displaying 0 I want to:

1. Change the price to - "Call for price"
2. Hide add to cart button

At a later stage when I give the item a price it should:

1. Display the price
2. Display add to cart button

I know this is possible in Magento but would rather try using Drupal Commerce. Any tutorials or links will be appreciated.

# Answer
> 0 votes
I guess giving the product a price is a manual process.

To make things clear I suggest adding a 'price hidden' boolen field to the product content type. Based on this field you can adjust the output of the product by implementing hook\_node\_view\_alter.

# Answer
> 0 votes
With Display Suite you can use a drag & drop interface to hide the price and add-to-cart button by clicking on *manage display* for the product display content type. You can also create a *code field* for the *call now* button (if you don't want to use a custom template) by going to *Structure -\> Display Suite -\> Fields -\> Add a code field* and that will then also be available on the drag & drop manage display screen.

---
Tags: 7, commerce
---


# Question
Title: How to rewrite link to taxonomy term in Views when using Pathauto?
The default language of my site is English. Taxonomy terms are translated using Entity Translation. I have created a view that uses aggregation to show Japanese terms (name provided by the Title module).

However, the Japanese terms do not have a path alias, so I need to rewrite the link provided by the view to point to the English term. The URL aliases of the English terms are generated by Pathauto, which strips some words ("to" in "Things I like to do").

Example:

* English term: Listening to Music
* Pathauto alias: listening-music
* Japanese term: 音楽鑑賞
* Desired output: 音楽鑑賞 (link pointing to listening-music)

I tried rewriting the link to \[name\] (the English term) with conversion to lowercase and spaces converted to dashes, but this causes the link to be listening-to-music, not listening-music. Ideally, I would like to keep pathauto settings as they are and somehow grab the URL of the term within views. Is this possible?

# Answer
> 4 votes
To get path of taxonomy term in default language (in your case it is English) you can use url() function, example:

```
$term_url = url('taxonomy/term/'. $term->tid, array('language' => language_default()));

```

# Answer
> 0 votes
I solved this by removing all the prepositions from the "Words to exclude from paths" on the Pathauto configuration page and then deleting and bulk updating all taxonomy aliases. For those aliases with () or other symbols in their names, I manually added redirects using the Redirect module. Not pretty but it works.

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: How to add link in user menu which is available for loggedin users in drupal
I want to add link for member area in user menu which is only available for logged in user.Please let me know how i can do this.I am using Drupal 7.

# Answer
> 2 votes
I have taken the easy way out on this one with all my projects. I have two menus, one for logged in users and one for logged out. This works because I can set the 'logged out' menu block to show only to anonymous users, and then I can set the logged in for only authenticated users (in block settings). The solution works great with no custom programming needed!

---
Tags: routes, users
---


# Question
Title: How to display nodes based on the taxonomy terms of the current logged in user, with multiple vocabularies?
**Say I have 3 taxonomy vocabularies:**

Products, Professions and Support

**Each vocabulary has 2 terms:**

Products -\> *product1*, *product2*

Professions -\> *profession1*, *profession2*

Support -\> *support1*, *support2*

**Users can be tagged with terms. User A is tagged with:**

product1 and support1

**Nodes can be tagged with terms. Node 1 is tagged with:**

product1

**Node 2 is tagged with:**

support1

**Node 3 is tagged with:**

profession1

So when **User A** logs in and goes to the view, they should see **Node 1** and **Node 2** only. I can't seem to achieve this in views. It's possible when there is just one vocabulary, but i can't seem to get it done when there are multiple vocabularies involved. Can anyone help without coding? Or perhaps I need to use code?

# Answer
Did you try this **using fields instead of taxonomy**? I personally prefer using fields over taxonomy since fields are more flexible with views. In your case, if your site is still under development I suggest you to use fields and try out the same.
> 0 votes

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


title: Module for fedex shipping for drupal 7

text:
# Question
Title: Module for fedex shipping for drupal 7
I am using Drupal Commerce version 7.

I came across requirement for `FEDEX shipping module`. I installed it but in it's requirements, **uc\_quote** is missing. I didn't find this module for Drupal 7.

I searched for this but it is supported only in Drupal 6.

# Answer
uc\_quote is a part of the main Ubercart module. You can find it in the directory structure of ubercart at `ubercart/shipping/uc_quote`. And it is obviously present for Drupal 7 (as part of Ubercart 3.1).
For commerce shipping there is a sandbox project, but I haven't tested it.
> 2 votes

---
Tags: 7, commerce
---


title: Drupal 7, AJAX and browser history

text:
# Question
Title: Drupal 7, AJAX and browser history
I have a website which is AJAX enabled for a great part.

My client now of course wants the browser buttons to behave as expected, which means the page should revert to the previous states when the 'back' button is pressed and so on.

I know there are solutions for this use case, the most interesting one being (seemingly) history\_js and its fellow Statehandler module.

I didn't test it yet, because it seems to be heavily based on coding - which I could handle - but I wonder if there is a more elegant (mean : abstract) solution.

The following points are mandatory :

* It must work with AJAX Views, including dynamic filters.
* It must work with custom AJAX links.
* It would be wonderful if it worked with popups (Colorbox style for example), but I think it's a lot to ask for so I could do without it.

What is your experience with AJAX browser history in Drupal 7 ? Any hint on the pitfalls you encountered would be very appreciated. A working solution or a good tutorial would be amazing.

# Answer
> 1 votes
For utilizing browser history and reload buttons with AJAX request, you can use the jquery plugin "jQuery Address" http://www.asual.com/jquery/address/

---
Tags: 7, ajax
---


# Question
Title: Tag autocompletion fails for anonymous users?
On a site, anonymous can create content. The content type has a term reference field, which works fine for logged in users.

However, for anonymous, the fields JS is "dead", no autocompletion happens, and I can't even see an http request going off.

Obviously I assumed is has to be a permissions issue as it only affects anonymous, but I can't seem to figure out what permission that would be, and if it was, then it seems like the http request would go off.

# Answer
Figured it out myself while I was typing the question.

Since JS didn't work at all, I checked the console, found a CKEditor related error, fixed it, and things went back to normal.
> 0 votes

---
Tags: taxonomy-terms, javascript
---


title: Create custom block with node title?

text:
# Question
Title: Create custom block with node title?
I would like to be able to use a region which is to contain the title of the current node. In the default theme the title is output in the main content, but I want it in this custom region instead. But I cannot find a block for the node title. Can I create it?

# Answer
> 3 votes
Remove the title from the node.tpl.php and create a new block with the following PHP code:

```
<?php
$node = node_load(arg(1));
print $node->title;
?>

```

Enable visibility only on view node pages.

CCK Blocks is a very handy module for these things, but unfortunately the node title isn't listed as an element in display mode.

\[EDIT\]

If you are on D7 and you are using Omega theme, Delta module should work for you. Check specifically Delta Blocks module from that package.

# Answer
> 0 votes
You could create a new block with the hook\_block\_ ... hooks.

Here's a block example how to do this. In hook\_block\_view, you can define the node title in `$block['subject']`.

Have a look to the code sample from Ivanhoe123 how to get the node title.

---
Tags: blocks, theming
---


# Question
Title: Can I relate a node with a taxonomy term via its description and not its name?
I import xml files into Drupal. These files use numbers for location which I want later to be interpreted into names (like Spain, Greece etc). So I would like the taxonomy terms to have the name of the countries but then how could I relate the node to the taxonomy term? I was thinking to use the description or another taxonomy field to relate it with the node instead of the name. Is that possible? Thank you!

# Answer
If you use drupal 7 you add a term reference field to the content type, and choose which taxonomy terms are related to the node on the add/edit page for the node. There refs are done by term id (tid) not by name/description
> 0 votes

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


# Question
Title: Remove datatype attribute from meta about tag
I'm trying to validate my Drupal 7 website on http://validator.w3.org but I can't keep getting the following error:

> Attribute datatype not allowed on element meta at this point.

This is because `<meta about="/frontpage" property="sioc:num_replies" content="0" datatype="xsd:integer" />` automatically gets the 'datatype=xsd:integer' attribute. I want to remove the datatype attribute altogether.

# Answer
> 4 votes
Apparently the meta tag isn't the problem. The problem is the validation service and how you use it. After some digging I found this article. The author suggest using a different validation type namely: http://validator.w3.org/nu/ with the following preset set in the additional options: "HTML5 + SVG 1.1 + MathML 2.0 + RDFa 1.1 + Microdata". This will validate said meta tags without any errors.

# Answer
> 1 votes
I don't know what effect this will have on the validity of that particular tag, but you can remove the property by implementing `hook_html_head_alter()` (either in your theme or a custom module file):

```
function MYTHEME_html_head_alter(&$head_elements) {
  if (isset($head_elements['rdf_node_comment_count'])) {
    unset($head_elements['rdf_node_comment_count']['#attributes']['datatype']);
  }
}

```

# Answer
> 0 votes
Use this function to alter meta tags...

```
// hook_html_head_alter().
function YOUR_THEME_html_head_alter(&$head_elements) {
  dsm($head_elements); // if you have Devel installed
  var_dump($head_elements); // else use standard PHP dump
}

```

---
Tags: theming, meta-tags
---


# Question
Title: Multiple pagination of arbitrary array of objects
I have an array with this structure:

```
$things = array('term1' => array(Object, Object, ... Object),
                'term2' => array(Object, Object, ... Object),
                'term3' => array(Object, Object, ... Object),
                 .... etc...

```

I want to be able to generate output like:

```
Term1

* Object 1
* Object 2
* ... etc ...

 < 1, 2, 3 > (<-- that's pagination :D)

Term2

* Object 1
* Object 2
* ... etc ...

 < 1, 2, 3 >

```

Which each list of things paginated (assuming there are more than x of them).

Is there a way I can achieve this?

A template function I can pass each of the individual arrays of Objects into to get pagination?

If it matters, this is all taking place inside a block, in D7.

# Answer
See Drupal Pagination with a Custom Query for full code example
> 0 votes

---
Tags: paging
---


# Question
Title: Adding classes to individual list items in a site map
I am using the Site Map module in my site but I need to style my list items individually. Is there a way to add a different class to each list item in the site map?

# Answer
> 0 votes
I prefer to use Menu Block blocks on a basic page for building a sitemap - it gives more control over the menu order, title display, etc. (unless, of course, you need the RSS feed icons in the sitemap - then the Sitemap module is more useful.) With Menu Block, you get a unique mlid class for each list item.

---
Tags: 7, theming
---


title: Email validation '+' not accepting

text:
# Question
Title: Email validation '+' not accepting
I have written email validation as follow.

```
if($email != ''){
             if (!ereg("^[_a-zA-Z0-9]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$",$email)) {
               form_set_error($email, t('Please enter a valid Email address.'));
             }
          }

```

But when i try to register with 'test.byme+1@gmail.com' , Not accepting with '+'. Can any one correct my code..Thanks

# Answer
The problem with your code is that you aren't allowing the + in the regex.

```
<?php

$email = 'test.byme+1@gmail.com';

if ($email != '') {
  if (!preg_match("/^[_a-zA-Z0-9]+(\.[_a-zA-Z0-9-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$/",$email)) {
    print "'{$email}' is not valid\n";
  } else {
    print "'{$email}' is valid\n";
  }
}

```

I converted this to use PCRE. Note the change right before the `@` in the regex.

But don't use this. Use the builtin as @Berdir suggested or use the Email Field module, which has some nice extras in addition to validation.
> 4 votes

# Answer
No need to reinvent the wheel: valid\_email\_address().
> 11 votes

# Answer
Couldn't resist adding this in...the only regex that will correctly identify any***** valid email address:

```
(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)
```

Scary, huh?

*****With the following caveat:

> This regular expression will only validate addresses that have had any comments stripped and replaced with whitespace

From http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
> 5 votes

# Answer
A regex to validate the a version of the `addr-spec` RFC grammar element \[RFC 822, but corrected to not have local-parts like `"foo bar".baz."a b c"` as later versions of the RFC, and RFC 821, only allow a single quoted string rather than a quoted string as part of a dot string\] without allowing embedded comments or whitespace/linebreaks:

```
(?:[^()<>@,;:\\". \000-\031]+(?:\.[^()<>@,;:\\". \000-\031]+)*|"(?:[^"\]|\.)*")
@
(?:[^()<>@,;:\\". \000-\031]+(?:\.[^()<>@,;:\\". \000-\031]+)*|\[(?:[^ \]\\]|\.)*\])

```

I have not tested this, so there may be typos or markdown problems.

Note that this does *not* allow a username portion containing two dots in a row, or beginning or ending with a dot, or a domain ending with a dot, as the spec does not technically allow these. It does allow such as `foo@1.2.3.4`, even though by the spec such an address should be foo@\[1.2.3.4\], to simplify the number of character classes used.

A simpler version of the regex which allows two dots in a row or beginning or ending with a dot, despite the spec not technically allowing this:

```
(?:[^()<>@,;:\\" \000-\031]+|"(?:[^"\\]|\.)*")
@
(?:[^()<>@,;:\\" \000-\031]+|\[(?:[^ \]\\]|\.)*\])

```
> 2 votes

---
Tags: emails
---


# Question
Title: When hook_field_load and hook_field_formatter_view are called?
I have implemented the `hook_field_load()` and `hook_field_formatter_view()` function to replace some characters in a specific field's value. But they don't seem to be called at all. I wrote some command like `exit()` and `print_r($field)` in the hooks but nothing happens.

When this hooks are called? (and is this the correct way to do alter field values for view?)

# Answer
> 5 votes
`hook_field_load()` and `hook_field_formatter_view()` aren't hooks really. They rather are callbacks which only can be used from a module implementing the field in question by itself. The documentation at api.drupal.org for both hooks is not very clear in that by stating nothing or just a vague:

> Define custom load behavior for this module's field types.

When grepping through the Drupal 7 code you never see this so called hooks invoked by `module_invoke_all()` which is a clear sign for that functions are not handled like hooks.

`hook_field_attach_load()` may be used instead of `hook_field_load()` which is a real hook.

See also the discussion at http://drupal.org/node/702586 for that matter.

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


title: Form Field Containers

text:
# Question
Title: Form Field Containers
How do I get rid of the outer box around the location field for example. I don't like how the location title + background colours are repeated twice for additional fields.

I have this issue on every template, not just the one displayed so can answers please be generic so I can do it on every template.

# Answer
> 0 votes
Drupal uses renderable arrays, so there is probably something like this:

```
'location_outter' => array(
  '#type' => 'fieldset',
  '#title' => 'location',
  'location_inner' => array(
     '#type' => 'fieldset',
     '#title' => 'location',
     'city' => array(
        '#type' => 'textfield',
        '#title' => 'City',
     ),
   ),
);

```

So i think you can, if it is form, try use alter hook, for example `yourmodule_user_form_alter` and modify that renderable array.

---
Tags: theming
---


# Question
Title: Javascript Not Functioning At All on Drupal 7
I haven't worked on building out my site for about 5 or 6 days only to come back to find that Javascript is completely non-functional on my site. As far as I can remember (about 90% positive), everything worked fine last time I worked on it.

Using Firebug, I've found the following error 4 times:

```
jQuery is not defined
})(jQuery);

```

And this error 7 times:

```
Drupal is not defined
jQuery.extend(Drupal.settings, {"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"capstoneskele","theme_token":"4I-qysgFuZXzCXVlRhgBo6i118JK5s1LLy2-a_ti1lE","js":{"misc\/jquery.js":1,"misc\/jquery.once.js":1,"misc\/drupal.js"......(cont'd)

```

I've been mostly playing around with a custom theme, so perhaps it's something with one of my tpl.php files - I'm new to Drupal so I really don't know. Any ideas/help would be greatly appreciated as my graduating college is dependent on this project...thanks!

*please let me know what further details I can provide also...*

# Answer
1. Check that in html jquery.js and drupal.js correctly open - just click on links in firefox html source view, it's should open js files.
2. Check your jquery.js and drupal.js in misc folder, if files exists, compare with drupal archive.
3. Check how many jquery-VERSIONS.js files attached in html, possibly conflicts can be there.
4. Check your html source for embedded js scripts (viruses like it).
> 1 votes

# Answer
Verify the scripts are being loaded in the correct order: any script that is loaded before jquery will give a 'jquery is not defined' error if it tries to use it.

Just open a page in firebug and inspect the scripts loaded at the bottom of the page; they're loaded in the order in which they appear in the markup.

If this is your problem, then find the places where the troubled scripts are being loaded by drupal (often via `add_js()`) and try setting a weight parameter. Something like:

`drupal_add_js( filename.js, array('weight' => 5));`

See: http://drupal.org/node/756722
> 0 votes

---
Tags: theming, javascript
---


title: How to debug a delete query?

text:
# Question
Title: How to debug a delete query?
I'm trying to debug an issue with a delete query not happening. I've added logging before the query, after the query and I'm logging the return value of the query. Everything looks right, the only problem is that the rows are still in the database.

It's a simple query, I can't see anything wrong with it:

```
$result = db_delete('cloud_files')
  ->condition('uri', $uri)
  ->execute();

```

I've checked the $uri in every way I possibly can and it's right. I've tried executing the delete query by hand and it works just fine. The table name is correct, the field name is correct, the $uri is correct. I don't know what else to check.

I've used the Devel module to log the queries and while it logs queries that happen both before and after this query, it doesn't log this query at all. However, I've got error\_log() calls before and after the query so I know this code is being run and it reports that it is running successfully.

I've even added code to select the data before deleting it and it works!

```
$select = db_select('cloud_files', 'cf')
                ->fields('cf')
                ->condition('uri', $uri)
                ->execute();

$entry = $select->fetchAssoc();

error_log("entry: ".print_r($entry, true));

```

That works, it prints out the row I'm trying to delete.

dqp() doesn't work for delete queries, so I don't know of any way of getting the truly final sql being executed.

I've made sure that if I connect using the mysql command line client from the drupal host with the user/password in the drupal config that all of the commands work.

How do I debug this? What is going wrong?

EDIT:

Is there any kind of transaction happening during a delete action? Could this behavior be the result of those delete queries happening in a transaction that gets aborted?

# Answer
With a problem like this, you may need to turn on MySQL query logging. Once logging is enabled, put a noticeable query right before and after your DELETE query (do you can have something easy to search for), check the logs, and go from there. Just be sure to disable logging when you are done. It can kill performance and also fill up the disk pretty quickly.
> 2 votes

# Answer
It turns out that my guess was right about a db transaction getting aborted. node\_delete() begins a transaction and the action was being aborted after 2 minutes (there are a LOT of files to delete from CloudFiles and it took too long and the php process was killed). So, while the delete queries were issued, they were issued inside a transaction that got automatically rolled back.
> 0 votes

---
Tags: 7, database, debugging
---


title: drupal_mail() new line \n not working

text:
# Question
Title: drupal_mail() new line \n not working
I'm trying to insert a new line in message body using \n but it's not working. Tried already with \r\n and it doesn't work also.

Any help?

Tks.

# Answer
> 5 votes
Could be a couple things, without seeing any of your code it's difficult to help you.

Try:

1. Making sure you're using double quotes (`"`) instead of single quotes (`'`) around the new line characters. (This is because PHP does not interpolate strings defined by single quotes).
2. Setting the Content-Type to `text/plain` in the mail headers. (If you need HTML in your email, use `<br />` for new lines).

Also, you should always use `\r\n` with emails so the new line is recognized across all platforms.

# Answer
> 1 votes
Are using double quotes? They are necessary for the special characters to be interpreted correctly.

---
Tags: emails
---


# Question
Title: Override (shorten) breadcrumbs on Views page
I'm using Views 3 and I DON'T want the contextual filter to tack itself onto the end of the breadcrumb. In fact, for the whole view, I want only the static breadcrumb Home » My View Name. That's it. Nothing changed or added no matter what contextual filter I click, as long as I'm inside the view.

I tried doing an `array_slice($breadcrumb)` inside my view's tpl.php file but it seems to have no effect. However, in the same template, `$breadcrumb[] = 'salamanders'` gives me the word 'salamanders' as the second to last item in my breadcrumb. It does this regardless of whether I have my contextual filter set to override breadcrumb or not, and also irrespective of what text I've actually entered to override it with, when override enabled.

I've tried overriding the breadcrumb in hook\_page\_alter() inside a custom module as well. Again, I can add to but not subtract from the breadcrumb.

How do I remove elements from my breadcrumb when Views insists on tacking things on to it?

# Answer
If you're open for contributed modules, I'd suggest that you try Path breadcrumbs. This module will allow you to set up breadcrumb definitions, depending on the path of the page. There you define all items to appear as breadcrumbs, and thus specify whether you want the last item or not, linked or not.
> 1 votes

---
Tags: 7, views, breadcrumbs, theming
---


# Question
Title: AJAX checkboxes in Views to change node values
I have a use case in D7 where I need to make a listing of nodes in table format, and included in the fields are checkboxes that us AJAX to do things like publish/unpublish a node and set other field values in the node. I know I saw merlinofchaos mention somewhere that there is a way to do this in Views, but I haven't been able to find details on how. I can do it easily enough by creating a table and manually filling the cells, but I would like to use Views if I can. Does anyone know how this can be done?

Thanks.

# Answer
For the sake of documentation here, I ended up using a tableselect form element with a dropdown list of possible actions, in the way the core content admin form works (/admin/content).
> 0 votes

# Answer
If you can "do it easily enough by creating a table and manually filling the cells," you can easily leverage Views' global custom text field along with rewriting to create whatever you need. For example, create a view with whatever you want in the fields, just make sure one of them is nid. Then add a global custom text field after all of them and craft up whatever AJAX divs or spans or ids etc you need to call your functions, substituting the nid token where necessary in the markup. Make sure that javascript is including on your page and you should be on your way.
> 0 votes

---
Tags: views, ajax, forms
---


# Question
Title: How to check if node is being rendered inside view?
I need to check inside node template if its contents are being rendered through view or not. What is the best approach to do it?

# Answer
> 0 votes
I am unaware of a good way to do this. However, the proper Drupal way is to not have one part of a template rely on where it is being used. If something needs to be different, then render it out in a different manner.

For nodes in views, you can accomplish this with custom node view modes. Essentially, you implement `hook_entity_info_alter`, and create new view modes (ones inaddition to Full and Teaser). You can then use the **Manage Display** tab on the content type page to set up how you want the new mode to work, and then set up your view to use **Node style: Row** with your new display mode. Also look at @Andy's answer on How to add additional display(view mode) for node? for some options that make this easier to do just from the UI.

# Answer
> 4 votes
You can check to see if `$view` is set and is an object in the template file; if it does, it means the node is being rendered in a View. From there you can even check that the View is the correct one if you need to.

```
if (isset($view) && is_object($view)) :
  // Do something
endif;

```

---
Tags: 7, views
---


# Question
Title: Change the value of a piece of content using a comment
I have a content type which I don't want a user to be able to edit once it has been created. but I want them to be able to change 1 value and the way I want them to do that is through a selection box on a comment. For example, on the content type there is a priority field. When a user leaves a comment I have a selection box added to the comment with the same options.

How can I get that option box to sync with the option in the node itself?

Thanks

Kieran

# Answer
> 0 votes
Assuming your content type is called `your_content_type` and your module is called `yourmodulename`, you can use the following code:

It will set some state when a none-priviledged user posts a comment, and show a state selection UI for priviledged users. The state will be saved to the CCK `field_erledigt_warten` in the node in either case.

```
<?php
/**
 * Implementation of hook_comment().
 * Fill a CCK field  in Drupal 6
 */
function yourmodulename_comment(&$comment, $op) {
  global $user;

  if (is_array($comment)) {
    $node = node_load($comment['nid']);
  }
  else {
    $node = node_load($comment->nid);
  }

  if ($node->type == 'your_content_type') {
    switch ($op) {
      case 'insert':
      case 'update':
        if (user_access('edit field_erledigt_warten')) {
          // QD-Mitarbeiter
          if (isset($comment['field_erledigt_warten']) && $comment['field_erledigt_warten']) {
            if ($node->field_erledigt_warten[0]['value'] != $comment['field_erledigt_warten']) {
              $node->field_erledigt_warten[0]['value'] = $comment['field_erledigt_warten'];
              drupal_set_message(t('Status wurde auf %v geändert.', array('%v' => $comment['field_erledigt_warten'])));
              node_save($node);
            }
          }
        } else {
          // Kundenaccount
          $node->field_erledigt_warten[0]['value'] = 'neu';
          node_save($node);
        }
        break;
    }
  }
}

/**
    Implementation of hook_form_alter
 * Add a input box to the comment form
 */
function yourmodulename_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'comment_form') {
    if (is_array($form) && isset($form['nid']) && is_array($form['nid'])) {
      $node = node_load($form['nid']['#value']);
    }
    if (isset($node) && is_object($node) && isset($node->type) &&
      $node->type == 'your_content_type' && user_access('edit field_erledigt_warten')) {
      $states = array_flip(array('some', 'values', 'come', 'here'));
      foreach($states as $text=>$index) $states[$text] = $text;
      $status = $node->field_erledigt_warten[0]['value'];
      $form['field_erledigt_warten'] = array(
        '#type' => 'select',
        '#title' => 'neuer Status dieser Forumseite',
        '#default_value' => $status,
        '#options' => $states,
      );
    }
  }
}

```

# Answer
> 0 votes
This was what the Comment Driven module was supposed to do, but they seem to have hit a wall in terms of a D7 version.

http://drupal.org/project/comment\_driven

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


# Question
Title: Order of facets block change after the research
I'm new in Drupal and I have a problem when I use *search ajaxified* with *search api* and facet block.

My research works fine: When I click on the facet block that contains tags for example, my results are fine. After, my block are not anymore in the same order than before.

**For instance, before I click on one tag, the order are like this (all my blocks are in the left sidebar and so in the same region):**

* navigation
* Facet API: content type
* Facet API: Tags
* Saved search

**After the reseach in Ajax:**

* navigation
* Saved search
* Facet API: content type
* Facet API: Tags

All my Facets blocks are now at the bottom.

I followed all the instructions on Drupal.org given by the author of the module, and they worked fine, I just don't understand why my facet block are not in the same order after the ajax search. I've been trying for a couple days and cannot figure out a cause for this. Has anybody encountered this before?

Maybe I need to create another region to put only my facet block in, but I think there must be a better solution than that.

# Answer
It may not be the block weights, but just in case, can you see what I mean by making sure they're distinct.

Verify the below and see if you still have the same issue:
> 1 votes

---
Tags: ajax, search
---


# Question
Title: How do I force unique values within a multi-value set?
When programming my own field and autocomplete widget, how can I ensure that each delta has a unique value?

I would like to handle the case as much silently as possible, so to not bother user with validation errors. Most gladly I would just prohibit the autocomplete test from returning the duplicate matches but as far as I can see, the autocomplete function does not accept any context, just the search string.

Should I then keep the already selected values in a session variable - would it be *the Drupal way*?

# Answer
It might be easier to filter the autocomplete results using JS. You could either extend the prototype being used by Drupal or use some sort of trigger for when the results are being displayed.

I don't think that server-side solutions such as session variables and so on are practical as there's no guarantee that the results of previous calls were actually used by the user. Similarly, hacking the autocomplete feature to perhaps send existing values along with current user input is inherently impractical.
> 1 votes

---
Tags: ajax, entities
---


title: Migrate DBTNG query with JOIN and IN

text:
# Question
Title: Migrate DBTNG query with JOIN and IN
I'm attempting to write DBTNG query for a Migrate v2 class (D6), and I can't quite get a WHERE clause using IN to work. Here's the query I need:

```
select ngeuu.user_name, ngeu.email_address1
from nge_users ngeu inner join nge_user_to_group_tbl ngeutg on ngeu.user_id = ngeutg.user_id
where ngeutg.usergroup_id IN (16, 5608, 48, 34, 22, 26, 24, 18, 28, 20, 14, 12, 6879, 36);

```

This query returns the appropriate amount of rows. The way I have the query written in my Migrate class is:

```
$query = db_select('nge_users', 'ngeu');
$query->innerJoin('nge_user_to_group_tbl', 'ngeutg', 'ngeu.user_id=ngeutg.user_id');
$query->fields('ngeu', array('user_name', 'email_address1'))
$query->condition('ngeutg.user_id', array(16, 5608, 48, 34, 22, 26, 24, 18, 28, 20, 14, 12, 6879, 36), 'IN');
$query->duplicate();

```

but I start getting duplicate rows after 4 records, even though the query by itself doesn't return any. How do I need to change this to make it correct?

Thanks.

# Answer
Coming back to answer this one after a while. Here's the code I ended up using:

```
$query = db_select('nge_users', 'ngeu');
$query->innerJoin('nge_user_to_group_tbl', 'ngeutg', 'ngeu.user_id=ngeutg.user_id');
$query->fields('ngeu', array('user_id', 'user_name', 'email_address1', 'first_name', 'last_name'));
$query->condition('ngeutg.usergroup_id', array(16, 5608, 48, 34, 22, 26, 24, 18, 28, 20, 14, 12, 6879, 36), 'IN');
$query->distinct();

```
> 0 votes

# Answer
Your original conditions looks in usergroup\_id, while the D7 versions checks user\_id?

Also, there is no duplicate() method, only distinct().

You can use something like `dpm((string)$query)` to debug the generated query, and `dpm($query->getArguments)` to get the arguments passed to it.
> 2 votes

---
Tags: database, migrations
---


title: Drupal 7 field for expandable list

text:
# Question
Title: Drupal 7 field for expandable list
I'm looking for a module that provides a D7 field type that's an expandable list: a list where new values can be added at run-time. Is there a module for that?

# Answer
> 0 votes
Ended up using a taxonomy term reference with a tag widget.

---
Tags: 7, entities
---


# Question
Title: $node->type throwing PHP errors, occasionally
I've created some PHP code to get the node type, use it to get a filename, check if there is a banner image existing by that name; if the file doesn't exist, I render the default image.

In the images folder I'd have the following images.

* images/content\_type.jpg
* images/default.jpg
* images/careers.jpg

If the content type is careers, and there is an image called careers.jpg, then that image is displayed, but if that image isn't found then default.jpg is displayed.

```
    $type = $node->type;  // This is line 131.
    $type = preg_replace('/\s+/', '-', $type);
    $type = strtolower($type);

    $base_path_trimmed = $base_path;
    $base_path_trimmed = rtrim($base_path_trimmed, '/');

    $img_url = "$base_path_trimmed/sites/default/files/images/banners/sub-banners/$type.jpg"; //placed in variable so it's rendered out in $image
    $image = $_SERVER['DOCUMENT_ROOT'] . $img_url; //php is weird and checks from the server root rather than web root.

    if (file_exists($image)) {
      print "<img src=\"$img_url\"/ >\n";
    }
    else {
      print "<img src=\"$base_path_trimmed/sites/default/files/images/banners/sub-banners/sub-page-banner.jpg\"/>\n";
    }

```

The code works, except I sometimes get the following errors:

> Notice: Undefined variable: node in include() (line 131 of templates/page.tpl.php).
> Notice: Trying to get property of non-object in include() (line 131 of templates/page.tpl.php).

What can I do to avoid those errors? Is there a better way to write the code I need?

EDIT: Better way is to use the Dynamic Banner Module.

# Answer
Better way is to use the Dynamic Banner Module.
> 0 votes

# Answer
If your site is barfing on

```
$type = $node->type;

```

then it more than likely means that `$node` isn't a real node. If you are using this in page.tpl.php, then I would guess it is because the code is being called on a non-node page.

BTW, you shouldn't need to place any code in template files. That is what the preprocess functions are for. If you need to do things with the page template, then check out `template_preprocess_page`.
> 3 votes

# Answer
As for improvements that could be made, here's a suggestion:

```
function THEMENAME_preprocess_page(&$vars) {
    // Sub Page Banner Function
    //
    // Gets title ID (name of page set in drupal), strips spaces and sets to lowercase
    // Checks if img by that name exists in sub page banner folder
    // If it exists render img code
    // If it doesn't render the default banner

    // using content type

    if(isset($vars['node'])) {
        $node = $vars['node'];
    }
    elseif(arg(0) == 'node' && is_numeric(arg(1)) && arg(2) !== 'edit') {
        $node = node_load(arg(1));
    }

    if($node && isset($node->type)) {
        $type = $node->type;

        // file_build_uri returns drupal path:
        // public://images/banners/sub-banners/$type.jpg
        $img_url = file_build_uri("images/banners/sub-banners/$type.jpg");
        $default_img_url = file_build_uri('images/banners/sub-banners/sub-page-banner.jpg');

        // file_create_url returns the real path to the image
        $img_url = file_create_url($img_url);
        $default_img_url = file_create_url($default_img_url);

        // Build associative arrays to pass to theme('image');
        $img_vars = array(
          'path' => $img_url,
          'title' => $type,
          'alt' => $type,
        );
        $default_img_vars = array(
          'path' => $default_img_url,
          'title' => $type,
          'alt' => $type,
        );

        if(file_exists($img_url)) {
            $image = theme('image', $img_vars);
        }
        else {
          $image = theme('image', $default_img_vars);
        }

        // This will be available as $banner_image
        // in your page.tpl.php
        $vars['banner_image'] = $image;
    }
}

```

Place the above code in template.php and replace THEMENAME with the name of your theme (Don't forget to check if same function already exists).

Then $banner\_image variable will be available in your page.tpl.php.

Don't forget to clear the cache!
> 1 votes

# Answer
`$node` is not always defined when `page.tpl.php` is executed. It is only defined when you are actually viewing an node page. But `page.tpl.php` is used on all pages.

Perhaps you want to wrap your code into an if-block like

```
    if ($node) {
      …
    }

```

The more complex but still sound solution is to rewrite it like in the answer from Baysaa.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Send different email response based on form options?
I need to set up a *Request Download* form in which users choose which software they want from a drop-down. Is there any way to make it, so they are sent a unique email for each software? If not, is there a way to just show different responses on form submit?

# Answer
I experienced the same problem a while ago. I wrote a blog post on it (link below) if you need more information. Basically you can change the email that gets sent based on the input of the form by creating your own webform-mail-\[node-id\].tpl.php. Within this template you can change the content based on submission data in the $submission variable.

```
<?php
  if ($submission->data[1]['value'][0] == 'General Application'){
    print 'Thank you for submitting your resumé and covering letter'."\n\n";
  } else {
    print 'Thank you for submitting your resumé and covering letter for the position of '.$submission->data[1]['value'][0]'."\n\n";
  }
 ?>

```

http://bouncingorange.com/blog/201204/custom-email-templates-webform
> 3 votes

# Answer
You should be able to do this with rules and webform rules integration.

* **RULES**

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.
* WEBFORM RULES

> This module adds rules integration on webforms.
>
> Did you ever want to react on webform submission using rules but couldn't find the proper event?
>
> Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).
> 1 votes

---
Tags: webforms, emails, navigation
---


# Question
Title: Drupal Custom Login Page Using Zen Sub-theme
I have a custom Login Page in my website

I am using Zen for my themes.

I already have the Login page using the naming convention (e.g xxx--xxxx--tpl.php) but I can't display my form in this page.

here is my cpde

```
page--user_block--login.tpl.php:

<table class="body_login">
                    <tr>
                        <td class="gre"><div class="green_skin" ></div></td>
                        <td class="gre1"><div class="green_1_skin"></div></td>
                        <td class="cen">
                        <div class="alle" style="width:450px;">
                        <div class="modal-login">
                            <div class="modal-login-header">
                                <p>ONREVUE LOGIN</p>
                                <div class="icon-lock"></div>
                            </div>
                        <div class="content_my">

 /****This is where I want to display the form ***/

</div>
                        </div>
                        <div class="data_d"><p class="other_p"><a href="#">Register</a><span>|</span><a href="#">Forgot Password?</a></p></div>
                        <div style="clear:both;">
                        </div>
                        </div>
                        </td>
                        <td class="gre1"><div class="green_1_skin"></div></td>
                        <td class="gre"><div class="green_skin"></div></td>
                    </tr>
                </table>

```

My Template.php code

```
function Alphasys_theme(&$existing, $type, $theme, $path) {
$hooks = zen_theme($existing, $type, $theme, $path);
 // Add your theme hooks like this:
/*
  $hooks['hook_name_here'] = array( // Details go here );
*/

$hooks['user_login_block'] = array(
  'arguments' => array('form' => NULL),
       'template' => 'page--user_block--login',
);

 // @TODO: Needs detailed comments. Patches welcome!
 return $hooks;
  }

  function Alphasys_preprocess_user_login_block(&$vars) {
  // Modify the text of the submit button
 $vars['form']['submit']['#value'] = t('Login Now!');

  $vars['form_markup'] = drupal_render($vars['form']);
}

```

I don't know what's the problem with the Code but it seems I can't make to work...

I already tried to put

```
<?php echo $form_mackup ?>

```

in my page--user\_block--login but doesn't work.. I already tried to clear the cache.. but it is not working either..

Please help me...Responses are much appreciated..Thanks

# Answer
> 1 votes
I think your problem is that you're confusing the login block with the login page in the preprocess function and tpl names

try

```
function Alphasys_preprocess_user_login(&$variables) {
  //a capitalized theme name?
  $variables['rendered'] = drupal_render($variables['form']);
}

```

then change the

```
$hooks['user_login_block']

```

to

```
$hooks['user_login']

```

and drop in your print statement into the tpl

```
<?php print $rendered ?>

```

and you should be good to go

---
Tags: hooks, users, theming
---


# Question
Title: switching display suite view modes based on context or user location, show/hide fields based on user location
The Drupal 7 site i'm working with needs to have a services directory, each service needs to have a general description and a description for health professionals.

So I've created a new content type and called it service, and create 2 custom fields one for general description and one for the health description.

Now the the general services will create their own menu items (this part is fine), the healthcare ones will need to be available in a sortable list as pictured below

https://i.stack.imgur.com/fpVCF.png

Now here's the tricky part.

(I know I could just create 2 content types, one of general and one for healthcare but i'd like to reduce the double handling and maintenance as much as possible - so if there is a way to have all the data entered in one content type that would be ideal)

Using display suite I can hide one of the fields, and using views I can create the directory listings but the directory listings created by views all just link back to the node.

So far I haven't been able to figure out a way to manipulate which fields are displayed (or even switch between display suite views) based on where the user is in the site. This could be context, a link, or block on a page, i'm open to anything at this point.

Hopefully this is starting to make sense:

**Services Content Type** (takes all the data, field 1& field 2)

**Viewing Content through general services (/services/service-name/service-item)**

Display field 1

**Viewing Content through health care (/services/health-care-professionals/service-item)**

Hide Field 1

Display Field 2

I was hoping you could give me some pointers, I've looked into using the context module, rules module, even had a thought about having 2 content types and using rules to copy the data from

Content Type 1 Field 2, to Content Type 2 Field 2 upon saving..

# Answer
> 3 votes
Better yet I was able to figure it out entirely using views.

First I created a page with a glossary type view, but most importantly some linked titles. I altered the link path, look under the Rewrite Results tab, and click 'output this field as a link'

Now you'll be able to set link paths, tokens are available for use as well BUT you have to add them as a field in views first (and they must be placed above the linked title field)

I ended up using this path: `health-professionals/[field_servicetype]/[title]`

You'll also want to check 'replace spaces with dashes' to make the url friendly.

(also on a side note if you are using url aliases you'll need to go to the configuration and remove the words from the strip filter (eg, for, a, and, the) - because views has no option to do this, and your url needs to match with the actual alias. So remove those, and delete all the aliases and regenerate)

So now we have the altered linked titles setup. Now create another page, but this time look under Format \> Show: and select rendered entity.

Now here's the good part, in rendered entity settings you can select 'view mode' which for me was one of the previously created modes I'd setup in display suite earlier, but you'll still be able to select from 'Full Mode','Teaser', etc.

Page Settings \> Path: Needs to be the url and token, so mine was `/health-professionals/%`

Pager settings : Needs to be set to 'display a specified number of items' and set the number to 1 - so in essence what we're creating is an alternate way of viewing the actual node content through views.

**Now the hard part**

Contextual filters \> add one for Content:Title

**When filter value is NOT in the url** \- whatever, I've just left it as 'page not found' but when testing it can be a bit annoying so display all results is fine too.

When filter value IS in the URL: Override title: %1 (or %2, %3, etc depending how many filters you have an what they are)

Apply that, and now if you look down to the 'preview with contextual filters' form go ahead and input a node title, so if you have a node called 'services' you'd put services in. If it's setup right you should get the node content for that page and nothing else.

Better still you'll also have a way to link to it, and a linked index (previous page created)

this absolutely did my head in... but good result in the end :)

# Answer
> 3 votes
I was able to do this using Display Suite Extras, I found this tutorial very useful.

Display Suite Extras has a switch view mode by URL option, if you add ?v=view\_name to the end of the url it will render that view. So I created the needed view types and used views to rewrite the URL of the titles to include the url parameter.

---
Tags: 7
---


# Question
Title: How to re-run javascript core code for content loaded with jQuery's ajax()?
I'm trying to AJAXify page loads using `.load()`/`.get()` methods and the main problem I'm currently stuck with is that the loaded content isn't being processed by the relevant javascript code.

I've tried upgrading to jQuery 1.7 and addind this scary workaround: https://stackoverflow.com/questions/11442723/how-to-convert-bind-pass-through-to-on-to-delegate-like-right-inside-jqu , but the problem is not in the `bind()` calls AFAIU.

Something with `Drupal.behaviors`?

The simplest way to reproduce the issue is to take a page's `#content`.innerHTML that is normally being processed by JS (`/admin/structure/block`) and replace the `#content` HTML with it. This way the resulting HTML is the same but \[for me\] it's not processed by JS functions.

# Answer
Looks like `Drupal.attachBehaviors(jQuery("#content")[0]);` is working. Some issues still exist though. Like the absence of relevant `behaviors` when loading from different page.

Taken from https://drupal.stackexchange.com/a/3193/7177
> 0 votes

---
Tags: 7, ajax, javascript
---


# Question
Title: Strip HTML from trimmed body before it is trimmed
Teaser display has been set to display "summary or trimmed" at 200 characters but the auto generated trimmed body comes through with image tags, links and all.

I have tried the following in `THEME_preprocess_node`, but it results in a short trimmed version as it counts the html as characters -\> trims to 200 -\> removes tags:

```
if(isset($variables['content']['body'][0]['#markup']) && $variables['teaser']) {
    $variables['content']['body'][0]['#markup'] = strip_tags($variables['content']['body'][0]['#markup'], '<p> <br>');
}

```

This seems like surprising behavior, is trimmed not normally clean? PS this should ideally not be done in the template file.

# Answer
> 7 votes
You might want to take a look at the Smart Trim module. It gives all sorts of options for customizing trim functionality, including stripping HTML.

# Answer
> 0 votes
You can implement hook\_node\_view or hook\_node\_view\_alter and render the teaser the way you want it.

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