# Question
Title: Make block appear on some pages but not others
How can I tell a block to appear on user profiles, like `/user/1`, but not on other pages where the beginning of the path is the same? So for instance, if I have a view set up at `/user/1/articles`, or `user/1/messages`, how can I tell the block to appear in the main user profile but not on the articles or messages pages?

# Answer
I believe your only option is to use a PHP snippet to set the visibility.

Under `Visibility settings` select `Pages on which this PHP code returns TRUE (experts only)` copy and paste the snippet below.

```
<?php
if (arg(0) == 'user' && !arg(2)) return TRUE;
?>

```

For this to work you would also need to enable the `PHP filter` module.

Note that it's not generally recommended to use the PHP filter, but in some cases it might be the easiest solution.
> 1 votes

# Answer
Try making it visible only on

```
user

```

and only for `authenticated user` role.
> 0 votes

---
Tags: blocks, users
---


title: Role cannot create or edit book content

text:
# Question
Title: Role cannot create or edit book content
I feel like I am missing something obvious that I just can't quite put my finger on.

As an administrator, I see "Add Content \> Book page" and "My Workbench \> Create Content \> Book page" in the admin menu, and I see tabs to create and edit drafts when viewing a book page.

My "book author" role does not see any of this though, despite seeing controls for 3 other content types just fine. The node permissions allow book authors to "Create new content" for the book page type. The 3 other content types also have "Create new content" and no edit permissions, and they all work fine.

For the 3 working content types, if I remove the "Create new content" permission, the admin options disappear from the menu and tabs aren't shown, and the menu and tabs reappear as soon as I recheck "Create new content". So it's just this Book module content type that's giving me problems.

This is a Drupal 7 site, with a few contributed modules that affect content access, such as Workbench Moderation and Organic Groups. I have also tested out some other content access modules in the past, such as Workbench Access and Domain Access. All these modules have long been disabled, however, and I have rebuilt permissions several times since. I suppose it should be noted though that I only just recently enabled the Book module, while the 3 working content types were all in use when I was experimenting with Domain Access, Workbench Access, et al, so maybe there are some lingering settings in the database?

# Answer
> 0 votes
I'm not quite sure why this started working, but all went right with the world when I added the "Book page: Edit own content" and "Book page: Edit any content" permissions for the "book author" role.

Two odd things with this though:

1. I'm sure I tried this at least once before earlier today
2. I immediately disabled both permissions again to see what would happen, and nothing did, i.e. the book author role is still able to create and edit draft Book page content... which is good, but weird

---
Tags: nodes, users
---


# Question
Title: How to reorder vertical tabs by weight in Drupal 7?
I have some vertical tabs I am trying to reorder and the dpm()'d weights are not matching the visual output. Can someone explain this or point me to the right documentation on how weights and vertical tabs work?

# Answer
> 1 votes
If you are calling the hook function through your module it can happen that other modules are calling the same hook function after your hook. This would make the changes you made overwritten by the other module.

So if you want to make sure your hook is called last, either call the function in the themes template.php file or change the weight of your module to something higher so that it gets executed last. The second option would require you to edit the system table in the database.

---
Tags: theming, forms
---


title: Asking a branching series of questions

text:
# Question
Title: Asking a branching series of questions
I want to be able to ask users a question, and, depending on their answer, go to some other question. Webforms does not handle this well, since it seems to assume that the user answers most of the questions. I'm looking for something like

What price range do you want?

* If between $100 and $200, go to question 2
* If between $200 and $300, go to question 3
* If between $300 and $400, go to question 4

And so on.

At the end, I need to be able to see all of their answers in order to perform a DB query, so their responses will have to be "accumulated" as they go. I don't strictly need to have their answers stored in the DB, but it would be nice. I'm fine with programming in a hackish special case with hardcoded targets, but a clicky-button interface would be preferable, if such a module exists.

I feel like there should be some relatively-easy way of doing this, perhaps with the Form API and fields on nodes, but I can't quite put my finger on how it would be done.

# Answer
> 0 votes
I ended up going with the Mforms module. It has the flexibility to create more complicated flows beyond surveys and quizzes. Its included example module contains enough to get started.

# Answer
> 1 votes
Look at webform conditional or update your webform to \>4.0-alpha2.

I have done a 2-way or 3-way branch on a form with a few sub-pages of questions for each branch. It's kind of a pain but its very doable.

Webform results will show you only the answers they had to complete depending on conditions and validations.

# Answer
> 1 votes
Try this module dquarks. Using this you can create surveys and quiz. Hope this helps.

# Answer
> 0 votes
You may take a look at the Field Conditional State module.

> With field conditional state module you can set #state form field attribute based on value selected in other form fields.

---
Tags: 7, forms
---


# Question
Title: List all groups where the profile owner is a member?
I need to put a block inside the profile page, that shows all the information of the **profile owner**, regardless of the logged in user. (There are some information out there in the forums about how to catch the logged in user´s information).

I need to list all groups where that user is a member of. And I can´t. I´ve tried a lot of combinations, and the last one seemed correct, why isn´t working? What am I missing?:

This is my current configuration:

**Contextual filters** (author) Usuario: Uid Provide default value (User UID from URL)

**Relationships** Content: Author (author) OG membership: OG membership from User

**Filter criteria** Content: Type (= Group)

What am I missing? Thanks for your help!!!

# Answer
You should have a view that comes with OG called "OG User groups". If you clone that view and change the contextual filters to "Content ID from URL", or change your current view to reflect the provided one you should be good.

If you don't have access to the view these values should work:

**Contextual filters**
OG membership: Entity id

**Relationships**
OG membership: Group Node from OG membership
> 1 votes

---
Tags: views, users, organic-groups
---


# Question
Title: Views managing fields with style in Drupal7
i have created a view

having three fields as image , title and body

i want to show image on left and on right hand side title and below title body .

i don't want to customize view template file. is there is any option so i will get desired results .

Thanks in advance

# Answer
> 0 votes
Exculde From display first and second field and in third field use rewrite output something like this

```
<div>
<div style='float:left'>[field_movie_image]</div>
<div style='float:left'>[title] [body] </div>
</div>

```

it is working for me. itself in a view

---
Tags: views, theming
---


# Question
Title: Show list of users based on taxonomy term (D7)
I have a taxonomy vocabulary "Department". In the user account I have a taxonomy term reference field with this vocabulary. So each user can be assigned to one or more departments. I used the module Taxonomy Meny to show the taxonomy terms in my main menu.

Now I want to show a list of users when I click on a department in the menu. Does anybody have an idea how I could do this?

Thanks.

# Answer
You're right Mohammed, I should be using views. Use a view with a filter on the department field and then create a link to the view page in my main menu. I was overthinking this way too much.
> 0 votes

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


title: Create <ul> in custom node.tpl

text:
# Question
Title: Create <ul> in custom node.tpl
I have a node with a lot of images and I want to convert this images in a `<ul>`-list. So I created a `node.tpl`-overwrite page and tried to alter my HTML, but with no result.

```
 <div class="content"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content['field_themes_body']);
    ?>
    <div class="theme_slider">
        <ul>
        <?php
          dpm($content['field_themes_images']);
          //print theme_item_list($content['field_themes_images']);
        ?>
      </ul>
    </div>
  </div>

```

It seems like the dpm of the `$content['field_themes_image']` contains a whole array with all kinds of properties... Is it possible to filter out the images path only?

I've looked at the theme\_item\_list-function, but with no luck (or I did it wrong).

# Answer
> 1 votes
The following should work for you.

```
      hide($content['field_themes_images']);
      <div class="theme_slider">
        <ul>
        <?php
          foreach ($content['field_themes_images']['#items'] as $key => $img)
          {
            print "<li>";
            print render($content['field_themes_images'][$key]);
            print "</li>";
          }
        ?>
      </ul>
    </div>
  </div>

```

---
Tags: 7, nodes, theming
---


title: How to use ddblock to create slideshow?

text:
# Question
Title: How to use ddblock to create slideshow?
I am having problem creating slideshow with DDBlock

Created a new block 'DDBlock1' from 'admin/structure/ddblock' Cannot configure Block: Selected "Input Type" as "Content Type" but under "Content Type" drop down box, only option is "None" (as shown)

I am stuck here - how do I direct DDBlock to pick images from an Image field in a content type I have??

# Answer
Have you noticed that the help text says

> Only content types enabled in the settings tab of the ddblock module will show up here

?

As far as I can tell from your question, you haven't enabled your content type, and thus that's likely your problem.
> 0 votes

---
Tags: views, 7, javascript
---


title: Organic Group Permission

text:
# Question
Title: Organic Group Permission
I am using drupal 7, how to give permissions for the anonymous user to the view the fields of created from the OG module. The values doesn't show for the anonymous user. In the people permission page, there is no option to view the field name permission. There is only a permissions of creating, editing and deleting the node. Please help me resolve this problem.

Thanks.

# Answer
It sounds like you have "Strict node access permissions" enabled.

On the OG settings page (`/admin/config/group/settings`), make sure `"Strict node access permissions"` is unchecked.

This disables the OG permissions and lets you use the standard Drupal permissions alone.
> 2 votes

---
Tags: users, organic-groups
---


title: use a custom view mode in node.tpl

text:
# Question
Title: use a custom view mode in node.tpl
With Display Suite we can make custom view modes other then Teaser to use through out the site (in views for example). This is working fine and very nice!

However, using the custom view in a .tpl file does not work (where $teaser is confirmed to work).

```
Notice: Undefined variable: custom_view_mode_one in include() (line 92 of /home/dev/drupal-7.x/sites/.../node--custom-content-type.tpl.php). =>

```

do i need to register this in template.php even though it is already registered on the page and usable everywhere else?

# Answer
> 0 votes
Though slightly different i have accomplished my goal with the following in **node.tpl**

```
if ($node->type == 'custom_content_type_name' && $view_mode == 'custom_view_mode_')

```

(*node-\>type* is optional)

What threw me off is that `print render($content)` *must* be in the *else* statement, otherwise things dont load and it looks like its not working.

# Answer
> 1 votes
`$teaser` is being passed in from `template_preprocess_node()`. DS just makes the view mode via a `hook_entity_info`; it doesn't wire it into the themeing system. You need to do something like this:

```
function MYTHEME_preprocess_node(&$variables) {
  $variables['custom_view_mode_one']
    = $variables['custom_view_mode_one'] == 'custom_view_mode_one';
}

```

You could also be smart by using a `entity_get_info('node')`, and get all of the view modes, and set similar variables.

Note that you should already have a variable called `view_mode` available in your template, too.

---
Tags: entities
---


title: Search Drupal modules by dependecies

text:
# Question
Title: Search Drupal modules by dependecies
I need some feature upon Entity Reference module, To clearing I need rendered version of entity in form instead of just entity label.

So before writing new module or hacking Entity reference, I should search for exist modules.

It will be good if I can see all modules dependent to Entity reference. Where can I find sucj list of modules?

# Answer
There appears to be a module for this Module browser but it doesn't seem to be up to date at all unfortunately.
> 1 votes

---
Tags: 7
---


# Question
Title: Views to display recent content with user pictures
I want to create a view displaying the recent content posted by users along with their respective pictures. I am able to Create the view displaying recent content but how to display the respective user picture who created the content along side the content.

# Answer
> 1 votes
Add a relation ship of the type content:author and use that relationship to add the user profile image.

Hope that helps.

EDIT : A description as per the comment

1) From RELATIONSHIPS(This would be in the advanced section on the right side) click on add. it will bring up a list of fields that you can add.

2) Add the Content: Author relation ship.

3) Now When you try to add the a field additional fields would be displayed related to the user you can select User: Picture. The relationship author should be select.

---
Tags: views, users
---


# Question
Title: Adding some new custom variables to page.tpl.php
I want to add some variables to page.tpl.php via template.php so i guess i need to use my\_theme\_preprocess\_page. But my variables does not seem to be passing through.

I am using something like this :) In template.php

```
function my_theme_preprocess_page(&$vars) {
$vars['myvar'] = "value";
}

```

and in page.tpl.php

```
print $myvar;

```

and $myvar fails; also tried defininig it with **$vars\['page'\]\['myvar'\] = "value";** and reading it back with **print ($page\['myvar'\]);** but with no luck, variable (or index) stays undefined.

I cleared cache.

Any clues why this does not work ? Thanks!

# Answer
> 0 votes
Thank you all for your effort to resolve this issue. The error was of very strange origin. Drupal cache was not cleared when doing drush cc - all!

Cache was fully cleared when I cleared it from Drupal performnce clear cache button. This is strange new issue that is part of something else.

# Answer
> 3 votes
Add the following function to the template.php file for your theme. Replace themename with the effective short name of the theme.

```
function themename_preprocess_page(&$variables) {
  $variables['contactTitle'] = t('You can leave a message using the contact form');
}

```

Clear the cache, and add this anywhere in the page.tpl.php file used by your theme.

```
print $contactTitle;

```

# Answer
> 2 votes
Drupal doesn't have code that checks if the theme is adding a new index in the array passed as reference to `hook_preprocess_page()`; every index added to that array from a preprocess/process function is then passed as PHP variable to the corresponding template file.

If what you are adding is then not passed to the template file, then the possible explanations are:

* You are prefixing the function name with something that is not the short name of the theme.
* You wrote the preprocess function for the theme that is not currently active. If the theme currently used is the Bartik theme, the preprocess function for a different theme would not be called. Keep in mind that the used theme could be different from the one you are expecting; this is what happens with administration pages, for which the used theme is the one set as administration theme in admin/appearance.

There are also modules that can set a different theme for a page implementing hook\_custom\_theme().

A possible mistake could be implementing a preprocess function for a theme when a sub-theme is actually used, or (vice versa) implementing a function for a theme when the parent theme is actually used.

### References

---
Tags: theming
---


# Question
Title: The user-profile.tpl.php file won´t be recognized in my Drupal 7 installation
I´ve created a file user-profile.tpl.php in a Drupal 7 installation. I´ve updated the site from Drupal 6. I have old core profile fields and I´ve installed the new profile2 module.

I´ve inserted that user-profile file into my theme folder and flushed cache. I want the profile to show all the core profile fields and the new profile 2 fields.

The thing is that it won´t show any field at all. It just shows the user picture.

After a lot of trying and error, I´ve tried deleting all the content inside user-profile.tpl.php file, and adding into it just "hello world". It won´t be printed out. And the profile picture is still there.

**So, how do I get the file to be recognized? Should I set something at my template.tpl.php file?**

Thanks for your help!!

Rosamunda

# Answer
> 1 votes
You could try adding your content in the user profile template preprocess function instead.

e.g, in template.php:

```
/**
 * Implements hook_preprocess_user_profile
 */
function THEMENAME_preprocess_user_profile(&$variables) {
  // Fetch relevant user account
  $account = $variables['elements']['#account'];
  // Add content to user profile render array
  $variables['user_profile'][] = array(
    '#type' => 'markup',
    '#markup' => 'Hello world'
  );
}

```

After adding a new preprocess function, clear theme registry cache, e.g at `Admin > Performance > Clear all caches`

# Answer
> 1 votes
After adding content to user profile template preprocess function,to display it on user profile page, you need to render that content. I recently had the same issue. So I created the preprocess function inside my theme's **template.php** file as suggested by **David Thomas** and created a **user-profile.tpl.php** file (just copy the user-profile.tpl.php from User module) **inside my theme's template** folder and rendered whatever content I wanted to display. In your case it should be something like:

```
print render($user_profile['content_name']);

```

Hope that works for you!

# Answer
> 1 votes
It must be possible to print anything when you have properly reckognized user-profile.tpl.php.

In my case it works out of the box. If i delete content of whole file, and just type "test" in it, page shows only "test".

**Try this**: Make sure that your user-profile.tpl.php is in **/templates** sub directory, not in root of your template folder, otherwise it won't work!

---
Tags: 7, users, theming
---


# Question
Title: Where to add custom theme function that generates HTML?
I am making a theme for Drupal 7 that includes an HTML5/CSS3 animation in the header. The animation works fine, but I want to generate the HTML for it dynamically so there is an element of randomness.

At the moment I am doing this via a pair of simple for loops in page.tpl.php but I am aware this isn't really the best place to put the code. I have spent a little while searching and most answers seem to deal with modifying variables or code that Drupal puts out, whereas this is generating some completely new HTML.

What is the "Drupal way" to handle this? Just add a custom function to template.php that I call (themename\_mycustomfunction) or do it in the preprocessor function (themename\_preprocess\_page) to add the generated HTML as a variable? Thanks

EDIT: This is the code I've currently got located at the top of my page.tpl.php. Nothing fancy, just generates some divs with the classes that the CSS3 animation will use. Where is the best place to put it though?

```
<div id="anim">
    <?php
    for ($i = 1; $i <= 10; $i++) {
        ?>
        <div class="block o<?php print rand(1,3); ?> w<?php print rand(1,6); ?> x<?php print rand(1,9); ?> start"></div>
        <?php
    }
    ?>
    <?php
    for ($i = 1; $i <= 20; $i++) {
        ?>
        <div class="block o<?php print rand(1,3); ?> w<?php print rand(1,6); ?> x<?php print rand(1,9); ?>"></div>
        <?php
    }
    ?>
</div>

```

# Answer
> 1 votes
I would add this sort of functionality to **template.php**. In **themename\_preprocess\_page** you define a variable and assign the output of a custom function in template.php, for example **\_themename\_mycustomfunction**. In page.tpl.php you check if the variable defined exists and then you print it.

# Answer
> 2 votes
Your nearly there...

If your going to do this on the theme layer then create the custom function and call it in a process function assigning to a variable that can be passed to the template.

Thats typically the "Drupal way".

**template.php**

```
function THEME_customFunction() {
   // blah blah...
}

```

**template.php**

```
function THEME_preprocess_page(&$vars) {
   // blah blah...

   $vars['animation'] = THEME_customFunction();

}

```

**page.tpl.php**

```
<?php if ($animation): ?>
<?php print $animation; ?>
<?php endif; ?>

```

---
Tags: theming
---


title: Alter Views arguments from URL

text:
# Question
Title: Alter Views arguments from URL
I'd like to alter Views arguments which is currently Term name. Is there any way to use term name slug instead of complete Term name and use this slug as views argument? If not what hook should I use to convert these parameters from URL (as taxonomy term slug) to full name Taxonomy term which can be used as views argument. I tried to use hook\_views\_query\_alter and hook\_views\_pre\_view, but it's too late for any changes.

# Answer
> 1 votes
It is a build in function in drupal views. When you add a contextual filter there would a section called more. You can put the case to lower case and check "Transform spaces to dashes in URL"

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


title: Email to image in ckeditor?

text:
# Question
Title: Email to image in ckeditor?
I'm looking for a module to convert emails links to an image in the body field to prevent spam.

The closer I found is this one but it's for drupal 6 and I needed for D7: http://drupal.org/project/email2image

Since I'm using ckeditor maybe there is plugin for this?

# Answer
You could look at

http://drupal.org/project/textimage

> Textimage adds text to image functionality using GD2 and Freetype, enabling users to create crisp images on the fly for use as theme objects, headings or limitless other possibilities.
> 0 votes

---
Tags: entities, wysiwyg
---


title: Providing Archive feature in a website

text:
# Question
Title: Providing Archive feature in a website
We are considering to migrate an exiting website to Drupal: www.rkmission-shivanahalli.org The website has simple static content which I believe is not a big deal to migrate to Drupal.

However, there is one requirement which is pretty unconventional and not many websites have it. The archives feature. What we have been doing is, since currently the website is only collection of html files, we pick the whole web folder of current edition and place it into archives folder of the website and link the new website to the index.html page of that archived folder. We also have a link to get back to the current edition from the archives section.

Please see this link for more details, the archives page of current edition: http://www.rkmission-shivanahalli.org/archives.html

One of the edition from archives page will have a link like: http://www.rkmission-shivanahalli.org/Archives/AUG\_2006/index.html.

Now I am not very sure how to achieve this using Drupal. Is there any direct way to do this? Or, any modules which does it on my behalf? Or, do I have to modify any source files etc.?

Thank you for any suggestions.

PS: This is a mirror of the question already asked in Drupal forums: http://drupal.org/node/1884930

# Answer
> 1 votes
My immediate thought is to use version control software like Git or Subversion to store your code, and use some kind of standardized process to:

1. create a branch/tag/snapshot the current code
2. deploy the tag to a new location on the web server
3. create a copy of your database
4. update the settings.php file in the deployed tag to point to the new database

Depending on your Drupal configuration and your requirements, you might also need to copy your public files folder to the new location, as this folder is usually excluded from version control. If this is the case, be sure to specify your file system paths in Drupal's admin area with relative paths, not absolute.

Finally, you'll either need to create a new virtual host in your web server's configuration each time, or come up with a catch-all virtual host definition (I did this once to spin up branch sites automatically for QA, using subdomains, server alias wildcards, and rewrite rules, e.g. branch "foo" = foo.mysite.com = /var/www/mysite/branches/foo).

You can automate much of this process with shell scripts or a tool like Capistrano.

# Answer
> 3 votes
AFAIK the features provided by the Demonstration site (Sandbox / Snapshot) module are the closest as per your requirements. It has the feature that allows you to take snapshots of your site, use it as sandbox and later (if you want) restore it back to any of the previous saved state.

> This module allows you to take snapshots of your site. Whenever you need to reset your site to the state of a saved snapshot a click of your mouse will do so.
>
> With cron enabled, a site can be automatically reset to a chosen snapshot in a definable interval.
>
> * Backup/archive of uploaded files and restore upon reset. To allow sandboxes for file related modules.
> * Journal module integration to show recent changes in snapshots.
> * Demo Reset security improvements to allow to demonstrate administrative functionalities more easily.

There is also a Demonstration Site Install Profile which allows restoration of the Demonstration Site module's database dumps during site installation.

# Answer
> 1 votes
As you've stated this is a unique feature to your site. Bear in mind with Drupal as a CMS some things like built-in Search using Drupal or "login blocks" wouldn't work on archived sites unless you look at @indrock approach of snapshots of the site. Drupal is a dynamic database-driven CMS.

If you're sticking with mostly static pages. This blog post might interest you on archiving drupal and making it accessible as HTML pages. A comment to that page mentions the Boost module. If you were clever and could write your own module in Drupal I believe. You could leverage Boost and specify your own cache directory(s) to work as the snapshots you've mentioned. You could even use a webservice or old code you have on-hand to grab the homepage image. You'd then use an Apache rewrite rule, or absolute url link to point users to the archived "cache" directories from Boost per Month/Year.

You could probably easily Cron archives as needed. I think trying to boost and a custom module actually wouldn't be a TON of code. I haven't done this -- as you've said its fairly specific functionality.

# Answer
> 0 votes
http://archive.org/web/web.php i think this helps you here you can even choose date/month/year as per your requirement

---
Tags: views, 7, migrations, nodes, version-control
---


title: Change Form submit button's title

text:
# Question
Title: Change Form submit button's title
I have a content type called "project" . I want to change the title of the submit button of the edit form. I wrote a module with the following:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project-node-form') {
     $form['actions']['submit']['#value'] = t('Publish');
  }
}

```

I enabled this module but no change of the button title.

please help...thanks.

# Answer
The form ID of the form alter function is wrong. It should have _ instead of -.

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project_node_form') {
     $form['actions']['submit']['#value'] = t('Publish');
  }
}

```
> 6 votes

---
Tags: 7, forms
---


title: Context in Drupal 7

text:
# Question
Title: Context in Drupal 7
When I install the context module in Drupal 7, it works but does not display all the options for reactions. So I created my context, but was not able to built it like I wanted because the "Block" reaction was unavailable. I had read that clearing the cache will bring this option up, so I cleared the cache, but now my contexts stopped being interactive.

Behavior happening:

* Select a condition/reaction from contexts and no options appear. I cannot input any information or select any options.

Expected behavior:

* Select a condition/reaction from contexts and options appear (if I select views, I should see various views appear. If I select path, I should be able to input a path).

What can I do to fix this? It does not appear to be on the Context bug list.

# Answer
Got the same problem just a few days ago. And it was not contained only to context. The usual drag and drop behaviour for rearranging fields for example also was not working. I only got weights. Everything using javascript was broken. It would seem something is messing up the jquery. Perhaps drupal loads a javascript that needs jquery before loading jquery?

The problem showed up after installing BeautyTips and CalendarTips that use jquery to create pop-up tips. Even after unistalling them didn't change the situation.

Then I enabled the js aggregation from the admin\>config\>development\>performance menu and everything works. Perhaps you could try the following:

* Enable/Disable the js aggregation
* Forcibly delete the contents of sites\>default\>files\>js so drupal will have to regenerate them
* Clear your caches
* Keep firebug open to the script tab and watch if you get any errors.

Good luck
> 1 votes

---
Tags: 7
---


# Question
Title: How to set the access of a menu page for all?
```
function onthisdate_menu() {
  $items = array();

  $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;
}

```

what access I need to set to let all the users see the page?, because I am looking that page as admin and I get an message "access denied"

# Answer
> 1 votes
If you set `access callback` to TRUE, all users will have access to the menu router item. That means **ALL** users.

```
 $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'access callback' => TRUE,
    'type' => MENU_SUGGESTED_ITEM,
  );

```

However, setting `'access arguments' => array('access content'),` and omitting `'access callback' => TRUE,` is the best way - check your permissions settings. You should be getting an access denied error at example.com/node page as well.

If you don't set an `access callback`, it would be `user_access` and the `access argument` will be passed to that function.

---
Tags: routes
---


# Question
Title: What is the best way to handle post data in drupal?
What function I need to implement to handle simple post data when I submit a form?

# Answer
You need to implement hook\_menu to register a path (`api/getdata` for example) and you can post data to example.com/api/getdata path, and your `page callback` function will be able to grab `$_POST` data.

Update: Alright, too many downvotes and I can't delete the answer because it was accepted (can anyone do it for me ?). Anyways, *the question I answered* was all about handling $\_POST. It just asked "how to I handle $\_POST or something" and no form was mentioned. Handling some $\_POST is not some kind of form everytime. (Like Paypal IPN handling). Yes you should use Form API for forms and a module like Services for REST/SOAP stuff.
> 1 votes

# Answer
You are doing it Wrong(TM). Both the question(!) and especially the answer. Yes, you need to implement hook\_menu but your `page_callback` is drupal\_get\_form because you never, ever work with `$_POST` directly for security reasons.
> 6 votes

---
Tags: forms
---


title: hook_node_info or node_type_save?

text:
# Question
Title: hook_node_info or node_type_save?
I've created a custom module that creates 2 content types in it's .install file (with node\_type\_save). This works fine, but now i have trouble implanting the hook\_xxxx system. As the content types are already defined there is little need hook\_node\_info to define them again in the .module file, and even if i wanted to this will not work.

Now i can get around this by using hook\_node\_xxxx but i wonder if this is the right approach. It seems a bit dodgy to use the general hooks in a module which just defined those hooks.

Here is the code:

```
<?php

/**
 * Implements hook_install().
 */
function vakantie_install() {

    $t = get_t();
    $content_types = array(
        'name1' => 'vakantie_blok',
        'name2' => 'vakantie_pagina',
    );

    $types = array(
        array(
            'type' => $content_types['name1'],
            'name' => $t('Vakantie Blok'),
            'base' => 'node_content',
            'description' => $t('Maak een <em>Vakantie Blok</em> item.'),
            'custom' => 0,
            'modified' => 1,
            'locked' => 0,
        ),
        array(
            'type' => $content_types['name2'],
            'name' => $t('Vakantie Pagina'),
            'base' => 'node_content',
            'description' => $t('Maak een <em>Vakantie Pagina</em> item.'),
            'custom' => 0,
            'modified' => 1,
            'locked' => 0,
        ),
    );

    foreach ($types as $type) {
        $type = node_type_set_defaults($type);
        node_type_save($type);
        node_add_body_field($type, $t('Inhoud'));
    }

    foreach ($content_types as $type) {
        // add persistent variables that control settings
        variable_set('additional_settings__active_tab_' . $type, 'edit-menu');
        // 0 = disabled, 1 = optional, 2 = required
        variable_set('node_preview_' . $type, 1);
        // array(0 => 'status', 1 => 'promote', 2 => 'sticky', 3 => 'revision') remove to uncheck
        variable_set('node_options_' . $type, array());
        // 1 = Display author and date information, 0 = none
        variable_set('node_submitted_' . $type, 0);
        variable_set('menu_options_' . $type, array());
        variable_set('menu_parent_' . $type, 'main-menu:0');
    }
}

/**
 * Implements hook_uninstall().
 */
function vakantie_uninstall() {

    $content_types = array(
        'name1' => 'vakantie_blok',
        'name2' => 'vakantie_pagina',
    );

    // gather all job nodes created and delete them
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type1 OR n.type = :type2';
    $result = db_query($sql, array(':type1' => $content_types['name1'], ':type2' => $content_types['name2']));
    $nids = array();
    foreach ($result as $row) {
        $nids[] = $row->nid;
    }
    node_delete_multiple($nids);

    // remove persistant variables that control settings
    foreach ($content_types as $type) {
        variable_del('additional_settings__active_tab_' . $type);
        variable_del('node_preview_' . $type);
        variable_del('node_options_' . $type);
        variable_del('node_submitted_' . $type);
        variable_del('menu_options_' . $type);
        variable_del('menu_parent_' . $type);
    }

    // delete our content type
    node_type_delete($content_types['name1']);
    node_type_delete($content_types['name2']);
}

```

Here the .module:

```
<?php

function vakantie_node_view($node, $view_mode, $langcode) {
    if($node->type == 'vakantie_blok') {

        $extra_field = 'test_extra';

        $node->content['test'] = array(
            '#markup' => $extra_field,
            '#weight' => 1,
        );

        $node->content['test2'] = array(
            '#markup' => $extra_field,
            '#weight' => -1,
        );
    }
}

```

# Answer
I would suggest doing as a Drupal module does: the Blog module. That is the correct code to use for a module that defines its own content type.

* In the installation file, the code the Blog module uses is the following.

```
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

```
* In the module file, it implements the content type hooks, which are:

Another Drupal core module that implements its own content type is the Forum module. Differently from the Blog module, the Forum module adds a field to the nodes of its content type. The code it uses to set its content type is similar, though. (See forum\_enable().)

```
  // Ensure the forum node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['forum']);

```

Notice that Drupal core modules don't remove the content type they define, when they are uninstalled; eventually, they remove any field they attached to their content type. (See forum\_uninstall().)

As side note, the string passed to `t()` contains English words, not in other languages.
> 3 votes

---
Tags: nodes
---


# Question
Title: Display values from exposed field in Views as a Dropdown
I am building an events website - so I have a taxonomy term Venue - and this, in turn, has a field Address, which is an instance of addressfield.

I need to expose the Locality field of the address to users. I have this working fine, but it's displaying as a text field, since the original field is a text field. http://journalofmusic.com/listings/test

I want the field displayed to users as a dropdown of all possible locality fields.

I have taken a look at this thread, and this specific comment: http://drupal.org/node/1549250#comment-6653514

But I can't quite get it to work. I've updated the example code to refer to taxonomy\_term, and not node, and the locality field...

Below is the code. Can anyone suggest what I'm doing wrong here?

Thanks!

```
<?php
function dd_locality_form_views_exposed_form_alter(&$form, &$form_state) {
$field_id = 'field_address'; // change for the field in question

// Only alter forms with the necessary field
if (isset($form[$field_id .'_locality'])) {

// Build a query to get all term ids having the specified field
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'taxonomy_term')
->fieldCondition($field_id, 'locality', '', '!=')
->fieldOrderBy($field_id, 'locality', 'ASC')
->execute();

// Attach the field values to the terms
$terms = $results['taxonomy_term'];
field_attach_load('taxonomy_term', $terms, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

// Add a default so the filter is optional
$options = array('' => '---');

// Buld the options array based on the query results, overwriting duplicate entries
foreach($terms as $nid => $term) {
  $value = $node->{$field_id}['und'][0]['locality'];
  $options[$value] = $value;
}

// Alter the field
$form[$field_id .'_locality']['#type'] = 'select';
$form[$field_id .'_locality']['#options'] = $options;
$form[$field_id .'_locality']['#size'] = 1;
  }
}
?>

```

# Answer
> 0 votes
There is a small mistake in the code

```
$value = $node->{$field_id}['und'][0]['locality'];

```

should be

```
$value = $term->{$field_id}['und'][0]['locality'];

```

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


title: Reordering vertical tabs

text:
# Question
Title: Reordering vertical tabs
Is it possible to reorder vertical tabs in the node edit page? There are certain buried tabs that I am constantly needing to switch to, and it would make my life much easier (and that of my users!) if I could change the order to put the frequently used tab on top.

***Note regarding similar questions***: I realize something similar has been asked, but he asked specifically about doing it by *weight*, and I'd be happy with *any* method of reordering them, in case there are other ways. And no one answered his question, which leads me to hope there is some other way to do it. If there's no way to do this at all, then I'll either delete this question--if that's the general consensus of the community--or accept the answer that it's not possible, as long as it is convincing and no one disputes it.

# Answer
Reading between the lines of the other mentioned question and its comments and answer, I've been able to pull out these useful bits of information.

1. You can do this with hook\_form\_FORM\_ID\_alter
2. You can find the correct FORM\_ID by looking at the HTML source of the form you're working with. It's given inside the tag. *Apparently* you need to replace the hyphens with underscores.
3. The code might include *something* like this:

```
function hook_form_sublanding_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['promotion_settings'] = array(
    // something goes here....
  );
}

```

The code is *very* incomplete and quite possibly incorrect. Perhaps someone will complete/correct it.
> 0 votes

---
Tags: forms
---


# Question
Title: duplicate terms added by taxonomy_term_save
Doesn't taxonomy\_term\_save() check if terms are being added in duplicate ? I have the following code -

```
function custom_create_taxonomy_term($name, $vid) {
  $term = new stdClass();
  $term->name = $name;
  $term->vid = $vid;
  taxonomy_term_save($term);
  return $term->tid;
}

```

But whenever I pass it a $name- which already exists in that vocabulary, then also a new entry is made in the database and there are 2 tids for the same term.

# Answer
> 6 votes
It's perfectly ok to have terms with the same name in the same vocabulary, the name column is not unique in the taxonomy\_term\_data table, and `taxonomy_term_save()` doesn't contain any logic to check.

This is by design as it would be very restrictive otherwise. Imagine you had a hierarchical vocab with many different levels...what happens if two terms happen to have the same name but live under different parents?

If you need your term names to be unique for whatever reason you can check if the term exists before saving it by using `taxonomy_get_term_by_name()`

# Answer
> 0 votes
In the case of the hierarchical vocab the check still could be done by having the combination of the parent-\>child combination is always unique and hence avoid the duplicates.

The top level terms would have its parents as empty and subsequently we could avoid this bug.

Check out Taxonomy dupecheck:

> Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.

---
Tags: taxonomy-terms
---


# Question
Title: Drupal 7 aggregator module with BBC persian feed
I am trying to import the BBC persian feed from http://www.bbc.co.uk/persian/index.xml using the Aggregator module in Drupal 7. For some reason, I always get the same link for the article for all the imported items. I have tried with other RSS feeds form BBC.co.uk; only the Persian one is not properly imported.

Is this a know issue? Is there a workaround? I presume it is a problem with the RSS parser in the module, and the Persian numerals, but I can't be sure.

# Answer
After you add new feed, make sure you update the items twice after removing them in the first time.

steps as follow:

* add new feed
* go to feed aggregator page `admin/config/services/aggregator`
* update items manually by clicking on `update items` for the added feed
* remove items by clicking on `remove items` for the updated feed
* then update feed again `update items`

these steps worked for me while importing BBC persian and arabic feeds
> 3 votes

---
Tags: feeds
---


title: Access denied for admin?

text:
# Question
Title: Access denied for admin?
Why when I am logged as admin I get an access denied page, the page is custom like mysite.com/test - added by the custom module:

```
function onthisdate_menu() {
  $items = array();

  $items['test2'] = array(
    'title' => 'Test route',
    'description' => 'description of test',
    'access callback' => TRUE
  );

  return $items;
}

```

Why is that happening?

# Answer
You're missing `page callback` from your menu item. From the docs:

> "page callback": The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

Since your menu item is the root item (has no parents) that's probably what's causing the access denied.

Just add a `page callback` to your menu item, implement the function to return a string or render array to display the page, clear Drupal's caches, and it should work.
> 4 votes

---
Tags: routes
---


# Question
Title: How do I add menu items within a .install file
I'm trying to build an intall profile that implements a number if features. I am running into some issues because although features allows me to require menus, it seems there is no way to also include the links (most of the link are simple aliases to add content or edit views). Is there a way to add menu items from within the install profile?

# Answer
> 5 votes
You can follow the example from the profiles/standard/standard.install file and use code like this inside your implementation of `hook_install()`:

```
// Create a Home link in the main menu.
$item = array(
  'link_title' => st('Home'),
  'link_path' => '<front>',
  'menu_name' => 'main-menu',
);
menu_link_save($item);

```

---
Tags: features, distributions, aegir
---


# Question
Title: How to render an Image Field as a URL in node.tpl.php
I have an image field called `field_body_image`

I want to render it in my tpl.php file with a custom image style. I am using the following code (from this thread) to do this:

```
<?php $view = field_view_field('node', $node, 'field_body_image', array('settings' => array('image_style' => 'thumbnail')));?>
<?php print render($view); ?>

```

However, I want to display the URL of the image. How can I do that?

This thread has a solution, but it is for user photos and so you cannot specify a custom field.

Image Url Formatter is a module that can do this, but I would rather achieve it without an extra module.

This page has some advice, but apparently it is not best practice.

# Answer
> 4 votes
You can do this by getting the path to the file.

```
<?php $file = file_load($node->field_body_image['und'][0]['fid']); ?>

```

Then render the path:

```
<?php print file_create_url($file->uri); ?>

```

I tested this and it works. In my case I had an event image in my local dev site and it rendered:

```
http://events.dev/sites/default/files/event-images/imagefield_7tgPJ7_0.jpg

```

In your tags, you did not specify Drupal 6 or 7 but my code above would be for Drupal 7.

# Answer
> -1 votes
first enable devel module, and add this to top of your tpl file:

```
<?php dpm($node); ?>

```

then clear your cache, and refresh your node. then you probably see an orange box at top of your page, click to collapse it, and start looking for your image cck field (ex. field\_products\_image), click on that to see if there is any more array beneath that or not, what you are looking for is a string named "filepath". now you have to render your image URL like this:

```
<?php print $node->field_products_image[0]['filepath'] ?>

```

let me know if it works or not.

---
Tags: media
---


# Question
Title: How can I more efficiently save nodes programatically with my custom module without cron?
I have a scraper I created that aggregates data found on various sites, feeds, and databases. So that I don't hammer the servers to death that I am connecting to I have it set to sleep 5 seconds between requests. When it finds what I need it saves it as a new node. I have program set to fire on a cron run using hook\_cron().

It's works fine but now I have added significantly to the sources I am searching through. The problem is this process could days, especially doing it in series. I have even had the case be that I get an error that cron tried to run while cron was already running.

How can I make this process go more efficiently? More quickly? And not depend on cron? Before I wrote a module for this I simply created several scripts - one script for each source - and I fired them off simultaneously in terminal windows.

How can I do this with my module? I know I could run php's exec() function. In fact this is the commanad was calling with it when I was doing it manually:

```
php myscripts/search1.php < /dev/null &
php myscripts/search2.php < /dev/null &

```

When I try this in the module I get bootstrap errors.

When I wrote the module my individual scripts simply became functions in the module. I'm happy to go back to firing off the scripts simultaneously if someone can help me understand how to do that correctly in the module. Or, if you have another suggestion on how to do this quickly and efficiently, I'm all ears. Realistically, I need to process a couple million items of content a week.

# Answer
To fix the bootstrap issue you need to change the CWD (Current Working Directory) to where index.php is located. So in your case you are one directory deep so adding this to the top of your scripts inside of "myscripts" should make them work

```
// Change the directory to the Drupal root.
chdir('..');

```

If you were 2 directories deep the code would look like this `chdir('../..');`. If the errors had to do with php notices/warnings and things of that nature I would look at scripts/drupal.sh (checkout the "define default settings" section) or running your commands/functions with Drush.

There are a couple of options to help with dealing with millions of items of content per week. My recommendation is the HTTP Parallel Request & Threading Library. It will help with downloading things in parallel and doing things in background processes. As an example Link Checker recently integrated with it http://drupal.org/node/380052. With HTTPRL, Link Checker runs \_linkchecker\_check\_links in a new process independent of cron, issue parallel http requests, and runs a callback inside of the event loop allowing work to be done locally while we wait for things to download.

The other options (That I know of) for dealing with LOTS of items are Elysia Cron and Background Process. The stock Batch API will be too slow if your looking to do millions of things per week (there are only 604,800 seconds in a week).
> 2 votes

# Answer
Maybe you can take a look to the Batch API instead of cron.

http://api.drupal.org/api/drupal/includes%21form.inc/group/batch/7

Or you can use Drush : http://drupal.org/project/drush With Drush you can organise your cron like you want, in the order you want ...
> 1 votes

---
Tags: 7, performance, cron, nodes
---


# Question
Title: Panels page or Panels node - which to use?
I have two content types for a theatre listings site:

1. Production: title, description, image gallery, video
2. Show: date, ticket cost, production (nodereference to Production)

So a single Production node that runs for 14 nights will have 14 Show nodes linked to it. Simple.

Each Production page will pull together a list of Shows (using a View), images, video and maybe some other stuff. So I think Panels would be useful for this display.

But I'm struggling to understand whether it's best to create a single Panels page for this (that maybe overrides the default display of Production content type) or turn Production into a Panels node. The layout will be the same for each Production, so maybe a single Panels page is best?

The Production node edit page has to be simple and easy to edit, so making it a Panels node might add complexity?

Essentially, this boils down to what are the main differences between Panels page and Panels node?

# Answer
> 6 votes
"Essentially, this boils down to what are the main differences between Panels page and Panels node?"

A Panel page takes over the layout of the entire page. It can override one or more full pages.

A Panel node takes over one or more node(s) layout.

# Answer
> 3 votes
Unfortunately, Terminology does not define what a page is. I have posted a documentation issue at Terminology: Page.

In the meantime, a page is the container of a node; a page can contain multiple nodes.
In Panels a panel node can contain other nodes because of its flexibility. However, most usages of Panels is in the form of a Panel Page.

If I remember correctly, a panel node can have comments and widgets assigned to it, as any node would. A panel node fits within the template file node.tpl.php, while the page fits in the page.tpl.php (which is a layer up).

# Answer
> 3 votes
The difficulty with Mini Panels, Panel Node, Panels Page, Page Manager is that you don't figure out the specific limitations or benefits until you've actually worked with one of them trying to solve your problem.

I suggest you look at Panelizer, as it seems like the most direct way to add a panel to a pre-existing content types.

A Node Panel gives you a single content type called Panel, to which you can add fields. Panelizer goes the opposite direction (add a panel to a content type), which is more logical.

---
Tags: 7, nodes, panels
---


# Question
Title: What is the difference between hidden and value types in form API?
In Drupal's Form API page mentioned both hidden and value will not display to user.

What is the difference between them?

# Answer
With the hidden form element, the HTML markup added in the form is `<input type="hidden" />` (including other HTML attributes).
With the value form element, nothing is added to the form markup.

In both the cases, there are no form elements visible to the users. The difference is that the *value* form element is simply kept in the cache Drupal uses for forms created with the form API; nothing is sent to the browser.

Generally, the *hidden* form element is used for values that are used from JavaScript code, but that must be non editable nor visible in the form.
> 10 votes

# Answer
When you define something as hidden it is actually there in the html as an of hidden type. but when you define it as value it is not rendered in the form.

Both values are passed to the form\_state the value would be there in the $form\_state\['values'\]

I am not sure what would be a use case for the same. May be a value that is internal to the form and does not need to be even a hidden input.
> 5 votes

---
Tags: 7, forms
---


title: date popup field

text:
# Question
Title: date popup field
how to implement a date field in my forms using the form API. I actually wanted a date popup field. I have use this code

```
$form['dob'] = array(
  '#type' => 'date_popup',
  '#title' => t('DOB'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-100:+0',
);

```

but it does not work..

# Answer
you would need to install the date module for date popup to work.

the following answer on stackoverflow has more details

How do I choose the "date\_popup" widget for custom date field from code?
> 8 votes

---
Tags: forms
---


title: Custom CSV Importer

text:
# Question
Title: Custom CSV Importer
I decided to write my own csv node importer since Feeds did not give me the functionality I needed. I have about 500 nodes to create each month and from that node it needs to create another node.

I have everything working right for a few nodes, however for 500 I get a 'page not found'. I want to echo out 'Node $nodeID created' so the users knows the script is working. I tried ob\_start but I can't seem to get it to keep echoing out the result.

Does anyone have a better solution?

Here is a simple snippet:

```
 $file_handle = fopen("FinalListToIMport.csv", "r");
  ob_start();

 $i = 0;
  while (!feof($file_handle) ) {

    $row = fgetcsv($file_handle, 100024);
    if($i != 0 && $row[0] != ''){
        $update_node = node_load($nid);
        $update_node->title = 'update title';
        node_save($update_node);
       echo('Node: '.$row[0].'updated');
    ob_flush();

    }
$i++;
 }

 fclose($file_handle);

```

# Answer
> 4 votes
You can use the drupal\_set\_message() to send a feedback to the user. It's the best way to do that in my opinion.

**EDITED**

In order to prevent the timeout issue you must use Drupal's Batch API.

Here goes another example: https://gist.github.com/4329270

# Answer
> 2 votes
Since this is running a long script I would suggest looking at the example module.

There is a module with in that called batch\_example

That explains how you can put a progress bar or in your case the node id as the script progress.

# Answer
> 1 votes
I did this while back just as Shameem suggested, custom code using Batching so there would not be any memory problems.

Alternatively you could try going back to Feeds and use module Feeds Tamper http://drupal.org/project/feeds\_tamper which lets you alter the data a bit on the way in.

---
Tags: 7, importing-exporting
---


# Question
Title: Occasional Drupal Error in bootstrap.inc
Every now and then our site gives out this error:

> Notice: Constant CACHE\_PERMANENT already defined in C:\Inetpub\wwwroot\includes\bootstrap.inc on line 13
>
> Notice: Constant CACHE\_TEMPORARY already defined in C:\Inetpub\wwwroot\includes\bootstrap.inc on line 18
>
> Notice: Constant WATCHDOG\_ALERT already defined in C:\Inetpub\wwwroot\includes\bootstrap.inc on line 57
>
> Notice: Constant WATCHDOG\_CRITICAL already defined in C:\Inetpub\wwwroot\includes\bootstrap.inc on line 68
>
> Notice: Constant WATCHDOG\_ERROR already defined in C:\Inetpub\wwwroot\includes\bootstrap.inc on line 79
>
> Notice: Constant WATCHDOG\_WARNING already defined in C:\Inetpub\wwwroot\includes\bootstrap.inc on line 90
>
> Notice: Constant WATCHDOG\_NOTICE already defined in C:\Inetpub\wwwroot\includes\bootst... as of 10:40:01 on 2011-07-14.

Don't know what happens that bootstap.inc get run twice? Why else would it complain about constants already being defined. Thanks for any insight.

# Answer
> 1 votes
The bootstrap.inc file is included, from index.php, using `require_once './includes/bootstrap.inc'` (Drupal 6) or `require_once DRUPAL_ROOT . '/includes/bootstrap.inc'` (Drupal 7). That one of the first instruction executed from Drupal when bootstrapping, as the bootstrap code is all contained in that file.

The errors you are seeing could be caused from a module that is using `include` or `require` to load the bootstrap.inc file, which would not be necessary, as the file is already loaded from Drupal.
Alternatively, the errors are caused from a module that defines those constants in one of its files, which is then causing those errors once it is loaded. For example, it could be a module that implements an alternative to the cache mechanism implemented from Drupal, which defines those constants with the wrong assumption that they would not be available.

# Answer
> 0 votes
I had this same error and what caused it was a file in a module I created. This file had the same name as a core Drupal file. I renamed it and the errors went away. If you can't rename it try specifying the absolute path instead of just " require 'bootstrap.php' ". Hope that helps.

---
Tags: caching
---


# Question
Title: How do I embed a view as a form field and pass the information on
I have a view that lists a number of nodes with images, I would like to take a grid view version of this and utilize it as a form. When the user clicks on an image, it will act like a selection box. Then, when the form is submitted that information will be passed on. What is the best way to do this?

# Answer
I ended up doing this with `hook_form_alter()` `and views_embed_view` you can also add html to a form this way.

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

if ($form_id == 'your_form_id') {

       $form['what do you want'] = array(
         '#type' => 'textfield',
         '#title' => t('Question'),
         '#description' => t('Here is a question ?'),
         '#default_value' => $form['#node']->something ? $form['#node']->something : 'itis',
         '#required' => FALSE,
         '#suffix' => '<div>html test here</div>',
         '#weight' => 0,
       );

       $form['contact_information'] = array(
         '#value' => "<div>some html</div>",
       );

       $form['choose_an_image'] = array(
         '#value' => views_embed_view('my_image_view', $display_id = 'default'),
         '#weight' => 0,
       );

      return $form;
   }

}

```
> 0 votes

---
Tags: views, forms
---


# Question
Title: How do I include a required context in a ctools content type plugin?
I need to include a subject type as a required context for a ctools content type plugin? How and where is context set for the ctools plugin?

# Answer
> 1 votes
You can define the required context in the plugin definition array. Use the `'required context'` key and the `ctools_context_required` class.

Here are a few lines of stripped down code you can find in the CTools Plugin Example module:

```
/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t('Simplecontext content type'),
  'description' => t('Simplecontext content type - works with a simplecontext context.'),
  'required context' => new ctools_context_required(t('Simplecontext'), 'simplecontext'),
);

```

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


# Question
Title: How to add an image upload field to a node programmatically?
I want to add an image upload field to a node programmatically when the node is being loaded.

I heard that you could use hook\_form\_alter() but I am looking for better options. Could anyone provide a solution?

# Answer
Add a CCK imagefield to the node.

If you need to show / hide it, use your form\_alter to set `['#access'] = FALSE` on the field.
> 0 votes

---
Tags: entities, 6
---


# Question
Title: How to hide group header in grid style View?
How can I hide the headers of the groups in views (Art, Society and Culture) ?

this is a grid style view of taxonomy grouped by parent term (Drupal 7)

# Answer
> 0 votes
Several options :

* hide the relevant elements with CSS.
* override the relevant template to prevent the output of the field.
* depending on the view, tick the checkbox to not display the field in the field properties.

# Answer
> 0 votes
you must go to this location: `\sites\all\modules\views\theme\views-view-grid.tpl` and delete

`<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>`

or

go to `\sites\all\modules\views\theme\views-view-grouping.tpl` and delete

`<div class="view-grouping-header"><?php print $title; ?></div>`

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


title: Drupal 7 Batch Question

text:
# Question
Title: Drupal 7 Batch Question
I'm trying to set up a batch process and from the examples I see:

```
$context['results']['processed']++;
$context['message']

```

Is there a list of these, 'buckets' somewhere?

# Answer
> 1 votes
The array keys available in `$context` are listed in Batch operations:

> * The following keys are provided:
>     + 'results' (read/write): The array of results gathered so far by the batch processing, for the current operation to append its own.
>     + 'message' (write): A text message displayed in the progress page.
> * The following keys allow for multi-step operations:
>     + 'sandbox' (read/write): An array that can be freely used to store persistent data between iterations. It is recommended to use this instead of $\_SESSION, which is unsafe if the user continues browsing in a separate window while the batch is processing.
>     + 'finished' (write): A float number between 0 and 1 informing the processing engine of the completion level for the operation.
>     1 (or no value explicitly set) means the operation is finished and the batch processing can continue to the next operation.

---
Tags: 7, batch-operations
---


# Question
Title: How to show the tabs according to the logged in user role? (Omega subtheme)
I´m using an Omega subtheme in a Drupal 7 installation. I´ve set at the theme configuration, that Drupal should show the tabs (`$tabs`).

What I want is to show the tabs only to a specific role. I try this snippet out, wich didn´t worked. **My guess is that it didn´t worked because I´ve told Drupal through the omega subtheme, to show the tabs. And the theme show them to everybody**.

If I uncheck "show tabs" variable, they won´t show up, no matter what I do at my template file.

If I uncheck the tabs but add them inside my page template file, whey won´t show up either.

I want to be able to show the tabs or not according to the logged in user role. Here´s my snippet that doesn´t worked (at my page.tpl.php file):

```
<?php
global $user;
if (!in_array('admin', array_values($user->roles))) {
print render($tabs);
  }
  else {}
?>

```

What should I do? Thanks for your help!!

# Answer
If you are using the Omega sub theme then there would be a template file for each of the regions defined by the Theme.

The content comes in the template called region--content.tpl.php

You should see the tab printed there. you can put your logic there.
> 1 votes

---
Tags: 7, users, theming, routes
---


title: radios button help

text:
# Question
Title: radios button help
I have a radio button called 'phone\_number\_y\_n'. The values are 0 = India, 1 = US, 2=UK, 3=Canada. I want to check the value (which button the user selected) and process based on that.

It seems a simple thing, but i am not able to find how can i do that check $form\_state\['values'\]\['phone\_number\_y\_n'\] is not working. I don'e see any #values option when I do the dpm of $form\_state.

Thanks for your help.

Here is the code:

```
<?php

function formalter_form_alter(&$form, &$form_state, $form_id){

  if($form_id == "form1_node_form"){

    $form['field_province'] = array (
       '#title'   => 'Provience',
       '#type'    => 'select',
       '#options' => _load_province(),
       '#ajax'    => array(
            'event'=>'change',
            'callback' =>'formalter_dropdown_city',
            'wrapper' => 'edit-field-city',
            'method' => 'replace',
            )
      );

  $options2 = array(
    0 => t('Zero'),
    1 => t('One'),
    2 => t('Two'),
    3 => t('Three'),
       );

  $form['field_city'] = array(
       '#title'   => 'City',
       '#type'   => 'select',
       '#options' => $options2,
       '#prefix' => '<div id="edit-field-city">',
       '#suffix' => '</div>',

   );

  $options3 = array(
    0 => t('India'),
    1 => t('US'),
    2 => t('UK'),
    3 => t('Canada'),
       );

    $form['field_phone_number_y_n'] = array (
       '#title'   => 'Phone number Y/N',
       '#type'    => 'radios',
       '#options' => $options3,
       '#prefix' => '<div id="edit-field-phone-number-y-n">',
       '#suffix' => '</div>',
       '#ajax'    => array(
            'event'=>'change',
            'callback' =>'formalter_phonenumber',
            'wrapper' => 'edit-field-phone-number',
            'method' => 'replace',
            )
      );

    $form['field_phone_number'] = array (
       '#title'   => 'Phone number',
       '#type'    => 'hide',
       '#value'   => 'none',
       '#prefix' => '<div id="edit-field-phone-number">',
       '#suffix' => '</div>',
      );

 }

}

function formalter_dropdown_city($form, $form_state) {

  $options2 = _load_city($form_state['values']['field_province']);
  $form['field_city'] = array(
       '#title'   => 'City',
       '#type'   => 'select',
       '#options' => $options2,
       '#prefix' => '<div id="edit-field-city">',
       '#suffix' => '</div>',

   );

  return $form['field_city'];
}

function formalter_phonenumber($form, $form_state) {

  $options3 = $form_state['values']['field_phone_number_y_n'];

  $form['field_phone_number'] = array(
       '#title'   => 'Phone number',
       '#type'    => 'textfield',
       '#value' => $options3,
       '#prefix' => '<div id="edit-field-phone-number">',
       '#suffix' => '</div>',

   );

  return $form['field_phone_number'];
}

function _load_province() {
  $province = array('- Select province -');

  $query = db_select("sandbox_province", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $province[$row->id] = $row->name;
  }

  return $province;
}

function _load_city($province_id) {
  $city = array('- Select city -');

  $query = db_select("sandbox_city", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->condition("a.province_id", $province_id);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $city[$row->id] = $row->name;
  }

  return $city;
}

```

Also, i want to display the label associated with the selected radio button instead of the value 0,1,2 or 3.

# Answer
> 1 votes
put the field\_phone\_number in an if condition as given below with (This is inside the formalter\_form\_alter function where you have placed the hidden field. that should be removed and place the below code.

```
if (!empty($form_state['values']['field_phone_number_y_n']))
{
    $options3 = $form_state['values']['field_phone_number_y_n'];

  $form['field_phone_number'] = array(
       '#title'   => 'Phone number',
       '#type'    => 'textfield',
       '#value' => $options3,
       '#prefix' => '<div id="edit-field-phone-number">',
       '#suffix' => '</div>',

   );
}

```

Now the call back should simply return the field\_phone\_number so your callback funtion would be.

```
function formalter_phonenumber($form, $form_state) {

  return $form['field_phone_number'];
}

```

# Answer
> 0 votes
If you need the value within the form you should use ajax for that.

See ajax\_example in the examples module for simple implementations similar to yours.

During submit, in form\_submit the $form\_state will have $form\_state\['values'\].

If you want the value outside, you can use variable\_get()

---
Tags: 7, forms
---


title: Live css module won't save my css

text:
# Question
Title: Live css module won't save my css
I am using the live css module, but when I try to save the css on the fly I get the error message 'The url used contains a sub-filextension which poses a security threat. Saving not allowed.' Any idea what might be causing this?

# Answer
> 1 votes
The error is generated by the following code in the module

```
  if (file_munge_filename($sanitized_url, 'css less') != $sanitized_url) {
    echo drupal_json_encode(array(
      'result' => 'failure',
      'filename' => $href,
      'msg' => 'The url used contains a sub-filextension which poses a security threat. Saving not allowed.'
    ));

```

This checks passes the sanitized url through the file\_munge\_filename function. The function checks for all the extensions in the file adds an underscore after the extension to make it secure. you can read the link for more information.

So I presume that there is some issue with the css file you are uploading. there might be more than 1 extension in the file name such as style.abc.css.

---
Tags: 7
---


# Question
Title: Contextual filter with taxonomy term that is not in the url
I'm hoping someone could please help me tame the beast that is known as contextual filters. :) I have a series of nodes that all have a specific taxonomy term assigned to them (all from the same vocab), but for my url path I do not include those:

For example:

Vocabulary name = videos

A node has terms:

```
-food
--vegetable
---carrot

```

assigned to it, but the only url that I want is:

```
site.com/videos/title-of-node

```

And then all other nodes which have terms on them will all be under the 'videos' directory:

```
site.com/videos/title-of-another-node
site.com/videos/title-of-yet-another-node

```

I created a view that has a contextual filter where I want to display only the nodes that have the carrot term. And it that works perfectly when previewed on the views page, but when loading up the actual page I get a listing of ALL the nodes under the "food" term because I have "WHEN THE FILTER VALUE IS NOT IN THE URL --\> Display all results for the specified field"

My main problem I think is that "The contextual filter values is provided by the URL." And my terms are not in the url. So somehow I need to pull the terms associated with each node.

Any help would be much appreciated!

# Answer
Instead of creating a node view create a taxonomy view.

In that provide two relationships:

1. Taxonomy term: Content with term;
2. Taxonomy term: Content using {Name of the taxonomy field in the content type}\*;
3. Add a contextual filter of the type Content : Title; Use the first relationship for the contextual filter, Make necessary changes in the more option such as change to lower case turn space to dashes etc;
4. Add the required fields from the content with the relationship set to 2);

You are good to go.

**EDIT : As per the discussion There was another need to also show the nodes under a term and its sub terms.**

1. Create a view of the type content;
2. Add the required fields;
3. Add a contextual filter of the type Content: Has taxonomy term ID (with depth) and select the depth a value as deep as the hierarchy you have in the taxonomy.

Now when you pass the term id as the input it would show all the nodes under that taxonomy term including the child nodes.

**If you wish to change the url to have the term name instead of the term ID Do the following.**

1. In view give the path as taxonomy/term/% this will override the default taxonomy path;
2. Install Pathauto Module this depends on Tokens module so have to install that as well;
3. In Configuration -\> URL aliases you have a tab called Patters;
4. Set the pattern of the "TAXONOMY TERM PATHS" to what you would like it to be. Make sure that the last value is \[term:name\] so if you want the path to be category/carrot you should give it as category/\[term:name\];
5. If you have already added the taxonomy terms then you would need to do the "BULK UPDATE" which is again a tab on the URL Alias page.

Now when you visit the page category/termname you will see all the nodes under the term including the child terms.
> 8 votes

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


title: How to theme a quiz in D7?

text:
# Question
Title: How to theme a quiz in D7?
I´m trying to theme my quizzes, but even when I did manage to theme the quiz nodetype (**node--quiz.tpl**), **that template is gone after the "take the quiz" button is clicked**.

I´ve tried theming the **multichoice-answering-form.tpl** (as my questions are all of the multichoice type), but nothing happens.

I´ve checked the quiz module and haven´t found a default template according to this need. Or maybe I´m missing something?

I´ve tried creating the template quiz-single-question-node.tpl, it seems that even when it is "taken" the content isn´t correct, because I get an undefined variable error.

This is what I´ve try into that template, and didn´t worked out:

```
print drupal_render($form);
print render($form);
print render($content);

```

Whith any of the three options I get the same undefined variable error.

Any help will be very much appreciated. Thanks!!

# Answer
> 4 votes
There are different templates that you could use to theme the quiz.

1) page--node--take.tpl.php this would take care of the basic page level template for all the nodes with the url of the form node/nid/take

2) node--quiz.tpl.php this would be used for the quiz page.

3) quiz-single-question-node.tpl as you guessed this is the one for the single page quiz node. there is one variable in that $question\_node

```
<?php print drupal_render($question_node->content['body']);?>

```

that would render the quiz form on each of the quiz node. so this could be used to add additional things to the quiz node like a footer with instruction or things like that.

4) theme\_quiz\_question\_navigation\_form function is the place were the navigation buttons are rendered so you could either over ride it in your theme or create a template file. the variable would be $form.

5) multichoice-answering-form.tpl.php this tpl contains the part of the form other than the buttons in the multichoice question type. this has got a variable called $form. you can make the required changes and then render the same in the tpl with something like `print drupal_render($form);`

Or the above can also be done using the form\_alter function with in a module or theme. the form ID to use would be `quiz_question_answering_form`

There are many other template and theme functions with in the quiz module to change the look and feel of quiz for example to change the design of the result page you have `quiz-report-form.tpl.php`

If you go through the files and functions of the quiz module you would see many other templates and theme functions.

---
Tags: 7, theming, quiz
---


title: author profile info in a content type

text:
# Question
Title: author profile info in a content type
Need to print the profile fields of author of a node in a particular content type

I am using support tickets for my home owners association website. where in users can login in and create tickets for house keeping, electrical etc. Support tickets modules provides a content type support ticket which is been used for ticket creation. I would like to add profile fields to above content type example:apartment no, contact nos of the user who creates the ticket node so that the support team looking at the ticket know the contact info.

I am presently on D7 Thanks

# Answer
Use Views module and make a content view in relation with Content authored.
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Ajax on Autocomplete does not fire again, if previously fired
I am using Drupal 6, and question is regarding autocomplete. As a part of performance, I am caching the results of AJAX calls, so that if the same values are passed, we dont have to fire ajax call again, and should get the result instantly.

Scenario I have 2 autocomplete fields, one coming from Drupal taxonomy module, for tags and the other is a custom autocomplete field added via form alter, fetching some other information from custom table.

While I was checking on the Drupal default autocomplete field for tags, I saw that the if I insert the same text, the ajax is not fired. Like I insert "I", I get some values, change it to "j", I get some other values, If I change it back to "I", NO ajax is fired. However, for my custom autocomplete field, i am able to see 3 ajax calls.

Can someone please put some light as to how drupal does it, so that even i can implement the same on our custom field as well. I am using drupal 6, but if you are aware of how it is done in Drupal 7 as well, it would be a great help.

# Answer
The basic idea behind this is to simply cache the AJAX response of an autocomplete query keyed by the query string itself. Eg.

```
q = 'I',
cache miss
cache['I'] => [ 'India', 'Indonesia', 'Italy', 'Iceland' ]
[ 'India', 'Indonesia', 'Italy', 'Iceland' ]

q = 'In'
cache miss
cache['In'] => [ 'India', 'Indonesia' ]

q = 'I'
cache hit
[ 'India', 'Indonesia', 'Italy', 'Iceland' ]

```

If you inspect `misc/autocomplete.js` in Drupal 7, you'd notice that there is a `Drupal.ACDB` (Autocomplete Database for those curious) object. What's more interesting is the `search()` method implementation in the same object. You'd notice that given a query string, first the in-memory cache object is looked up first before an AJAX request is made. This is something that you might want to emulate too.
> 2 votes

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


title: Create / publish a node via sms

text:
# Question
Title: Create / publish a node via sms
I have successfully installed sms framework module and configured with envaya gateway. I have support ticket module. I need to allow the users to create ticket (node:support ticket) via sms. Could you please guide me how to accomplished the same.

# Answer
Normally the SMS gateway will ping a URL on your site with the relevant details from the SMS, e.g appended as a GET querystring.

I've done this before with hook\_menu and a custom callback to listen for the SMS details.

```
/**
 * Implements hook_menu
 */
function MYMODULE_menu(){
  $items = array();
  $items['api/sms'] = array(
    'title' => 'SMS listener',
    'page callback' => 'mymodule_sms_incoming_process',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;

}

/**
 * SMS listener
 * Processing incoming SMS messages
 */
function mymodule_sms_incoming_process(){
  /* Do stuff with SMS parameters
   * Make sure to sanitize any $_GET vars with filter_xss etc..
   */
  if (!isset($_GET['code']) { return FALSE }
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: "Call to undefined function views_get_view()" error
What do I need to load before calling `views_get_view()`?

# Answer
I'd say you just need to have Views module enabled to have this function globally available. You enable/disable modules at `/admin/modules`.
> 3 votes

---
Tags: views
---


# Question
Title: Product Page Uploads and Automatic Updates
Right now my website has ubercart. I was wondering if there was a way to make it so when a user uploads a file with a description/price/etc that the product page would automatically update with their new upload.

I'm making a user based artist website. Where the users can upload their own art works and sell either a digital copy of their work or a physical copy (their choice ultimately), and I was wanting some help with the logistics of doing such a thing.

The website is currently running with Ubercart and all of its required addons AND the CorporateClean theme.

Any help would be very appreciated.

# Answer
> 0 votes
You probably will have to alter the 'ubercart product-content type' and add some taxonomy fields to create the categories (electronics etc.). (Not sure if ubercart has this by default.)

Then you will have to use a view to override the ubercart product page. Look into views and Contextual filters. You can for instance create a block (user-product-block) and use a contextual filter to fill this. You can choose to get the user id from url and then select all products created by that user.

Filtering by category is exactly as done on the page above.

---
Tags: entities, ubercart
---


# Question
Title: How can I create a view to display a secondary tab on a node?
Using views I can create a page with the nid as context and place a primary tab alongside the "View" and "Edit" tab on a node. How can I move it to the seconday tab on the "View" page?

e.g. What I can get

What I need

# Answer
> 1 votes
Try adding a View page with path

```
node/%/view/secondary-task

```

Make it a "Default task" or "Default menu tab" in the View menu settings.

# Answer
> 1 votes
It is not possible, as the menu structure is missing a menu item.

I have altered a default view the Views module to be visible on node/%/view/backlinks, instead of node/%/backlink; I also changed its menu type to menu tab for an existing menu. The view was not shown.

I then added the following code in my test module.

```
function code_testing_menu_alter(&$items) {
  $items['node/%node/view/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
}

function code_testing_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    $group = $implementations['code_testing'];
    unset($implementations['code_testing']);
    $implementations['code_testing'] = $group;
  }
}

```

Once I did that, the view was correctly rendered as sub-tab.

In short, showing a view as sub-tab is possible, if there is already a sub-tab. Differently, the view will not be visible.

---
Tags: views
---


# Question
Title: Overriding contributed module functionality
Every so often, I need to make a little hack to a contributed module to add a bit of needed functionality, usually something specific to the project that the module maintainers probably would not want to use.

Currently, I create a patch file for every hack, and I store all such patch files in sites/all/modules. This way, whenever I update a module, I can easily reapply my hacks and address any conflicts.

I can't help but feel like I'm doing something wrong though. Am I?

# Answer
A patch doesn't necessarily apply to a new version of a module: It is enough the patched function is moved to a different line, or the code for that function is changed, and the patch doesn't apply anymore. For the function to be moved to a different line, it is enough another function is re-written to take more lines (or less lines).

A better way to alter the behavior of a module is, for Drupal 7:

* If the module uses code for a page callback that you want to change, change the page callback with hook\_menu\_alter().
* If the module implements a theme function you want to alter, change the function associated with hook\_theme\_registry\_alter(). In alternative, if it is sufficient to change the variables the theme function gets, then you can implement the preprocess function for that theme function (e.g. `hook_preprocess_rdf_metadata()` for theme\_rdf\_metadata(), and change the variables that theme function will get.
* If the module executes an SQL query using db\_select(), and assigns a tag to the query, change the executed query with hook\_query\_alter().
* If the module implements a hook you don't want it is executed, you can implement hook\_module\_implements\_alter() to avoid it is executed.
* If the module implements an alter hook (e.g. hook\_page\_alter()), and you want to change what that hook altered, implement the same alter hook, being sure it is executed after the one implemented from that module.

In the case the function you want to alter is not a hook, then:

* Check that function is using hooks implemented from other module. For example, node\_save() invokes hook\_node\_presave(); if I would want to change the "changed" property of the node, I don't hack `node_save()`, but I rather implement `hook_node_presave()` to alter it.
* Check that function is referenced/used from a hook; in that case, you can do something for that hook, as I previously described.

If anything I said until now doesn't apply, then it is better to create a custom module, and use the code of the other module to create it. I would also try asking a feature request for the existing module, hoping the feature is implemented.
Hacking a third-party module is never a good idea, especially because automatic updates of the module (via the Update Manager, or Drush) would not anymore possible for that module.
> 12 votes

# Answer
Most modules comes with hooks to override many of the functionalities of the module and theme functions to over ride the themes. You should try and use that in most of the cases. And avoiding hacking the code it self.

If you are absolutely sure that what you want to achieve is not something that can be done with the overrides then the next option I would choose is to create a copy of the module and give it some other name and even strip down the functions that I really dont need and create a new modules out of it.

If the changes are very little then I dont see any harm in changing the code itself but have to keep track of the changes to make it work again after an upgrade which I suppose you are already doing.
> 2 votes

# Answer
Yeah, IMO you're "doing it wrong", but maybe your project requirements are just less than my average project requirements :) Put all your patches and module versions in a drush make file so you can always build out your platform with drush if something happens.

http://drupal.org/project/drush\_make

Make files are very straightforward to write once you know the syntax.
> 1 votes

---
Tags: 7, version-control
---


title: Comment count unpublished

text:
# Question
Title: Comment count unpublished
I want to display the number of unpublished comments in a template. I don't want to execute unnecessary queries on the database. Is there an already available function for this that I can use in page.tpl.php?

```
function comment_count_unpublished() {
  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE status = :status', array(
    ':status' => COMMENT_NOT_PUBLISHED,
  ))->fetchField();
  return t('Unapproved comments (@count)', array('@count' => $count));
}

```

# Answer
I don't think there's anything already in page.tpl.php but it really depends on what is happening in the preprocessor(s) of your theme. I don't know what theme you're using.

If you're worried about calling a function like comment\_count\_unpublished() multiple times in one page load why not statically cache the result with drupal\_static()?

Have you actually profiled that query and shown that it will cause problems on your site? Drupal generally runs hundreds of queries each page load so I don't think counting the unpublished comments in that table would have a noticeable impact on most sites.
> 1 votes

---
Tags: comments
---


# Question
Title: Slideshow for the homepage. Views Slideshow or another Module?
I would like to have a slideshow with pagination on my homepage. Should I use Views Slideshow or is there another Module which is flexible and will give me the ability to add a slideshow block?

# Answer
IMHO, adding a module for this is overkill. I prefer to create a view, add the jQuery Cycle plugin to my theme and apply the plugin to the view using just a few lines of javascript.
> 2 votes

# Answer
You can use this module http://drupal.org/project/views\_galleriffic ,its nothing but the support module for views . You can customize the slideshow with thumbnail,content of slideshow,prev ,next button and pagination through view fields.
> 1 votes

# Answer
I use EntityFieldQuery which is part of core and can be faster to work with and to run for many simple use cases like slideshows than Views - http://drupal.org/node/1343708

I personally love the carouFredSel slideshow - http://caroufredsel.dev7studios.com/

Edit: EntityFieldQuery is only part of core in D7
> 0 votes

---
Tags: javascript
---


title: Site search not picking up all pages

text:
# Question
Title: Site search not picking up all pages
I've only so far added 5 or so nodes to my site. I've noticed that not all nodes are coming up in the search results. What I mean is searching for their title doesn't find them :S It works for some but not others. Why would this be the case\>

# Answer
The search table is created on cron job. So the sites that are added before the cron job would be displayed. Could you try running the cron and then try to do the search.
> 0 votes

# Answer
The problem as mentioned by the other answers is that the search table is only updated incrementally on cron runs as new nodes are added.

It's possible for nodes to be added faster than your current site is configured to process them on busy sites but you won't hit this problem with just 5 nodes :)

If you tell your site to re-index the content as proposed by indrock this will make your index reach 100% *slower* as it will start over from the beginning.

Drush actually provides functionality to force the site to finish indexing the remainder of content on demand. The command is:

```
$ drush search-index

```

Personally I've found that changing your search settings to index fewer items of content far more frequently (like 10 items per cron with a search cron task every minute) is better than larger, infrequent spikes (like 500 items once a day).
> 0 votes

# Answer
Your site is probably not indexed 100%. You can re-index the site by visiting admin/config/search/settings and clicking re-index.

This will re-index your site on cron run and you will be able to search the content.
> -1 votes

---
Tags: search
---


# Question
Title: Inherit areas of parent or ancestor page
I have a website built with Drupal 7. Each page on the site can have an infinite number of child pages. Each page has "areas"; an area can be a thing such as left or right side bars that contain blocks, views or attributes/fields of the page content type (e.g., page.sponsor\_ad\_1, page.sponsor\_ad\_2).

I want the child pages inherit the areas of its closest ancestor page by default. A content editor can override it afterwards.

What's the best way to achieve this? What module does, completely or partially, what I need?

# Answer
It depends how arbitrarily flexible the layouts need to be but:

For the layout switching you could probably use Omega and Delta http://drupal.org/project/delta

Then write your own custom context condition that says "does this page have a parent with the layout X?" then use the reactions provided by Delta to switch to layout X for the closest parent.

For the defining/storing what layout is associated with each "page" you could just use the Field API. If each "page" is a node then it will be easier for you, otherwise you might have to also define a new type of Entity for your site.
> 0 votes

---
Tags: views, blocks
---


title: Footer links - menu, UL or text

text:
# Question
Title: Footer links - menu, UL or text
What is the best way to enter footer links (horizontally)? I was thinking a Menu would be best but this causes limitations around what content goes in the links (eg. cannot have images or non hyperlinked text). While looking at another drupal site I noticed that the footer links are just regular content (not even in a list) ...

What is the best way? And how would you go about deciding how to do it?

# Answer
Something you would want to consider for "menus" not created by the Core menu system is generating any links you create with the l() function http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7

This means that at the least Drupal will add the "active" class to links that take you to the current page which can be essential for theming them properly.

Generally I'd say you should create a render array (or arrays) and get drupal go generate all the markup you need from that, but it sounds like you might be a bit too new to Drupal to be doing that.

The idea of wrapping menus in a list (ul) structure is totally optional, don't feel obligated to do it just because you've seen it elsewhere. It can help if you're doing things like drop-down menus or similar but don't worry about it magically boosting your SEO or that other people know something you don't.

You probably *do* want to wrap each item in some kind of html tag to help with theming, but that could just be a span/div.

One interesting idea to consider is a single table row as it will automatically space words out for you in a way that's difficult to do with other markup - but whether this helps or hinders is entirely dependant on the design you're trying to implement.
> 0 votes

# Answer
Instead of seeing the footer as a single entity you can consider it as different blocks of which the links would be a part.

So you would have a region defined as footer and add blocks to that region. One block would be the menu and could have another for the static text and may be another one for the images. and arrange the same in the order you want.

In this way the links would be managed through the menu and the rest of the things through the respective blocks.

If you are sure that the content is going to be static through out the site then it would be better to put the same in the page.tpl file.
> 0 votes

---
Tags: navigation
---


# Question
Title: unset the path for the library used by FullCalendar
I am using FullCalendar module to display some events. I had to modify the design of the calendar and the only solution was to alter the way javascript of fullcalendar displays events and so . Now i do not want that at an update of the fullcalendar, all the changes i have made to dissapear.My question is how can i unset the path of the current fullcalendar library and set the path to my own customized library ?

# Answer
According to this issue FullCalendar should support the Libraries API module - http://drupal.org/node/980886

Comment #7 is especially relevant I believe.

This means you should be able to use Libraries http://drupal.org/project/libraries to handle getting your customized version of the library to be used instead of the bundled one.

Ie. Make sure it is named the same as the original and stick it in sites/all/libraries
> 0 votes

# Answer
When you update a module what ever changes you have done would automatically be over written. if you have just made changes to js then it would be better to add that JS to your theme rather than the module itself.

You could you the hook\_js\_alter (On Drupal 7) or jsalter (On Drupal 6) in yout theme to remove the module specific js.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Inserting html just before body of all pages (drupal 7)
I want to add some html just before the start of body of all pages. I have managed to do so by adding the html before the body tags in html.tpl.php. It works fine. But it appears in all themes. I want it to appear only for my default theme (i.e. stark). How can I do that?

# Answer
> 1 votes
You should be editing the template file with in the theme. By default stark does not have any template files. You should copy the required template file to the theme you are using and then edit the same there.

---
Tags: theming
---