title: How do I adjust autocomplete list width

text:
# Question
Title: How do I adjust autocomplete list width
Has anyone been successful in adjusting autocomplete list width (entity reference tag style)? I have hard time grabbing the element in Inspector/Firebug. The goal is to have the width wider than the field that it's bound to, so to accommodate entire item label.

# Answer
> 0 votes
As coded in autocomplete.js file inside misc folder, popup is wrapped inside

```
<div id="autocomplete"></div>

```

You can able to set width using above id. If you want to disable hide popup option for time being to style the popup results, then try commenting lines shown below in autocomplete.js file inside misc folder of your drupal root.

```
/**
 * Hides the autocomplete suggestions.
 */
Drupal.jsAC.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed.
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    this.input.value = $(this.selected).data('autocompleteValue');
  }
  // Hide popup.
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function () { $(popup).remove(); });
  }
  this.selected = false;
  $(this.ariaLive).empty();
};

```

**NOTE: Remove commented code** once styling is done. Clear the cache after making javascript changes and make sure changes are reflected in autocomplete.js file using firebug. Clear browser cache.

Hope it helps :-)

---
Tags: ajax, theming
---


title: search results in JSON format

text:
# Question
Title: search results in JSON format
I have a website built on drupal with search functionality. When I search for example for "test" the link of the search is displayed like `search/node/test`

Is there any possibility that if I call `search/node/test?json` or `search/node/test/json` the returned page would be plain text in json format of node ids ?

# Answer
Try Services Search & Services module. Using these module you can expose search results as JSON.

Another option is Views Datasource module. Construct a page view which accepts search term as an argument and displays search results in JSON format.
> 1 votes

---
Tags: search
---


# Question
Title: How to change string which comes from breadcrumbs?
I have used custom breadcrumbs module.

Now one of my title of blog has single quote or double quotes, which is having problems.

So, in titles i have added

> \[node:title\]

so output of the title whose having quotes are like

```
Home > blog > Politics > No Democracy but many other 'o-cracies'

```

and i have added hook which will show the output is like this..

```
function myowntheme_breadcrumb($variables) {
    $sep = ' > ';
  if (count($variables['breadcrumb']) > -1) {
    return implode($sep, $variables['breadcrumb']);
  }
  else {
    return t("Home");
  }
}

```

How to remove that hash tag values and show on simple version ?

# Answer
Your nodes contain apostrophe in their title. Node titles will be passed through `check_plain()` function and it uses `htmlspecialchars()` function to convert the quotes to HTML entities.

You may try by decoding them back

```
function myowntheme_breadcrumb($variables) {
    $sep = ' > ';
  if (count($variables['breadcrumb']) > -1) {
    return htmlspecialchars_decode(implode($sep, $variables['breadcrumb']),ENT_QUOTES);
  }
  else {
    return t("Home");
  }
}

```
> 4 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: Form element with type = value odd behaviour
I have 2 forms on the site, each of them has an array, that I want to store inside the form to use in `form_submit` function:

```
$form['store'] = array(
  '#type' => 'value',
  '#value' => $fields
);

```

But in one `form_submit` function this works:

```
$fields = $form_state['values']['store'];
unset($form_state['values']['store']);

```

In another one it doesn't work, giving an error:

> Notice: Undefined index: store in scores\_search\_form\_submit

While this code works:

```
$fields = $form_state["complete form"]["store"]["#value"];
unset($form_state["complete form"]["store"]);

```

Why does this happen?

# Answer
You can use form properties:

```
$form['#mystore'] = $fields;

```

The form properties are not sent to the client, but are available in the submit hander. For example, core use `$form['#node']`, `$form['#user']`, etc.

Updated:

http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html#val

> Note that as of Drupal 6, you can also simply store arbitrary variables in $form\['#foo'\] instead, as long as '#foo' does not conflict with any other internal property of the Form API.

Updated 2:

Your problem may be related to this issue: http://drupal.org/node/1381830
> -1 votes

# Answer
Try to store the values within `$form_state`

```
$form_state['storage']['store'] = $fields;

```

And access the same within your submit functions.

```
$fields = $form_state['storage']['store'];

```
> -1 votes

---
Tags: 7, forms
---


# Question
Title: How can I unset an option from Profile2 while it is part of Registration?
I have a Main Profile page that I added to the User Registration page but I only need one option from the entire Main Profile to display while the user is creating an account. I was able to hide all of them using 'display: none' in the CSS but this caused an issue with a particular field in the Main Profile where they could list themselves as 'Featured'.

In my Custom Module I have a form\_alter function but when I print out the form in tags it only shows the form values of the actual registration part. It doesn't include any fields from the Main Profile. In the developer tools on Chrome it shows that the Main Profile section is in the same form as the registration section.

Is there any way I can get to the Main Profile elements to do an unset on my particular field within my form\_alter function?

Thanks

# Answer
Main profile fields are added through hook\_form\_alter. Solution: hook\_form\_alter function is executed in all modules while accessing registration form. Your custom module form\_alter is executing before Profile fields get added. To solve this issue increase custom module weight. FYI : Module weight change
> 0 votes

---
Tags: users, forms
---


# Question
Title: Define module parent item to contain other module items
I want to define section of items in administrative area, for my custom module operations.

I defined some items with hook\_menu in /admin/config/development/ But i would like now to make a section, that will containt those menu items, so on click on that parent item i would be presented with those "contained" items.

It is like, when you have admin/, you click Configuration and you get to the screen with all the items contained ( admin/config/ ).

It is probably very simple, but somehow could not trample on it! Thanks!

# Answer
What you are trying to achieve is really simple. You need not use any additional code. You just need to follow the correct menu structure. I've posted a sample code below

```
     function mymodule_menu() {
      $items['admin/config/development/mymodule'] = array(
      //Your code here
      );
     $items['admin/config/development/mymodule/sub-module-1'] = array(
      //Your code here
      );
     $items['admin/config/development/mymodule/sub-module-2'] = array(
      //Your code here
      );
      return $items;

}

```

You need to clear the cache. Sometimes you might need to disable and re-enable your modules to register the menu. Now when you click `mymodule` menu item, a list of all your sub modules will be displayed.
> 1 votes

---
Tags: routes
---


title: Altering menu local task title

text:
# Question
Title: Altering menu local task title
I'm trying to override the title of a system provided local task. I have the following code which works for uid 1 but not authenticated users:

```
function test_controller_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path == 'user/%') {
    foreach($data['tabs'][0]['output'] as $key => $item) {
      if ($item['#link']['path'] == 'user/%/edit') {
        $data['tabs'][0]['output'][$key]['#link']['title'] = t('Password and email address');
      }
    }
  }
}

```

According to this issue this is expected behaviour for the time being. Is there another way round this?

# Answer
> 1 votes
i have an idea if you use string override module .this module provide the override the local task menu.

http://drupal.org/project/stringoverrides/

# Answer
> 1 votes
I'm not sure for you digital, but the authenticated must have first the rights to modify their own account to see the local task. And the code below worked for me :

```
$pattern = '/^user/';
if (preg_match($pattern, $root_path)) {
  foreach($data['tabs'][0]['output'] as $key => $item){
    if(isset($item['#link']['path']) && $item['#link']['path'] == 'user/%/view'){
      $data['tabs'][0]['output'][$key]['#link']['title'] = t('My personal tools');
    }
  }
}

```

I used a pattern so the title stays the same on each user's page.

---
Tags: 7, routes
---


title: Populate a field on node creation

text:
# Question
Title: Populate a field on node creation
I have a content type "abc". I have a field "listing id". I want this field to be prepopulate starting from 1 and autoincrement" on every "abc" node creation.

How can I do this.

# Answer
It looks like you can use the Serial Field module to accomplish this.

From the Serial Field page on Drupal.org:

> **Usage**
>
> You can add a serial field to any type at admin/content/types -\> manage fields. In the New Field form select Serial as the type of data and label and field name as your choice, and Save. No other settings.
> 1 votes

---
Tags: 7
---


title: Check if current page is taxonomy term

text:
# Question
Title: Check if current page is taxonomy term
How can I check if the current page is a taxonomy term page, similarly to what done with the following code used to check if the current page is the front page?

```
if (drupal_is_front_page()) {
  // The current page is the front page.
}
else {
  // It is not the front page.
}

```

# Answer
Just to offer a solution that doesn't make use of `arg()` (which it's advised to avoid where possible according to the docs page)

You can use the `menu_get_object()` function:

```
$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  // User is on a taxonomy term page
}

```
> 13 votes

# Answer
`<?php if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)): ?>` should do the trick.

In case edit/feed (and possibly some other related pages) should be excluded you can use: `<?php if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2) && !arg(3)): ?>`
> 5 votes

# Answer
```
<?php

if (arg(0) ==  "taxonomy" && arg(1) == "term" && is_numeric(arg(2)) && arg(3) == "") {
  // Taxonomy term page
}

?>

```
> 5 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to create related links list in Views
So for Content Type 'Level 3' I have added a field called 'Related Links' which uses Entity Reference and autocomplete so a user can select multiple pages that are related.

I've been now trying to render these pages as links using Views, however I'm really stuck as to what settings I should be using. I need Views to get the Related Links for the current page on which it is displaying the block, and then display a linked Title of each of the pages that have been specified in the 'related links' field.

# Answer
Create a new view showing content, check "create a block".

Click in advanced and, in relationships, add "a bridge to the content entity that is referencing content via your\_field\_name". The identifier will be something like: "Content referencing Content from your\_field\_name"

Then add a contextual filter with a relationship to the filter you just created. Select provide default value (Content ID from URL) when filter value is not available.

You can also filter nodes by type to make the view more efficient.

Save your view and add your block to show in the corresponding pages through the block display manager, context or display suite.
> 2 votes

---
Tags: 7, views
---


title: Making a REST AJAX call from Basic Page

text:
# Question
Title: Making a REST AJAX call from Basic Page
The following successfully calls a REST Services Module endpoint when contained in a module but I cannot get it to work within the script tags of a basic page.

```
(function ($) {

  var myapi = {
    'apiPath': '/api/award'
  };

  // REST functions.
  myapi.create = function (award) {
    $.ajax({
      type: 'POST',
      url: 'http://localhost/testsite/api/award',
      data: JSON.stringify(award),
      dataType: 'json',
      contentType: 'application/json'
    });
  };

  myapi.create({ award : 'The Award' });

}(jQuery));

```

I am wondering if it is even possible to embed AJAX calls in a Basic Page.

Thanks for any help,

Orville

# Answer
It turned out to be a 401 error that only occurred when the user was not logged in. Changing the 'access arguments' string in the hook\_services\_resources array fixed the problem.
> 0 votes

---
Tags: 7, ajax, services
---


# Question
Title: Most popular content content modules in Drupal 7?
What's the best way to do most popular content in Drupal 7?

I've been using the Most Popular module because I haven't been able to find anything else, but that only has ~750 odd users spread between the D6 and D7 versions. Surely popular content is a fairly-common requirement? That leads me to believe there's a better maintained (and hopefully less buggy) module that does the exact same thing, just it has an obscure name and I can't find it via Google. If so, what is it?

(If you're going to crucify me for asking for an alternative module, note that I've contributed several issues and a documentation patch for Most Popular, and have volunteered to contribute code patches. However, there hasn't been a single commit on that module in ~6 months.)

Thank you!

# Answer
Almost all functionality of this module you can implement using Views + Radioactivity module as it is described here drupal.stackexchange.com/a/21075/7313
> 3 votes

---
Tags: 7
---


# Question
Title: Which access control module will allow me to use limit visibility of individual nodes?
There are a ton of Access control modules. Choosing one is difficult. The current use case is that I have a single video content type. Some videos are public and some are private that are only accessible by role. I want to be able to set each node (public or private) and then ensure that they do not show in taxonomy term pages and views pages unless they are logged in. Which module is best for this use case? Note that the term and view pages will be the shared but I need private ones to automatically removed if they are not logged in. Which access control module will meet these needs?

# Answer
BAM!

Taxonomy Access Control to the rescue.

Access control for user roles based on taxonomy categories (vocabulary, terms).

> Automatically controls access to nodes (based on their taxonomy terms).
>
> * Configuration page for each user role.
> * Three node access permission types: View, Update, Delete.
> * Two term access types: View tag, Add tag.

Just create a term called something like "Members only" and add that term reference to your video content types.
> 4 votes

---
Tags: 7, users
---


title: 500 Internal Server Error

text:
# Question
Title: 500 Internal Server Error
I changed my server and when I uploaded my site this error appeared:

> Internal Server Error
> The server encountered an internal error or misconfiguration and was unable to complete your request.
> Please contact the server administrator, webmaster@xxxxxxxx.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.
> More information about this error may be available in the server error log.
>
> Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
> Apache/2 Server at xxxxxxx.com Port 80

I tried to upload it again without success. I tried uploading the index.html file without the drupal site, and it worked.

How can I solve this problem?

# Answer
> 6 votes
I had this problem too, due to a bug in my PHP code and the fact php.ini was not set to display errors.

Find the line `display_errors = Off` in php.ini and change it to `display_errors = On`. This way you'll see the specific php error message instead of the generic internal server error.

# Answer
> 2 votes
I had the same problem on my laptop when setting up a basic Drupal 7 site.

The problem was Apache not updating include paths etc. In my case a simple Apache restart sorted it.

# Answer
> 0 votes
Try setting the permission of the root folder to 755.

```
Chmod 755 "root_folder_name"

```

# Answer
> 0 votes
Increase php memory limit. If new server is on shared hosting you might need a dedicated server.

# Answer
> 0 votes
I have that problem with hostgator and the following help me:

1. Permission for the folder must be 755 and the files 644
2. SuPHP was activated and the suphp user needs to be the owner of the folders and files
3. need to increase the php memory limit
4. If you change your domain remember to change your url base

---
Tags: http-request
---


title: Meta Tags for viewers to not see

text:
# Question
Title: Meta Tags for viewers to not see
Hi Im using D6 do I have to make the meta output so people can see the meta data if I select to not output the meta tags so viewerss will not read my meta data will this affect my search engine optimization (do the robots still read my meta or not?)

# Answer
> 4 votes
If your meta tags aren't in your page source, search engines (and any other robots) won't be able to read them.

You should never have anything sensitive in meta tags anyway so trying to hide them doesn't really make sense.

---
Tags: 6, meta-tags
---


title: How can I replace a custom token?

text:
# Question
Title: How can I replace a custom token?
I am trying to add a custom token in pathauto.
I have a token \[story-page-number\].
Then in my hook\_pathauto\_alias\_alter() I am trying to replace it using token\_replace().

Something is not quite right though.

```
token_replace("[story-page-number]", (array)node_load($context['data']['node']->nid));

```

Here's my custom token set up.

```
function mymodule_token_list($type = 'all') {
    $tokens['story-page-number'] = t('Page number (of story front)');
    return $tokens;
}

function mymodule_token_values($type, $object = NULL, $options = array()) {
    $values = array();
    $values['story-page-number'] = get_story_page_number($node->nid);;

return $values;
}

```

What am I missing here, I thought it would be a lot more straight forward.

# Answer
Try this:

```
$node = node_load($context['data']['node']->nid);
token_replace("[node:story-page-number]", array('node' => $node));

```

If `$context['data']['node']` is already a node, then you may skip the `node_load()` call, and simply assign `$node = $context['data']['node'];`

**Edit:** Sorry, I didn't try your example in code. You need to include the token type in your token names. In `mymodule_tokens()`, check to be sure that `$type` is `'node'`, and then look up `$node` from `$data['node']`. Note that you are using the Drupal 6 `hook_token_values()`; you should use the D7 `hook_tokens()`. Use the implementation of node\_tokens() as a guide.

### References
> 1 votes

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


# Question
Title: Convert a static query to dynamic one, with a having clause
i am writing a patch for ubercart 3, for a attribute ignore module i am building. For this module, i need to be able to query alter the query for the uc\_product\_adjustments\_form.

I need to convert the static mysql query to a dynamic one.

This is what the static query looks like:

```
$result = db_query("SELECT pa.nid, pa.aid, pa.ordering, pa.display, a.name, a.ordering, ao.aid, COUNT(po.oid)
    FROM {uc_product_attributes} pa
    LEFT JOIN {uc_attributes} a ON pa.aid = a.aid
    LEFT JOIN {uc_attribute_options} ao ON a.aid = ao.aid
    LEFT JOIN {uc_product_options} po ON ao.oid = po.oid AND po.nid = :po_nid
    WHERE pa.nid = :pa_nid
    AND pa.display <> :pa_display
    GROUP BY ao.aid, pa.aid, pa.display, a.name, pa.ordering, a.ordering, pa.nid
    HAVING count(po.oid) > 0
    ORDER BY pa.ordering, a.ordering", array(':po_nid' => $nid, ':pa_nid' => $nid, ':pa_display' => 3));

```

And this is what i got so far:

```
$query = db_select('uc_product_attributes', 'pa');
  $query->leftJoin('uc_attributes', 'a', 'pa.aid = a.aid');
  $query->leftJoin('uc_attribute_options', 'ao', 'a.aid = ao.aid');
  $query->leftJoin('uc_product_options', 'po', 'ao.oid = po.oid AND po.nid = :po_nid', array(':po_nid' => $nid));
  $query->fields('pa', array('nid', 'aid', 'ordering', 'display'));
  $query->fields('a', array('name', 'ordering', 'aid'));
  $query->fields('ao', array('aid'));
  $query->condition('pa.nid', $nid);
  $query->condition('pa.nid', $nid);
  $query->groupBy('ao.aid');
  $query->groupBy('pa.aid');
  $query->groupBy('pa.display');
  $query->groupBy('a.name');
  $query->groupBy('pa.ordering');
  $query->groupBy('a.ordering');
  $query->groupBy('pa.nid');
  $result = $query->execute();

```

So everything works, except for the HAVING clause, which i don't understand to be honest.

Many thanks!

-- Tom

# Answer
If I understand you right you just need to use the `having()` member function of the `SelectQuery`:

```
$query->having('count(po.oid) > 0');

```

FYI you have this line twice:

```
$query->condition('pa.nid', $nid);

```

I don't think it'll make a difference to the query result but it's probably best to remove the duplicate line.
> 0 votes

---
Tags: ubercart, database
---


# Question
Title: Manually adding sdk for AWS SDK PHP Module
The AWS SDK for PHP Module comes with a drush make script:

```
; Drush Make (http://drupal.org/project/drush)
api = 2
core = 7.x

projects[awssdk][type] = library
projects[awssdk][download][type] = git
projects[awssdk][download][url] = https://github.com/amazonwebservices/aws-sdk-for-php.git
projects[awssdk][download][tag] = 1.5.10

projects[libraries] = 2

```

What do I need to do to get this SDK manually? I am running Windows and I ran into some issues trying to add the script using drush. I already tried adding the sdk folder to /sites/all/libraries as "awssdk" but that did not work as I keep getting *"Failed to load the AWSSDK"* in Drupal reporting.

# Answer
> 2 votes
Assuming you have git installed, you should be able to run the following from within your /sites/all/libraries directory:

```
git clone git://github.com/amazonwebservices/aws-sdk-for-php.git awssdk

```

Alternatively, you could use the Zip button on the Github project page or the link it points to to download the zip file and put it in a subdirectory of libraries directory called awssdk.

---
Tags: 7, drush, theming
---


# Question
Title: How to resave content so that teaser thumbnails are generated
I imported a load of content from wordpress, and I am using the teaser thumbnail module. I need to effectively click 'edit' and 'save' on all my content so that any images create thumbnails on save automatically. Is there any way to do this.

# Answer
The image style files won't be generated when you save the node, only when the style URLs are requested for the first time.

You can generate the styles manually but I think it'll take some custom code. Without knowing more about your setup it's tricky but the following should get you started:

```
// Get the ids of nodes you want to generate styles for.
$nids = db_query('SELECT nid FROM {node} WHERE type = :type', array(':type' => 'my_type'))->fetchCol();

// Load the node objects
$nodes = node_load_multiple($nids);

// Setup a list of fields to generate styles for
$fields = array('field_image', 'field_image2');

// Setup a list of styles to generate
$styles = array('thumbnail', 'small');

foreach ($nodes as $node) {
  foreach ($fields as $field_name) {
    // Extract the fields items to get at the file ids.
    $image_items = field_get_items('node', $node, $field_name);

    foreach ($image_items as $image_item) {
      // Load the file
      $file = file_load($image_item['fid']);

      foreach ($styles as $style_name) {
        // Get a URI for the image style.
        $derivative_uri = image_style_path($style_name, $file->uri);

        // Create the derivative
        image_style_create_derivative($style_name, $file->uri, $derivative_uri);
      }
    }
  }
}

```
> 2 votes

---
Tags: media
---


# Question
Title: Limit Taxonomy display in Term Reference based on criteria?
1. I have Taxonomy called "Region" ex: (Region A / B / C)
2. Each user is linked to Taxonomy "Region" using Profile2 module (one person can be linked to multiple regions)
3. Content Type "Article" has a Term Reference field linked to same Taxonomy. (value = unlimited)

Requirement: . In content type "Article", I am asking user to select the Region (as Taxonomy Select list) where this Article belong too - how do I limit the Taxonomy list based on the Region user have an access too?

ex: User1 is linked to Region A / User2 is linked to Region A & B; When User1 creates an Article, Term Reference Taxonomy to show "Region A" but when User2 - show both "Region A" and "Region B"

in SQL world, I would write something like this.

select t.name from taxonomy t where t.name in (select p.name from profile p where user\_id = :%1);

How would you achieve this in Drupal without writing custom code?

p.s: My apologies - I am from database world and very new to Drupal; still learning Drupal lingo.

# Answer
I achieve the behaviour described in the question with:

* Entity Reference
* Views

In my Entity Reference field I use these settings:

* Target type: **Taxonomy term**
* Entity selection \> Mode: **Views: Filter by an entity reference view**
* Entity selection \> View used to select the entities: **My custom view**

In **My custom view** entity reference I have (most importantly):

* A relationship: to the user referencing the taxonomy
* A contextual filter: to grab only the terms the user "is linked to"

Related to this question - actually this is what brought me here, In some cases it easier to filter taxonomy terms using a get parameter. For example, I want my visitors to see only the cities of one country when adding a classified ad, I will have a view that produces this:

* Morocco: q=node/add/ad?country\_tid=1
* India: q=node/add/ad?country\_tid=2
* Zambia: q=node/add/ad?country\_tid=3

And on the entity reference view used on the ad content type I will add a contextual filter with a default value generated by this **PHP code**

```
return $_GET['country_tid'];

```

PS. I tried hierarchical select, term reference tree and hook\_form\_alter. This solution is KISS.
> 3 votes

# Answer
There's a module named Term Reference Tree, which - apart from a nice tree widget - provides an option to filter presented taxonomy items through a result of a view. I mean, I never had to use that option, but I assume it's working ok. However I think you'd have to resort to using that widget then, as well.
> 2 votes

# Answer
It worked for me with the following steps

1. Create a view, which list Region based on the user who is logged in (using Relation link in View)
2. content type article, add a new field type=Term Ref then select Term Reference Tree / under field setting select filter by the view created in #1.
> 0 votes

# Answer
If you want to do this without the term reference tree module try the http://drupal.org/project/entityreference module. Just create an entity reference field and you can limit using views.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Table Drag problem with Jquery Update to jquery 1.4 and highers
I want to use some jquery plugins that need jquery 1.7.x But as you know jquery update in drupal 6.x only support jquery 1.3.x and lower.

if we copy jquery 1.7 to jquery update folder, it cause problems in table drag function.

Is there any way to repair table drag bugs with jquery high versions?

# Answer
As mentioned in a comment on another answer, it's possible to load a newer version of jQuery alongside Drupal's without conflicting with Drupal's, using jQuery's built-in noConflict() mode.

You can do this very easily using the jQuery Multi module. Simply select the plugins using the module's UI, or include them via the hooks. Only your plugins will use the newer jQuery, and the rest of Drupal (like tabledrag), will remain untouched. See the module README for more info on how to use it.
> 1 votes

# Answer
The problem is that newer jQuery `.after` function returns the content to be added if you invoke it on an empty list. This breaks the tabledrag.js `makeDraggable` function.

The following patch that function fixed it for me:

```
   // Insert the handle after indentations (if any).
-  if ($('td:first .indentation:last', item).after(handle).size()) {
+  var td = $('td:first .indentation:last', item);
+  if (td.size() > 0) {
+    td.after(handle);
     // Update the total width of indentation in this entire table.

```
> 2 votes

# Answer
The dev release of jQuery Update, even the Drupal 6 version, will automatically let you upgrade your site to use jQuery 1.7 fairly safely.

Bear in mind this is a dev release so there will probably be some bugs, but if I remember correctly the tabledrag functionality does at least work.

It might be worth checking out the issue queue to see what other problems you might encounter using this version.
> 0 votes

---
Tags: javascript
---


# Question
Title: Creating a select form element with multiple preselected options
How could I create a select form element that has more than one options selected as default options? Does the form API allow it?

# Answer
> 1 votes
Solved it my self using this example Default value is used to set multiple options preselected. It should be array of list for preselection

---
Tags: forms
---


# Question
Title: How can I make required cck date field "not required" by hook_form_alter?
I could make some requited cck fields "not required" by hook\_form\_alter a below but this doesn't work for date field.

for selection type

```
function hook_form_alter(&$form, &$form_state, $form_id) {
$form['field_smaple_1']['#required'] = 0;
}

```

or

for text are type

```
function hook_form_alter(&$form, &$form_state, $form_id) {
$form['field_sample_2']['0']['#required'] = '';
}

```

How can I do the same thing for date field?

# Answer
To alter date field required to disable, you can use following snippet in your form alter

```
$form['#field_info']['field_date']['required']=0; //field_date use your field name

```
> 2 votes

---
Tags: entities, 6, datetime
---


# Question
Title: Need module for notifications like privatemsg
I am using Drupal7 and notification module. Now i want the notification like Private Message module. When any comment occurs or any post occurs at that time i want notification like "Private Message" module i.e. just like "3 new messages" i want same like this "3 new comments" etc..

Can you please inform me if there is any module exists or not

# Answer
> -1 votes
There is **messaging\_simple** table which stores message values.

See the column **timeread** this provides time when the message is read. The entries which have **0** value shows unread message.

You can apply sql query to find out rows with timeread **0** for logged in user and can get the count of unread messages.

---
Tags: notifications, privatemsg
---


# Question
Title: How can my Drupal module expose custom URLs?
I'm writing a custom drupal module and have just starter out working with Drupal.

I need to expose a custom URL from my module so that some JavaScript files can request this URL for XML data. How can I do this? I'm not referring to the hook menu. Thanks

# Answer
> 1 votes
You need hook\_menu in your .module file.

> This hook enables modules to register paths in order to define how URL requests are handled. Paths may be registered for URL handling only ...

example:

```
function MY_MODULE_menu() {
  $items['path/callback/%/%'] = array(
    'page callback' => 'my_callback_func',
    'page arguments' => array(2, 3),
  );

  return $items;
}

function my_callback_func($arg2, $arg3) {
  //your process here
  $data = array($arg2, $arg3);
  return drupal_json_output($data);
}

```

in js call this url with 2 arguments: path/callback/VAR\_1/VAR\_2 - VAR\_1 is second argument, VAR\_2 is third as defined in "'page arguments' =\> array(2, 3)" (path is zero argument, callback is first argument)

The $data may be returned in what you want format. In this example this is JSON.

More for hook\_menu - http://api.drupalize.me/api/drupal/function/hook\_menu/7

---
Tags: 7
---


# Question
Title: Views Contextual filter for matching taxonomy names
I have a view of content type slideshow items. Each item has a taxonomy term from`slideshow_category` vocabulary. I also have another content type: articles, which has it's own taxonomy `article_categories`.

I'd like to create a view that will match the names of those taxonomies and display the slideshow items accordingly.

**For example** on articles taxonomy page `news` the only slideshow items displayed are those which marked `news` .

**What I'm doing right now:**

I have created a contextual filter on the slideshow items view

*When is NOT available*

* Content: field\_slideshow\_category
* Provide Default value \> Raw value from URL
* Path component \> 2
* Use Path alias \> checked

*When IS available*

* Specify validation criteria \> checked
* Selected the `slideshow_category`
* Filter value type \> Term name converted to Term ID

**PROBLEM**

This works fine on page like `/articles/news/` (using my previous example ), but obviously because I pass RAW value this view also appear on `/articles/news/news-item` (which is the actual article page). What I need is for this view to show up only on taxonomy pages. Is there a way to limit "Raw value"? should I be using a different "Provide Default value" ?

Thanks in advance :)

# Answer
> 1 votes
Yes try different "Provide default value" for this case "Taxonomy term ID from URL"

When it's available specify "Taxonomy name converted to ID"

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


# Question
Title: Autopopulate a different field if node reference autocomplete doesn't have a matching candidate?
I've got a form for non logged in users to submit an event, which then goes in to a moderation queue via rules. At the moment, when an authenticated user adds an event, they've got the option to either pick a venue from a list of already populated nodes (`field_venue`), or specify a venue in plain text if the venue isn't a node (`field_venuetext`).

I'd like to make this a bit easier for non-authenticated users and just provide one field which is a node reference autocomplete field. If the user just types a venue and doesn't select from the autocomplete, it will populate the plain text field (`field_venuetext`). Looking at the `nodereference.module` source, I can see the function I'd like to change (`nodereference_autocomplete_validate`), and I guess, I'd do something like this:

```
function nodereference_autocomplete_validate($element, &$form_state) {
  $field_name = $element['#field_name'];
  $type_name = $element['#type_name'];
  $field = content_fields($field_name, $type_name);
  $field_key  = $element['#columns'][0];
  $delta = $element['#delta'];
  $value = $element['#value'][$field_key];
  $nid = NULL;
  if (!empty($value)) {
    preg_match('/^(?:\s*|(.*) )?\[\s*nid\s*:\s*(\d+)\s*\]$/', $value, $matches);
    if (!empty($matches)) {
      // Explicit [nid:n].
      list(, $title, $nid) = $matches;
      if (!empty($title) && ($n = node_load($nid)) && trim($title) != trim($n->title)) {
        form_error($element[$field_key], t('%name: title mismatch. Please check your selection.', array('%name' => t($field['widget']['label']))));
      }
    }
    else {
      // No explicit nid.
      $reference = _nodereference_potential_references($field, $value, 'equals', NULL, 1);
      if (empty($reference)) {
        // *** CHANGE *** At the moment, this generates an error, but I would like to populate the field 'field_venuetext'
        form_error($element[$field_key], t('%name: found no valid post with that title.', array('%name' => t($field['widget']['label']))));
      }
      else {
        // TODO:
        // the best thing would be to present the user with an additional form,
        // allowing the user to choose between valid candidates with the same title
        // ATM, we pick the first matching candidate...
        $nid = key($reference);
      }
    }
  }
  form_set_value($element, $nid, $form_state);
}

```

However I'm not sure how I'd override it, or indeed how I'd populate the field `field_venuetext`. I'm new to Drupal, so not 100% sure where to go next. Any ideas?

# Answer
After some poking around and asking on the Drupal forum, I've found that there's a module that does pretty much what I want
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Create custom links for private message in OG group
I am using the module private messages to let users send messages to groups and other users. I would like to create a link where the recipient info is automatically filled with the Group title on the new message page.

Did any one try to work with private messaging groups and create the autocomplete links ?

# Answer
> 0 votes
There is a module for private message in group but it is sandbox module and for Drupal 6 only. You can customize it for Drupal 7

Just check this Sandbox

And refer this discussion also, it has nice roadmap regarding implementation of entire module. http://drupal.org/node/612664

---
Tags: 7, organic-groups, privatemsg
---


# Question
Title: Rendering a module's template contents in the page body
I've been digging through the Drupal docs and haven't found a solution for this:

What I'm trying to do is to create a module with a URL using menu hooks. I've got that far. When this URL is viewed, I'd like to insert some HTML and JS code in the body but I haven't managed that. I've been trying to use templates.

This is what my module looks like:

```
<?php
  function hello_menu(){
    $items = array();

    $items['nodes'] = array(
      'title'            => t('My Nodes'),
      'page callback'    => 'helloworld_output',
      'access arguments' => array('access content'),
    );

    return $items;
  }

  function hello_theme($existing, $type, $theme, $path){
    return array(
      'timeline' => array(
        'variables' => array('content' => NULL),
        'file' => 'timeline.tpl.php',
        'path' => drupal_get_path('module', 'hello')
      )
    );
  }

  function helloworld_output() {
    header('Content-type: text/plain; charset=UTF-8');
    header('Content-Disposition: inline');
    return theme('timeline', array());
  }
?>

```

..and this is what I want rendered in the body.

```
<script>
    var tl;
    function onLoad() {
        alert('I have loaded');
    }
</script>
<div id="tl" class="timdef" style="height: 300px;"></div>

```

If I place this code into my `timeline.tpl.php`, it doesn't get rendered in the page but before the whole content. Do I need to wrap this in PHP tags?

How can I get the `onLoad()` function to fire once my Drupal page is loaded. I a normal HTML page, I could use the `body onload=` callback.

(It looks really simple when you've worked with Drupal but for a first-timer, it's been a nightmare.)

# Answer
> 0 votes
The best way to add the JavaScript in Drupal is to have an external JS file like helloworld.js in your module/theme and include it using the function,

```
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
   );
  drupal_add_js('http://example.com/example.js', 'external');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

```

For more info see drupal\_add\_js()

> How can I get the onLoad() function to fire once my Drupal page is loaded. I a normal HTML page, I could use the body onload= callback

jQuery(document).ready is similar to your onload function that you are trying to call in your HTML body.

**UPDATE:**

Add the "template" instead of file in your hook\_theme for using templates like,

```
 function hello_theme($existing, $type, $theme, $path){
    return array(
      'timeline' => array(
        'variables' => array('content' => NULL),
        'template' => 'timeline',
        'path' => drupal_get_path('module', 'hello')
      )
    );
  }

```

---
Tags: 7, theming, javascript
---


# Question
Title: When to use Views attachments vs. content panes?
Up until now, I've always used content panes provided by Views in Panels to accomplish tasks like "Related content" and "Additional information about ABC." I just realized that Views also provides an `attachment` display, which as far as I can tell seems to be similar to a content pane except it doesn't require Panels.

However, if I'm already using Panels, are there any use cases where I would be better off using an attachment instead of a content pane, or are these basically the same thing?

# Answer
> 3 votes
There may some cases where an attachment is more useful than a content pane, but I always go with content panes by default.

1. Split content panes allow easier reuse of the View. You can show the View by itself in a second location, and make minor overrides with a second display.
2. You can easily have individual Pane settings. Caching, style, visibility rules etc.

I think the case in general for attachments would be if a second view absolutely depends on a first one. If they would never make sense individually, then one could might as well "combine them" into one, although the benefits are fairly limited, such as "move only one pane in the UI".

# Answer
> 4 votes
Attachments can inherit the exposed filters of the display they are attached to.

---
Tags: views
---


title: How to cache a node_load_multiple

text:
# Question
Title: How to cache a node_load_multiple
I'm loading 5 media gallery nodes into a single page via node\_load\_multiple(). Unfortunately the load time is very slow, several seconds. I read up on Drupal's caching mechanism, and Jeff Eaton's tutorial and got the idea that I could cache each gallery node via the `#cache` array on the node's renderable array. I think I've set everything up correctly, but I'm not seeing any increase in performance. Any idea what I've done wrong or neglected to include? Here's what I've done on a page.tpl.php for the page that contains the galleries:

```
$nodes = node_load_multiple($nids = array(1653,1654,1656,1657,1658), NULL, FALSE);
$i = 0;
$cid = "gallery_cache";
foreach ($nodes as $gallery) {
  $renderable = node_view($gallery);
  $cid .= $i;
  $renderable['#cache']['cid'] = $cid;
  $renderable['#cache']['bin'] = 'cache_page';
  $renderable['#cache']['expire'] = '1392001200';
  print drupal_render($renderable);
  $i++;
}

```

# Answer
> 3 votes
The results from `node_load_multiple()` are already cached within a single page load - the only time they're not is if you pass the `$reset` parameter as `TRUE` (which you're explicitly not doing). Looking at the code calls to `node_view()` don't seem to be cached, but I might be wrong there.

At a guess your performance hit might be coming from those individual calls to `node_view()`, which you might be able to mitigate a bit by using `node_view_multiple()` instead.

```
$nodes = node_load_multiple(array(1653,1654,1656,1657,1658));
$views = node_view_multiple($nodes);

foreach ($views as $view) {
  // ...
}

```

I'm pretty sure the reason your code isn't working as you expect is that the return from `node_view()` isn't a reference to anything, so the changes you're making to the array aren't actually getting saved anywhere, only to the local copy of the array.

One last piece of advice...it would be a good idea to take this code out of the template file and put it in a preprocess function at the the theme or module level. Running database queries directly in the template file isn't the best idea for a number of reasons.

---
Tags: 7, caching
---


title: Show taxonomy children in parent

text:
# Question
Title: Show taxonomy children in parent
I have a block view that only displays the taxonomy terms in a vocabulary. However I would like to have a link generated in that block with an "ALL" option. So I created a new taxonomy entry, which is the parent of all other terms.

However if I go to the taxonomy parent, the children aren't shown, only if the nodes are set to the parent value explicitly.

For example:

```
All (tid=1)
-Shirts (tid=2)
--Small (tid=3)
--Big (tid=4)
-Shoes (tid=5)

```

So if I were to go to `http://mysite.com/taxonomy/term/1` I want it to show all nodes in terms 2 and 5 (would be ideally to have 3 and 4 show up also, but not mandatory).

I am using Drupal 7.x

# Answer
> 2 votes
Have you tried using `taxonomy_get_children()`?

> Finds all children of a term ID.

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


title: WSOD in homepage

text:
# Question
Title: WSOD in homepage
I am getting WSOD just in homepage and the hardest part is it is not giving any clue of what is the error. Tried to check the error log but there is no error. Tried also to add this in the index.php

```
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

```

But the above code didn't help. Viewing the source code in the browser gives me...

```
<html>
<head></head>
<body>
</body>
</html>

```

The weird thing is when I restarted memcached the problem go away. But this happen regularly like when I restarted Memcache after 3 days problem return so I need to restart the Memcache and other caching.

Additional details of the site:

1. Homepage is mostly Views
2. I'm using Memcache and Boost
3. Context

# Answer
Try adding this to your `settings.php` file (not `index.php`). After you see what error message you have we might be able to help you better. Usually WSOD are caused by a PHP fatal error.

```
error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

Source: Show all errors while developing
> 1 votes

---
Tags: views, 6, caching, wsod
---


# Question
Title: views_query_alter apply "%LIKE%" condition
Is there a way in which I can alter the view query so I can get items that contain a specified string in title?

For example something like this:

```
if (isset($_GET['query']) && (!empty($_GET['query']))) {
    $view->query->add_where('title', $_GET['query'], 'LIKE');
}

```

# Answer
You can do it using code similar to the following one.

```
function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', $_GET['query'], 'LIKE');
  }
}

```

The first argument that is required from $query-\>add\_where() is the group for the WHERE to add. The documentation says to pass 0 as argument, to use the default one.

The code I shown works if `$_GET['query']` contains an SQL regular expression. If `$_GET['query']` contains a string that is not a regular expression, and that is used to build the regular expression for example as `'%' . $_GET['query'] . '%'`, the code to use should be the following one.

```
function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', '%' . db_like($_GET['query']) . '%', 'LIKE');
  }
}

```

Notice what reported in the documentation for `views_plugin_query_default::add_where()`:

> The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.

### References
> 3 votes

---
Tags: 7, views
---


# Question
Title: Markup filtering at theme level (security)
Please could someone advise if any sort of sanitization/filtering is required for the #markup below i.e. check\_markup(), check\_plain(), etc

The $title variable is basically just from drupal\_get\_title().

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

        // Some code goes here to remove title from page and use in form (not part of the question)

    $form['title'] = array(
        '#type' => 'item',
        '#markup' => '<h1>' . $title . '</h1>',
        '#weight' => -100,
    );

}

```

# Answer
Rather than remembering specific rules about which variables are safe at which point in the process I suggest you just test things out.

If you can execute Javascript by entering it as the title then you know you have a problem. I try each of these two example snippets of javascript when I want to test something:

```
<script>alert('xss');</script>
<img src="notfound.png" onerror="alert('xss');">

```

If your sanitization is working properly then you should either see the tags escaped (displayed as \>) or stripped (completely removed from the output).

It is also good to understand the internal workings of Drupal so that you know which functions are safe or not, but knowing how to test for XSS will serve you well in dealing with areas where you are unsure or working with something other than the API.
> 2 votes

# Answer
No sanitation need, if you get the $title by drupal\_get\_title. Just look at the drupal\_set\_title(). It has an `$output = CHECK_PLAIN` argument, which means, the title is sanitized by default.
> 0 votes

---
Tags: 7, security
---


# Question
Title: How to add a assign a value to File Field Desciption through tokens
Have been struggling with this, I have a field collection that contains a selection list and will like to assign this value to a file field description in the same field collection, so the selected value becomes the file display name.

Many thanks, Peace!

# Answer
> 0 votes
You can use: $form\['#attached'\]\['js'\] in your form preprocess to add some javascript that will set the field values.

---
Tags: entities
---


# Question
Title: Are db_update->condition() and db_update->where() the same?
Are db\_update-\>condition() and db\_update-\>where() the same? If not, what are the differences?

# Answer
condition() always involves a field/column name and a provided value (or an array of provided values). where() can contain arbitrary conditions (comparing fields against each other, can contain functions/expressions), it's just a string that is passed through.

condition() example, select everything where created is bigger than timestamp value.

```
$timestamp = 123465...;
$query->condition('created', $timestamp, '>');

```

where() example, select everything where changed is bigger than created.

```
$query->where('created < changed');

```

Everything that can be done with condition() can also be done with where(), but not the other way round. The following is the same as the condition() call.

```
$query->where('created > :timestamp', array(':timestamp' => $timestamp));

```

Works just fine, but is way more complicated. The basic rule is that condition() should be used whenever possible and if not, use where().
> 9 votes

---
Tags: database
---


title: Drupal on nginx: 404 Error

text:
# Question
Title: Drupal on nginx: 404 Error
I'm migrating my drupal websites from a server running with Apache web server to a Nginx server. The problem is, I can't access any of my websites on the nginx server. It redirects me to a 404 error page for all websites.

Any suggestion?

# Answer
> 1 votes
Were you using clean URL's before the migration? If this is the case, than you may need to set up mod\_rewrite only for nginx. I have not used the server but found this article on how to achieve the same.

http://wiki.nginx.org/NginxHttpRewriteModule

Not sure if this is your problem though, although it might be.

---
Tags: 7
---


# Question
Title: How to prevent user from viewing profile
I go into `Administration>People>Permissions>User>View user profiles` and see that only admin has this permission, however while logged in as non-admin I can still see his profile when I go to `/user`

# Answer
> 0 votes
I had success with Tab Tamer module and I was able to hide tabs while still giving the admin access to modify if needed.

# Answer
> 1 votes
There'd be a few ways you could do it, the fastest might be to create a user-profile.tpl.php and do a check for the user's group.

---
Tags: 7, users
---


# Question
Title: Why is $form_state always empty, even when my form-building-function is called after validation?
I'm having a little trouble with the terminology here, so I'll explain my problem directly with code samples (trucated for clarity).

**myModule.module**

Here I create a menu with a link to a form built using a function declared in form\_identification.php

```
[...]
require_once(dirname(__FILE__) . '/form_identification.php');
[...]
function myModule_menu() {
    $weight = 1;
    $items = array(
        'identification' => array(
            'title' => t('Identification'),
            'page callback' => 'identification_callback',
            'access arguments' => array('Acces myModule'),
            'type' => MENU_NORMAL_ITEM,
            'weight' => $weight++
        ),
        [...]
    );
    return $items;
}
[...]
function identification_callback() {
  return drupal_get_form("form_identification");
}
[...]

```

**form\_identification.php**

This file holds the function which builds the form, called form\_identification

```
function form_identification($form_state) {

    error_log("form_state: " . print_r($form_state, true));
    // always outputs `form_state: Array\n(\n)\n`

    $form = array(
        '#attributes' => array(
            'enctype' => 'multipart/form-data'
        ),
        'sex' => array(
            '#type' => 'textfield',
            '#title' => t('Sex'),
            '#disabled' => true
        ),
        /*[...]*/
        'enregistrer' => array(
            '#type' => 'submit',
            '#value' => t('Enregistrer'),
            '#submit' => array('form_identification_enregistrer')
        )
    );
    return $form;
}

function form_identification_validate($form, &$form_state) {
    /*[...]*/
}

function form_identification_enregistrer($form, &$form_state) {
    /*[...]*/
}

```

As you can see, I'm printing the contents of `$form_state` to the log every time `form_identification` is called, so I can confirm that the function is called on page load and also after validation. The problem is that in both cases, I just get an empty Array (`Array\n(\n)\n`). I would have expected to get an array full of form info when the function is called after validation. That way, I could have a look at the values entered and decide how to build the form based on them. Is there any way to achieve this? In what situation would `$form_state` NOT be an empty array?

# Answer
You've just got the signature for the form function slightly wrong, it should be:

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

```

The first arg that's passed to your form function by the form builder is the `$form`, which for a new form is pretty much always an empty array.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Calendar widget link to list a day's events
I am using the Calendar module to manage an events calendar on a new site. Currently when you click on a day in the widget it takes the user to the calendar page that shows a small list of the titles.

Is there a way to create a view that shows all of the days, and events for that day, in a single spread and bypasses the calendar completely?

# Answer
> 0 votes
I have got it: If you go to the *Day* view under the Calendar view, you can change the format to *HTML list* and show fields. From there, add the fields of the calendar event you want to show.

---
Tags: 7, datetime, entities
---


title: Missing external file

text:
# Question
Title: Missing external file
In my site, I'm getting a 404 error (http://www.site.com/&mch57a). I'm guessing it's a problem with a module. Is there a way to trace where this call is coming from, other than disabling modules one at a time? I do have the devel module.

Thanks for the help

# Answer
I think you need to look at URL aliases under configuration/Search and metadata or look it up in the url\_alias table in the database.

Worst case scenario, try to search "&mch57a" in the entire database, to see which module is generating it.
> 0 votes

# Answer
I figured out the problem, but not the workaround - it was caused by the links to Google's webfonts in my info file
> 0 votes

---
Tags: database
---


title: How to show Taxonomy menu on Page View?

text:
# Question
Title: How to show Taxonomy menu on Page View?
I would like to show Taxonomy menu on Page view ,so i could select different taxonomy terms to show related items with it.It has to exactly like following link www.techmusicschool.co.uk/courses/index.php

# Answer
> 0 votes
I used Quick tab module to made taxonomy terms as tabs then i have created different views for each tabs and yes its working ...Thanks..

---
Tags: taxonomy-terms
---


# Question
Title: Drupal & AJAXified links: hook into requests before they are sent?
I've got a link 'test/nojs' on a page. I've added the class 'use-ajax' to that link, so that Drupal automatically AJAXifies the link and replaces the 'nojs' part with 'ajax'. So far so good.

However, I'd like to hook into the AJAX request as there might be cases where I'd like to stop the request from being sent off to the server. However, I can't get it up and running properly.

One post say that I can do this by setting a 'hook' function in Drupal.ajax\[element\].beforeSend(a,b) and some places say that I can do it by settings a 'hook' function in Drupal.ajax\[element\].options.beforeSend(a,b). However, I can't get any of this to work.

Is there a "right" way of hooking into the AJAX process? Even better, is there a "right" way of hooking into the AJAX process for certain elements?

# Answer
You can use the following code,

```
Drupal.ajax[element].default_beforeSend = Drupal.ajax[element].beforeSend;
Drupal.ajax[element].beforeSend = function(xmlhttprequest, options) {
  if (1) {
    xmlhttprequest.abort();
  }
  else {
    Drupal.ajax[element].default_beforeSend(xmlhttprequest, options);
  }
}

```
> 1 votes

---
Tags: 7, hooks, ajax
---


# Question
Title: How to render a field above the node title using omega sub-theme
I am trying to render a slideshow in a node above the page title

So far I have in my template.php

```
function MYTHEME_preprocess_region(&$vars) {
  $theme = alpha_get_theme();
  if ($vars['elements']['#region'] == 'content') {
    $vars['node'] = $theme->page['node'];
  }
}

```

this passes a $node variable into a custom region--content.tpl.php I was then expecting to be able to use this snippet to render the field but it fails

```
print render($node['field_slideshow_images']);

```

# Answer
You might get a bit more luck using the `field_view_field` function:

```
function MYTHEME_preprocess_region(&$vars) {
  $theme = alpha_get_theme();
  if ($vars['elements']['#region'] == 'content') {
    $node = $theme->page['node'];

    $vars['slideshow'] = field_view_field('node', $node, 'field_slideshow_images');
  }
}

```

And then use `print render($slideshow);` in your template file.

You might need to play with the 4th parameter to `field_view_field()` (`$display`) a bit if you have custom settings on your display for that field, but it should be a good place to start.
> 2 votes

# Answer
For anyone else who needs to do this, here is a shorter version with better validation and using menu\_get\_object instead of getting the node from the theme.

```
function MYTHEME_preprocess_region(&$vars) {
  if ($vars['elements']['#region'] == 'content') {
    if ($node = menu_get_object()) {
      $vars['slideshow'] = field_view_field('node', $node, 'field_slideshow_images', 'default');
    }
  }
}

```

Then in region--content.tpl.php

```
print render($slideshow);

```
> 0 votes

---
Tags: theming
---


# Question
Title: Toggling not working properly in node--contenttype.tpl.php file
I am theming a node of type "test". I am using toggling in this "node--test.tpl.php" file.

Below is my code in "node--test.tpl.php":

```
    <div id ="block1" class="block_custom">
    <a href="javascript://" ><h1  class="active_custom">Property</h1></a>
    <div id="block1_content" style="background-color: rgb(233, 233, 233);" >
        <table cellspacing="0" cellpadding="3" class="tabledata">
    <tr>
    <td valign="top" nowrap="">
    <b>MLS #:</b>
    </td>
    <td valign="top">
    <?php echo $node->field_listing_id['und']['0']['value'];?>
    </td>
</tr>
</table>
</div>
</div>

```

code in javascript file is

```
 (function ($) {
        $('#block1 > a').click(function()
       {
        $("#block1_content").toggle("slow");

         });

  })(jQuery);

```

Loading the java script files in template.php

```
drupal_add_js("themes/bartik/custom.js", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("themes/bartik/jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);

```

jqueries and jquery plugins are enabled in modules.

but toggling is not working.

How to do toggling using jquery

# Answer
Try writing it when document get ready like this:

```
jQuery(document).ready(function ($) {
        $('#block1 a').click(function()
       {
        $("#block1_content").toggle("slow");

         });

  });

```
> 1 votes

# Answer
No need to add "jquery.min.js". Drupal has by default this file.
> 0 votes

---
Tags: 7
---


# Question
Title: Hide menu items from non-authenticated user
> **Possible Duplicate:**
> Hiding link from anonymous users

I have 2 nodes on Drupal 7 site, that only authenticated users can access. But even if I logout, links to these nodes appear in the main menu. When I click any of them, it gives:

```
Access denied
You are not authorized to access this page.

```

Which is correct. As far as I know, Drupal must hide the links, that the user can't access. But for these items it doesn't.

How to fix?

# Answer
> 0 votes
It's definitely a bug in Drupal core. It shouldn't give links, the user doesn't have access to.

I fixed it, using the programming in page.tpl.php in my theme, adding if($user-\>uid != 0):

```
<?php
      global $user;
      if($user->uid != 0)
      {
             if ($main_menu):
?>
      <div id="main-menu" class="navigation">
        <?php print theme('links__system_main_menu', array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu-links',
            'class' => array('links', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#main-menu -->
    <?php
               endif;
      }
 ?>

```

# Answer
> 3 votes
Follow Below things:

1) Make sure that in admin/people/permissions "View published content", "view own Unpublished Content are "Unchecked" for the "anonymous user".

2) Still if you are getting those "Disclaimer and Policies" menu links. i) Create a new menu and add those links in to that menu. While adding links Give the Parent menu link to "Main Menu". and save the menu. ii) Then admin/structure/block, configure the menu block: Give the permission to access only to Authenticated User and save the block

---
Tags: routes
---


# Question
Title: Encoded strings in hook_menu wildcard case menu item to lose access
I'm trying to create a menu link within the admin area that includes a urlencoded() copy of the current URL as a tail to the link URL, so that the code invoked can redirect back to the current page when it's done its job.

However, as soon as the string returned by my \_to\_arg() callback contains a URLencoded string (Or specifically any string containing a % character), Drupal drops access rights to that menu, and the link is hidden.

Sample code below:

```
/**
 * Implements hook_menu().
 */
function admin_bar_menu() {

  $items['admin/bar/%test'] = array(
    'title' => 'Admin Bar Test',
    'page callback' => '_admin_bar_redirector',
    'page arguments' => array(2),
    'access callback' => 'user_access',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 15,
  );

  return $items;
}

function test_to_arg ( $arg, $map, $index ) {

  // 1. Link is shown, but is of the form /admin/bar/admin/appearance,
  // so the desired string (admin/appearance) can't be retrieved
    // return $_GET['q'];

  // 2. Link is hidden
  // return urlencode($_GET['q']);

  // 3. Link is hidden
  // return 'foo%bar';

}

function _admin_bar_redirector($destination) {
    drupal_goto($destination);
}

```

I'm pretty sure this is being caused by the following code in menu.inc (Line 911 - d7.14):

```
// Skip links containing untranslated arguments.

if (strpos($item['href'], '%') !== FALSE) {
  $item['access'] = FALSE;
  return FALSE;
}

```

Can anyone suggest a potential avenue for a fix to the code in menu.inc - or is there a better way to achieve what I'm trying to do?

# Answer
> 2 votes
I've assumed this needs fixing in core, so logged it here - any insights welcome!

http://drupal.org/node/1822004

---
Tags: routes
---


title: Setting up Drupal without a domain name

text:
# Question
Title: Setting up Drupal without a domain name
A site's been developed on localhost and I want to move it to my new hosting, which uses Plesk. This hosting doesn't have DNS pointing to it, although the domain is added. (The domain name is currently pointing to my old hosting.)

I have changed `$base_url` to the preview URL Plesk provides:

```
$base_url = 'https://the-url-pleskprovides:8443/sitepreview/http/myurl.com';

```

I can access the site and even browse, but I can't login because login redirects to `https://the-url-pleskprovides:8443/user` instead of `https://the-url-pleskprovides:8443/sitepreview/http/myurl.com/admin/`.

Is there any way to work with Plesk preview, or with Drupal without a domain?

Any help will be highly appreciated.

# Answer
Ok, the answer is unfortunately Drupal can not handle this situation. What should be done is the following:

**On Windows**

Go to: C:\Windows\System32\drivers\etc

Open: hosts file

Add at the end:

```
100.200.10.20 yourdomainname.com
109.200.10.20 www.yourdomainname.com

```

**On Mac**

Open Terminal (Applications -\> Utilities -\> Terminal)

Open hosts file: `$ sudo nano /private/etc/hosts`

Type your user password when prompted

Add at the end:

```
100.200.10.20 yourdomainname.com
109.200.10.20 www.yourdomainname.com

```

Save the file Flush the DNS cache: `$ dscacheutil -flushcache`

**NOTE:** The IP is the IP of your server. You can get it by logging into Plesk, Home\>System Overview
> 3 votes

# Answer
One feature that Plesk 10 and 11 support is the use of a proper preview domain (which is a proper ServerAlias in Apache which Drupal will like) but it needs to be setup by the server sysadmin. It isn't something that a regular shared hosting account has access to change. In the control panel it's referred to as 'Quick Preview' see the manual.

If it is setup every site on the machine will get a hostname similar to:

domaininplesk.com.\[plesk server ip\].externaldomain.com

where \[plesk server ip\] is the ip assigned to the hosting account with the dots replaced with dashes e.g. 127-0-0-1.
> 0 votes

# Answer
I would do the following if I was in your shoes: Put a temporary entry in your robots.txt file so it won't get crawled. You can also add something in your /index.php; check `$_SERVER['HTTP_HOST']` to see if it's the temporary one or not.

Basically, just run the site from the temporary plesk domain until you're ready; then, change the settings file.
> -1 votes

---
Tags: 7
---


# Question
Title: Hooking into an update of the db system table
Essentially I want to be able to monitor all updates to the db system table, by catching all updates to the db system table (for a particular theme's record). We have encountered some odd bugs whereby all themes are periodically (and apparently randomly) disabled, and I need to be able to log further information whenever this theme is disabled. What is the best way to approach this?

Alternatively is there a way to hook into the function for whenever a theme is enabled/disabled?

# Answer
You should be able to use `hook_themes_disabled()`.

The following code in a module will put themes being disabled into the Drupal logs:

```
function MYMODULE_themes_disabled($theme_list) {
  foreach ($theme_list as $key => $themename) {
    watchdog('MYMODULE', '%themename was disabled.', array('%themename' => $themename), WATCHDOG_NOTICE);
  }
}

```

EDIT: Forgot to mention this, but `hook_themes_enabled()` is used in exactly the same way, so you could easily just modify the hook above to check when a theme is enabled.
> 1 votes

---
Tags: 7
---


# Question
Title: How to change "Description" in File field to drop down instead of text field?
What is the best way to modify the File field so the "Description" field is a select box instead of a text field. I.e. I want to go from:

To this:

I tried a quick experiment, editing the File modules `file.field.inc` file, which resulted in the screenshots above, but if I can avoid forking the File module and instead do it some other way it would be great.

# Answer
> 1 votes
You can use `hook_field_widget_form_alter()` to add your own `#process` callback to the element.

In the callback you can just change the description field from a textfield to a select.

# Answer
> 1 votes
Turns out the easiest solution is to use the Field Collection module, which allows me to do just what I want.

---
Tags: 7, files
---


# Question
Title: Use Ajax to load full node including comments and comment form
I tried to use Ajax links API Module, nice module it even replace url when loading page but it works so slowly... I can wait page loading even for few minutes. I found another solution seanbuscay.com it works better but it doesn't load comments and comment form. I would like to load full node including comments (create view reference field with related comments didn't help).

I found some similar topics

Ajax via Jquery and attach behaviors

Load and interact with a node comments from their related node

Is it the best solution for Drupal 7 t use drupal.attach.behaviours?

Have anybody experience with loading full nodes with comments via ajax?

# Answer
> 1 votes
This modules contains a lot of extra code for your case and probably make too much unnecessary actions. You should to make a little script to make jQuery.ajax that make request, insert your node with comments in and connect it to your theme. This modules made request by Query.ajax too.

Less code - faster action and may the force be with you.

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


# Question
Title: Drupal's 7 sites folder with its mysterious permissions and ownership
The problem is that I had to give sites directory and all subfolders and files of it permissions 777 in order for drupal to recognize this folder and not redirect me to install.php page. But on a virtual hosting I noticed that sites is a protected folder and all of its content esspecially sites/default/settings.php with 550 permissions. I did not get the magic trick here, how does drupal recognized that folders. I have created drupal's folders and files both as root and other sudo users, but it did not help. And drupal still see only sites with 777 permissions.

# Answer
> 3 votes
You need to insure that the php process (web server) is a member of the group for the Drupal files. You should make sure that the owner of the files is some user other than the php process / web server, because you do **not** want to allow the web server to overwrite the Drupal code files.

To change the group of all of the files in your root:

```
sudo chgrp -R webgroup /path/to/drupal

```

To add a group to the web server user:

```
sudo usermod -a -G webgroup www-data

```

For more advice on correctly setting file permissions for Drupal, see Securing File Permissions and Ownership.

**Edit:** It was suggested that this answer be expanded to point out that the above page contains a script for setting your permissions. There is also a Drush command for setting permissions in progress at http://drupal.org/node/990812. Both of these scripts can be helpful, but only if you set the user and group ownership of your files correctly, and insure that the web server user is a member of the applicable group as explained above. Please read the quoted page carefully, as it explains these concepts.

# Answer
> -1 votes
try this just replace "USER" with your login name without the Quotations this should solve all permission problems

```
cd /var/www
sudo chown -R "USER":www-data .
sudo chmod -R 750 .
find . -type d -wholename "*/sites/*/files" -exec sudo chmod -R 770 {} \;
sudo chmod g+s .
find . -type d -exec sudo chmod g+s {} \;

```

this will set all the permissions as suggested by drupal if the problem still persists then the problem isnt with permissions

---
Tags: users, migrations, installation, files, drush
---


title: Block with single image at top

text:
# Question
Title: Block with single image at top
I want to display an image at the top of my block. My block is a dynamic Views block, and it displays the top 5 latest news items. Is there any module to do so.

Also is it possible to rotate image and content within certain time interval (Eg. 1 hour).

# Answer
> 1 votes
You can have another view which selects that image. Then on your existing view you can add a header and choose "Global: View area". Then you just select the view you created earlier and that's it.

Another solution would be to have just another views block displaying that image.

The third solution would be to add an attachment (under Displays click Add \> Attachment) instead of a new view block. Choose the fields (image in your case) and attach this (look for ATTACHMENT SETTINGS section) to your existing one.

---
Tags: 7, views, theming, blocks, media
---


# Question
Title: Form api custom validation function doesn't work
I'm trying to reuse the login form in my own form. So far so good, everything is populated and shown properly. Now I want to use my validation functions to validate some data, so I tried to add them:

```
$userLogin = drupal_get_form('user_login');
array_unshift($userLogin['#validate'], 'MY_UBERLEAD_FUNC_validate');
$form['selfservice_ad_tabs']['tab_3']['login'] = $userLogin;

```

Printing the form shows that the function is in the proper place, but it was not invoked when expected.

I tried several other methods:

```
$userLogin['actions']['submit']['#validate'][] = 'MY_UBERLEAD_FUNC_validate';

```

also removing all validation handlers and leaving just mine, but those didn't work either.

Can somebody point what i am doing wrong or explain how i can reuse existing form **into** my custom form using my validation functions.

Thanks in advance!

# Answer
> 0 votes
I think that if you use `drupal_get_form()` you can't alter the form because the form will be already built, cached and all the processing done.

Try this instead.

```
$form_init = array();
$userLogin = user_login_block($form_init);

array_unshift($userLogin['#validate'], 'MY_UBERLEAD_FUNC_validate');
$form['selfservice_ad_tabs']['tab_3']['login'] = $userLogin;

```

---
Tags: forms
---


# Question
Title: Is there a way to share content between users?
Drupal 7... I just want to be able to send some information via content type from one user to the next such as an event. One user will create this content and only wants it seen by a select few of other users. Is there a way to make this happen. What would be cool is a field on my content type that collects usernames or emails for a private message or invite to view the content...

# Answer
You will find that the Organic Groups module is very useful for allowing users to protect content in this way. You may configure og such that only certain users may create groups, or if you prefer, as in the use case you describe above, many users may be allowed to create new groups for diverse purposes. There are many options on inviting users to groups, allowing users to request memberships to groups, or just letting anyone join groups automatically. It looks to me as if the behaviour you want can be achieved with just the og module, but if that is not the case, there are also many additional contrib modules that can extend or modify og's behavior.
> 2 votes

---
Tags: nodes, privatemsg
---


title: Allow users to create video playlists

text:
# Question
Title: Allow users to create video playlists
I have created a content type called "Video" and I was wondering if I should create another content type called "Video Playlist" that act as a container for storing a collection of the nodes that are of content type "Video"?

Each user will have a list of favorites that will be public to everyone and all the other playlists would be optionally public or private only to that user. How would you go about creating this structure/layout? Is this the best approach?

# Answer
You can use Flag Module with drupal views to create your playlist. Flag module allows you to bookmark contents, comments etc. Then you can display the flagged content by adding flag:content relationship in your view.
> 4 votes

# Answer
In addition to the Flag module, you can use the Flag Lists module to allow users to create their own unlimited playlists like favorites, funny, etc...
> 1 votes

---
Tags: nodes
---


title: Memcached tuning

text:
# Question
Title: Memcached tuning
Does the memcache module works by default after instalation (by setting up the `$conf['cache_inc']` in the settings.php file ) or it needs some other tweaks or some custom code?

I have memcache up and running on a server and I can see the memcache debug messages. It looks like it is working fine but I can't see any improvements.

I'm using the drupal 6 version on the module.

# Answer
The memcache module works by default. You don't need to do anything else to get it working. There are some minor tweaks one can do though; here is what my settings.php file looks like: Optimal Settings.php for Pressflow + Varnish + memcache
> 1 votes

---
Tags: 6, performance, caching
---


# Question
Title: Executing JS calls during user login validation (Drupal 7)
I need to execute three different JS calls during the login process (for tracking reasons) depending on how the validation goes. I have no idea where to include them:

```
1. Event: Login failed (wrong password and/or user name)
-> wrong_pass();

2. Event: Incorrect E-Mail format (I am using E-Mail addresses as user names)
-> wrong_email();

3. Event: Login successful
-> login_ok();

```

How can I catch these events and react to them by executing the respective JS calls?

Thanks in advance!

# Answer
You could add a validation hook to the user login form & block to add the javascript if the fields fail to validate.

So to alter the form:

```
function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  // Add the validate function
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // Add your javascript that contains Drupal.behaviors
    drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . '/MODULE_NAME.js');
    $form['#validate'][] = '_MODULE_NAME_user_login_validate'; // this is the function name
  }
}

```

Then in your validation function:

```
function _MODULE_NAME_user_login_validate($form, $form_state) {
  // Do your field validation here, I'll only showcase one of them (username)
  if(!valid_email_address($form_state['values']['name'])) {
    // Add a setting to the Drupal.settings variable available in javascript
    drupal_add_js(array('MODULE_NAME' => array('name' => FALSE)), 'setting');
  }
}

```

Finally in your `MODULE_NAME.js` file you can check to see if the setting was set:

```
if(Drupal.settings.MODULE_NAME.name == FALSE) {
  wrong_email();
}

```
> 2 votes

---
Tags: javascript, users
---


title: <?php replaced with <!--?php

text:
# Question
Title: <?php replaced with <!--?php
I am upgrading Drupal 6.26 to Drupal 7. I had a small handful of nodes (a dozen or so) that contained PHP code. After the upgrade, I've found that the `<?php` tags have been replaced with `<!--?php`.

I searched the Google but all I found was http://drupal.org/node/1403918. I'm not using the WYSIWYG module though. I am using CKeditor so I followed the advice in post 1 but that didn't resolve the problem.

I have the PHP filter module enabled.

When I try to edit the node, the `<?php` tags are not HTML comments so I can't fix it that way. How can I fix this?

Edit 1: I don't think CKeditor has anything to do with this actually. I've completed disabled the CKeditor module and I'm still getting issues mentioned above.

Edit 2: I have a script that resets it back to 6.26. When I re-upgraded, the PHP scripts execute before I enable any non-Core modules. I then enabled everything but CKeditor and it fails so I don't think its CKeditor but another module. I will attempt to further diagnose.

# Answer
> 1 votes
The issue ended up being with the drupal 7 version of http://drupal.org/project/contemplate. By not enabling that module, my issue was fixed.

Thanks to all who responded!

# Answer
> 3 votes
You don't have to accept this as an answer, but I would recommend not using CKEditor with the PHP input format. In D7's CKEditor module you're able to attach CKEditor to input formats, as opposed to D6 where you specified textfield IDs and paths and such. Therefore, you can just attach CKEditor to the "Filtered HTML" and "Full HTML" input formats and leave PHP alone. I just think it's a bad idea to try and use wysiwyg formatting that contains code like this.

So, my recommendation would be: 1) Disable CKEditor for the PHP input format. 2) Edit the handful of nodes and replace `<!--?php` with `<?php`

# Answer
> 3 votes
Disable any additional filters like html corrector on the PHP input format. If it's not caused by CKEditor, it could be this.

---
Tags: wysiwyg
---


# Question
Title: Overriding the function of a module in another module
Module1 has a function named 'function1'. 'function1' is not a type of hook, but it is a menu callback, or called inside a hook.

Module2 wants to override 'function1' using all variables which are available to function1 inside Module1.

I can call function1 using `module_load_include()`, but I need to override the called function.

How can I achieve this?

# Answer
If you want to use a different menu callback, you can implement hook\_menu\_alter() to change the menu callback. Suppose you want to override the menu callback Drupal defines for search, you could use the following code.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['search'])) {
    $items['search']['page callback'] = 'mymodule_search_view';
  }
}

```

From `mymodule_search_view()` you can call search\_view() without first including the file containing it, as that is done from Drupal before calling the menu callback.

Similar code could be done if the menu callback is returning a form, with the exception that, instead of changing the page callback (which probably is drupal\_get\_form()), you would change the page arguments to use as first argument the callback name of the function returning the form array. Rather than doing this, you should implement hook\_form\_alter(), and to hide the not necessary form elements with `$form['element']['#access'] = FALSE', and not with`unset($form\['element'\])\`.

As for replacing a function that is called from a hook, what can be done is removing the hook implementation that calls that function, and replacing it with a different implementation. It is possible only with Drupal 7, and it must be done carefully. (I will explain why right.)
Suppose you want to change the function called in menu\_node\_update() (the implementation of hook\_node\_update()) from menu\_node\_save() to `mymodule_node_save()`. You could use the following code.

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    unset($implementations['menu']);

    $implementations = array('mymodule' => group) + $implementations;
  }
}

function mymodule_node_update($node) {
  mymodule_node_save();
}

```

In this way, `menu_node_update()` would not be invoked anymore, but `mymodule_node_update()` would.

Normally, modules that depend from a hook implemented by another module don't check if that hook is executed; they check the module is enabled (and assume the hook is invoked), or they add that module as their dependency. Avoiding a hook is executed could cause problems to other modules which could be difficult to track. If it is really necessary to avoid a hook implemented by another module is executed, you should first check on a test site that all is working as expecting. Bear in mind that future Drupal version could break your code, and the code you are writing should be tested on future Drupal version too (when they are available).
> 7 votes

# Answer
You should try a module\_invoke\_all

Supposing your module A callback return the variable $output like this :

```
function module_a_callback($args){
$output =... your calculs ...
return $output;
}

```

Add this : module\_invoke\_all('module\_a\_alter');

```
function module_a_callback($args){
$output = ... your calculs ...

// call all module implementing your 'module_a_alter' hook
$alter =  module_invoke_all('module_a_alter', $args);

//if there is an answer,
$final_output = isset($alter[0]) ? $alter[0] : $output;
return $output;
}

```

You just created the hook\_module\_a\_alter($args) hook. In your module B, create the corresponding hook implementation

```
function module_b_module_a_alter($args){
 $output =... your calculs from module B ...
return $output;
}

```

Here a second methode, faster, using variables passed by reference :

```
 function module_a_callback($args){
 $output = ... your calculs ...

// call all module implementing your 'module_a_alter' hook
module_invoke_all('module_a_alter', $output,  $args);

return $output;
}

```

In your module B, create the corresponding hook implementation

```
function module_b_module_a_alter(&$output, $args){
 $output =... your calculs from module B ...
}

```

Have a look at this for a mini tuto. You can also use a module\_invoke which allow you to specify the module listening your hook call.
> 2 votes

# Answer
This is more of a php language issue than about Drupal per se....

You can't redefine a function in php by default. You could try using the runkit extension which will allow you to do it, but as far as I know use of runkit on production servers isn't recommended as it can get quite heavy.

In the cases where you absolutely need to change the functionality of another module, a well maintained patch is probably more appropriate.

In Drupal 8 this sort I'd thing should be far less of a problem as the focus is shifting much more towards an OO core (which of course is absolutely awesome) but for now we're stuck with workarounds for these types of situations.
> 0 votes

# Answer
Try overriding this function's output by another function where they both meet in any other hook(as you have mentioned the function is being called inside a hook).
> -2 votes

---
Tags: hooks
---


# Question
Title: How to create a render array for a location CCK field?
The situation should be common: I have a content class with one location field; in the page view of the class I show the location on map. But, at the top of the page, I want to print the address too.

In the 'manage display' of my content type, I can choose for 'map only' (formatter location\_map); which is perfect for the map, or for 'default (address only)' (formatter location\_default), which is perfect for the top of the page.

It is probably as easy as, something like, in the node.tpl.php, saying

```
// address here
$content['field_location']['#formatter']="location_default";
drupal_render($content['field_location']);

// google map here
$content['field_location']['#formatter']="location_map";
drupal_render($content['field_location']);

```

but that doesnt work. I also notice Location has a theming hook, described here

http://drupal.org/node/62486

unfortunately they forget to mention what goes in there. whatever i put in there, it doesnt pass to location.tpl.php (allthough it does pass that template in vain).

I have a workaround thats so ugly I'm not even going to post it here :-) Does anyone know how to do this properly ?

\*-pike

# Answer
Ah, ..in my node.tpl.php

```
// address here
$fvf = field_view_field('node', $node, 'field_location', array(
    'type'=>'location_default')
);
print render($fvf);

// google map here
print render($content['field_location']);

```

Great article: http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

pfew, \*-pike
> 2 votes

---
Tags: 7, location, entities, theming
---


# Question
Title: How to remove content from view once user clicks on it (or reads it) in drupal 7?
I have a view "Recent content of your interest" based on taxonomy and flag.

Current scenario:

User clicks on content from view and reads it, he comes back to same view.

What I want:

User clicks on content from view, read it, come back and the content (which he just read) is not listed i.e. removed from same view.

Any module I can use for same or any pointer to implement same functionality highly appreciated.

# Answer
> 2 votes
You can implement by altering query of view.

**history** table of your database stores the record whether any content is accessed in past or not.

You can check whether logged in user has visited this node in past or not.

function node\_last\_viewed($nid) returns the timestamp when node is viewed last. If node is not accessed then it will return 0.

So you can customize the query and put the condition to check whether node is accessed in last or not and you have to display only nodes which are not accessed in past.

See here for one more use case. Though it is not using views but it will guide you to solutions.

# Answer
> 5 votes
You can use rules and flag module.

Create a view that list related content that the user hasn't flagged.

Create a rule that flags the content when is viewed by the user.

Setup the flag so the it doesn't show up on the node view.

---
Tags: views, taxonomy-terms, users, flags, nodes
---


# Question
Title: Drupal 6 site updates are not been applied
I have a Drupal 6 site running fine, but when trying to apply updates to its modules by uploading the latest version of the module and visiting update.php the update process complete, but when I check the available updates report it still show me the old module versions marking them as outdate.

I can read and write in the DB, and I can upload files to the server so it is not a DB or file permission.

Can you explain why the updates are not being applied/seen?

# Answer
I have to put this here in case someone else has the same issue.

The problem was in my case the I was backing up the old modules folders to a folder call "old backup" in /site/all/modules/ so that in case something goes wrong I can just grap the old copy while I figure out what was wrong.

The problem was that the site module scanner was grabbing in the old modules new location and that is why I was never able to apply the updates.

I was able to tell using the comments above about checking the DB.

When I check the system table I notice this:

sites/all/modules/old backup/ctools/ctools.module

instead of this:

sites/all/modules/ctools/ctools.module

Thank you all for your ideas as they help me figure out what was wrong and I hope this can help some one else in a similar situation.
> 2 votes

# Answer
Did you clear the cache?

Are you sure you are updating the right modules? Drush for example will place modules in sites/all/modules, but if your modules are placed in profiles/profile/modules Drupal might still be reading the old modules. Drupal won't complain if you are having duplicates, only on enabling.

Can you confirm the modules are read? Check the database, are the module path correct? Is the info file of you modules showing the correct version?
> 2 votes

# Answer
As an additional precaution: are you overriding the existing module files with the new ones? If so, I'd try deleting the module to be updated first and then uncompressing the new one.
> 1 votes

---
Tags: 6, updating
---


# Question
Title: Complex SelectQuery with multiple left joins and conditions with OR
I have a view and in hook\_views\_pre\_execute() I have to add multiple left joins with conditions. Currently I'm doing this:

```
$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');
    $or = $or->condition($field->table . '.' . $field->field, '%' . $string . '%', 'LIKE');
}

$query->condition($or);

```

but it doesn't seem to work.

# Answer
> 1 votes
It seems that the problem was `$field->field`. For example if I have a field called `field_book_author` in database the `$field->table` would be `field_data_field_book_author` and the value of the field would be in `field_book_author_value`.

So the correct code is:

```
$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');

    if (property_exists($field, 'additional_fields') && (count($field->additional_fields) > 3)) {
        $field_name = $field->additional_fields[3];
    }else {
        $field_name = $field->field;
    }
    $or->condition($field->table . '.' . $field_name, '%' . $string . '%', 'LIKE');
}

$query->condition($or);

```

---
Tags: 7, views, database
---


title: PHP based node access control

text:
# Question
Title: PHP based node access control
Is there any way that I can use a custom PHP code to control the visibility (proper Drupal access) of a node?

Something similar to content access module, but instead of access control by role, I'd like to have access by PHP code so if it returns true, users can access that node, if not, the node will be access denied?

# Answer
You might be able to do that by using the HOOK\_NODE\_VIEW(). In my experience I have had great success using the ACL and content access modules as you can control the view, edit and delete function of the nodes by roles, but also a the node level you can specify what user(s) can have access and what type of access.
> 1 votes

---
Tags: 6, users
---


title: Can't add or update a taxonomy term

text:
# Question
Title: Can't add or update a taxonomy term
Something has happened on my site where I am unable to add taxonomy terms or edit existing ones.

If I go to add a taxonomy term or edit an existing one the form comes up, I made an changes (i.e. add some text in the description field) and then click save and it goes back to the Taxonomy list but nothing changed. When I go back into edit the taxonomy term the previous change is gone.

The same thing happens when I try to add a term through /admin/structure/taxonomy/name\_of\_vocabulary/add form- it saves, but then the new term doesn't show up.

Any ideas?

# Answer
> 2 votes
Solved by upgrading to the most recent version of Meta tags module.

Thank you to Patrick Kenney for pointing me in the right direction.

---
Tags: taxonomy-terms
---


# Question
Title: how to skip from add cart and directly go review in ubercart module?
I have developed a site in Drupal. I just want to go to review link directly from add cart.plz help to sort this out.

# Answer
You can skip yourdomain.com/cart , but linking to **yourdomain.com/cart/checkout**. You cannot go to yourdomain.com/cart/checkout/review though, because customer need to confirm his data.

Of course, with some heavy voodoo scripting and merging at the custom modue side, you could create unified checkout page, but that could be cumbersome task :).
> 0 votes

---
Tags: ubercart
---


# Question
Title: how to redirect users to a page after login only when a specific menu item is clicked?
I have a link "Add a Post" (url: /node/add/mypost) which is not directly accessible to users.

I want to display a menu item titled "Add a Post" so that when users click on it, user goes to login page and THEN goes to "/node/add/post"

I have tried using "logintoboggan" and "rules" modules but these redirect user to "node/add/mypost" EVERYTIME a user logs in - I also have a "log in" only link where I just want the user to come back to home page after logging in.

Question Summary: How to have redirect users to a node add form based on a menu item that they clicked on? (menu item here = separate than the "log in" link)

# Answer
You could add the link like this:

```
user/login?destination=node/add/post

```

after login they'll be sent to the add post form.
> 0 votes

---
Tags: 7, routes
---