# Question
Title: how to drupal_set_title for add node form D7 (form alter doesnt work)
drupal\_set\_title doesn't work in my case. well... it worked some time ago (i don't remember when it stopped working) but after installing couple (4-6) of modules it stopped working. where else i can override page-title? it really bugs when you see 'Create Add new order' instead of 'Order form'... so i can live with that but it BUGS me every time i go to that page....

```
function driver_mailer_form_alter(&$form, &$form_state, $form_id) {
global $user;
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'order') {
drupal_set_title(t('Order form'));
}

```

one more thing, if i do code like this

```
function driver_mailer_form_alter(&$form, &$form_state, $form_id) {
global $user;
drupal_set_title(t('Order form'));
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'order') {
}

```

it works but it changes page-titles to all my pages (((

and if its possible i really don't want work with .tpl files (i don't know how to yet), but if thats the only way in my case please provide sort of short tutorial.

THANKS to everyone for help!!!!!

I did try to weight my module... made a file 'driver\_mailer.install' and used this code:

```
<?php
/**
* Implements hook_install().
*/
function driver_mailer_install() {
db_update('system')
->fields(array('weight' => 100))
->condition('name', 'driver_mailer')
->execute();
}
?>

```

then i turned off my module, flush my caches, and turned my module back... nothing changed... not working.))))

# Answer
> 4 votes
finally...

in general code below works great...

```
function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'yourcontenttype') {
drupal_set_title(t('my title'));
}
}

```

BUT sometimes other modules do altering the form and title AFTER your module... that was my case :( it took me couple days to find the solution... solution:

```
function yourmodulename_preprocess_page(&$variables) {
if (!empty($variables['page']['content']['system_main']['#form_id']) && $variables['page']['content']['system_main']['#form_id'] == 'yourcontenttype_node_form'){
drupal_set_title(t('my title'));
}
}

```

to find out your form's id use this in form\_alter

```
drupal_set_message(print_r($form_id, true));

```

I hope someone will find it useful...

# Answer
> 1 votes
If the first way you code your `form_alter` doesn't work, but the second does, that suggests to me that your form has changed, because the only thing I see different is your `if` is failing. To figure this out some more, a little debugging might help out:

```
function driver_mail_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  drupal_set_message('Altering ' . $form_id);  // take this out when you figure out what $form_id you are looking for
  if ($form_id=='new_order_node_form') {       // or whatever the machine name of your node type you are looking for is plus _node_form or some such
    drupal_set_title(t('Order form'));
  }

  // whatever else here

}

```

If, however, this still doesn't work, this means (or suggests) that one of the 4 or 6 modules you added is altering the form and title AFTER your module. IF this is the case, then you'll have to weight your module so as to run after that module.

---
Tags: forms, 7
---


# Question
Title: Clearing cached CSS when updating live web page
I'm responsible for my company's webpage, and I'm having caching issues when updating it with the new CSS files. The CSS files are collected and minified as they should be, but when I update them, they should be cleared, so the page looks like it should.

How do I clear the cached CSS files in Drupal 7?

# Answer
> 3 votes
Navigate to http://mysite.com/admin/config/development/performance and click the "Clear all caches" button :)

Or if it's an option, install drush on your server and use `drush cc css-js`, it will only clear CSS/JS cache so won't slow the site down while all the caches are rebuilt.

# Answer
> 1 votes
If you use drush then you can use the command `drush cc css-js`

# Answer
> 1 votes
You are confusing "client-side cache" with "server-side cache". Your problem is generated by clients caching the css of your site. How does it work? When the browser requests the css file and it finds out it already has one *with the same name* in the cache associated with your domain, it doesn't download it again but keeps using the one it has for improved performance. So, even if you modify your css but you give it the same name, the client browser won't know the difference and it keeps using the old one \[unless the clients hits F5 or Ctrl+F5 in most browsers, effectively ignoring the cache\]. It's not a matter of flushing Drupal (server-side) cache. They are totally unrelated.

You may want to check this module: http://drupal.org/project/advagg

---
Tags: theming, caching
---


title: How can I hide titles with render()?

text:
# Question
Title: How can I hide titles with render()?
I'm using the Devel module, and the following snippet of code to insert its links into my theme.

```
<?php echo render($page['devel']); ?>

```

The result is a h2 element with the **Development** title in it, and then followed by the links as expected.

I want to hide the title, is it possible at all?

---

This is what I ended up doing.

```
<ul id="devel-menu">
    <?php if(array_key_exists('menu_devel', $page['devel'])):?>
        <?php foreach($page['devel']['menu_devel'] as $link):?>
            <?php if(is_array($link) && array_key_exists('#title', $link)):?>
                <li><a href="<?php echo $link['#href'];?>"><?php echo $link['#title'];?></a></li>
            <?php endif;?>
        <?php endforeach;?>
    <?php endif;?>
</ul>

```

Does this seem acceptable, or is there a preferred way to do this in Drupal?

# Answer
This is what I ended up doing, and it works 100%:

```
<ul id="devel-menu">
    <?php if(array_key_exists('menu_devel', $page['devel'])):?>
        <?php foreach($page['devel']['menu_devel'] as $link):?>
            <?php if(is_array($link) && array_key_exists('#title', $link)):?>
                <li><a href="<?php echo $link['#href'];?>"><?php echo $link['#title'];?></a></li>
            <?php endif;?>
        <?php endforeach;?>
    <?php endif;?>
</ul>

```
> 0 votes

---
Tags: theming
---


# Question
Title: How do I show in the home page the facets shown in the product page?
I'm working on the http://drupal.org/project/commerce\_kickstart distribution.

You can see that the products pages shows the search facets: http://demo.commerceguys.com/ck/products

How do I do to show these facets in the First Sidebar of the front page?

If this can't be done, then I think theres a main part missing in this distribution.

Imho the facets search in the products page are great but users are very used to see a main navigation in the left side of the home page, like: http://www.amazon.com/ , http://store.apple.com/us

How can I get this feature? Maybe there is module for this?

I've found this one http://drupal.org/project/commerce\_catalog but it seems to be the placeholder for a project...

# Answer
Facets are built inside blocks. Just go to the `admin/structure/block` and search for *Facet API*, click `configure` on the Facet you would like to display on the front page, scroll to the end of the page and you will see a section *Visibility options \> Pages* and on the right a selection named *Show this block under the following pages*.

You just have to add the pages where you want the selected Facet API block to appear. For instance if you type `collection/*`, the Facet will appear under every collection for the user to filter.
> 0 votes

---
Tags: commerce
---


# Question
Title: Is it possible to get last modified date for certain field?
Is it perhaps possible to get date and time of last modification of certain field?

Just like in table "Node" you have "created" and "modified" dates, but what about fields of certain content type?

I would like to know when certain field was last modified.

thanks!

# Answer
I took a quick look at the field\_data\_xxx and field\_revision\_xxx tables and there is no time stamp field, which means you wont be able to get the last modified dates for fields.

You can probably use Field Attach API to add time entries to a custom table which will contain field\_key, entity id, bundle id and time-stamp columns.
> 1 votes

---
Tags: entities, nodes
---


title: How to hide empty region in Omega

text:
# Question
Title: How to hide empty region in Omega
It seems that by default all regions are rendered in Omega theme because of the Debug blocks.

```
<aside class="grid-3 region region-sidebar-first" id="region-sidebar-first">
  <div class="region-inner region-sidebar-first-inner">
    <div class="alpha-debug-block"><h2>Sidebar First</h2><p>This is a debugging block</p>
    </div>
  </div>
</aside>

```

Is there a way to have an option to debug blocks and hide empty blocks at the same time?

# Answer
> 2 votes
Go to `admin/appearance/settings/your_subtheme_name`. Check attached image. You can set rights on who is or isn't allowed to see debugging stuff.

Uncheck debugging options will hide empty blocks...

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


title: Create a slideshow

text:
# Question
Title: Create a slideshow
I want to create a slideshow in my site, as in the middle bottom of the page at Blottr.com.

I created the gallery with the Views Slideshow module, but my problem is that I don't know how create a slide form video.
Each of my node has one image, but some nodes have am image with a video. I want to show the video, when there is a video, and an image when no video is present.

# Answer
If you can get the slideshow working yourself, it should be pretty simple to get where you want.

All you really need to do is try to display both the video and the image, then in a template\_preprocess function for the view, remove either the video or the image field so you only get the one you want.

Alternative you could use js/css to hide unwanted elements.
> 2 votes

# Answer
You can use global php custom field in view and can manage images/videos using php code.
> 0 votes

---
Tags: views
---


# Question
Title: My views slideshow doesn't work when the display is called from page.tpl.php
I am working on Drupal 6. I have a view with a display block. My view contains an animation of 6 images with slideshow as Style.

If I put the block in the content the view works fine, the images changes. However, when I call the same block from template the images not change, I can see only one image. What is my error?

my code is:

```
<?php
$block = module_invoke('views', 'block', 'view', 'images_home-block_1');
print $block['content'];
?>

```

Also, I tried this code:

```
<?php
print views_embed_view('images_home', $display_id = 'block_1');
?>

```

Thanks in advance.

# Answer
> 1 votes
try your views block inside a theme region.

# Answer
> 1 votes
you can try views\_embed\_view to call a views block programatically.

views\_embed\_view

```
<?php
print views_embed_view($view_name, $display_id, $argument); // with single argument
print views_embed_view($view_name, $display_id, array($arg1,$arg2,$arg3)); // with multiple arguments
?>

```

# Answer
> 1 votes
Define variables on template.php

```
<?php
  function bluemarine_preprocess_page(&$variables) {
      $variables['slideshow'] = views_embed_view('images_home', $display_id = 'block_1');
  }
?>

```

Now you can print this variables on page.tpl

```
<?php

     print  $slideshow;

?>

```

---
Tags: 6, views
---


# Question
Title: theme ALL form elements in a tpl through hook_preprocess_HOOK
Trying to theme a form into all the pieces available, passed my $form and $vars through hook\_preprocess\_HOOK but in my tpl i would like the exact render() representation of the fields and variables and the form itself like:

```
print $form_tag.
      $form_input1.
      $form_input2.
      $theme_var1.
      $form_closure; <!-- build_id,token_id -->
 ?>

```

Where there are declared in the preprosess\_HOOK as

```
$form = $variables['form'];
$variables['form_tag'] = render($form);
$variables['form_input1'] = render($form['input1']);
$variables['closure'] = drupal_render_children($form);
...

```

Is it possible to have all this variables of produced HTML in my tpl? like form start tag and closure and render correctly all the inner fields? Thank you

# Answer
> 0 votes
Well the answer is simple , i returned the content using a theme function e.g.

```
return theme('mytheme',$form)

```

Entering

```
$form['#theme']

```

in the form array and

```
'render element' => form

```

in my hook\_theme solved the problem

# Answer
> 0 votes
I am not sure if this is what you are trying to do. But from the question I feel that you just want to re arrange the form in an order of your choice.

The best place to do that is with in a hook\_form\_alter function. Rather than the preprocess\_HOOK.

Every form element has a property called **#weight** This could be used to arrange the forms in order the one with higher weight would go down.

---
Tags: forms, theming
---


# Question
Title: A quick way to load images from a list of urls
With media file selector widget it's possible to add images right from the web, without prior downloading them to the desktop.

But it quickly get's rather tedious if you have a list of image urls.

For adding multiple images from local drive there is a wonderful plupload module. But what's about convenient loading of remote files?

# Answer
Haven't tried it, but I would use the Feeds module with a csv import of the urls to the files.

You may also need http://drupal.org/project/media\_feeds. I think this video shows how to do this http://ia600704.us.archive.org/35/items/WorkingWithMediaInD7/usingmedia.mp4
> 0 votes

---
Tags: 7, media, files
---


# Question
Title: Media player for Drupal 7 that can play remote http-accessible files
I'm looking for a simple module for Drupal 7 to be able to have an embedded player that can play files that are stored on a different server and that is accessible via this URL:

http://\[servername\]/WebPlay/MCWS/v1/File/GetFile?File=\[FileID\]

(where \[servername\] is not a drupal site)

I think that file formats may vary, but should be the common ones (mkv, avi or flv containers).

Ideally the player should be able to play remote audio and locally (i.e. inside drupal) stored audio\video as well.

Note that the URL to be played (the one above) is stored in Drupal in a Token Field, but if needed by the player I can try and store it in a different field type.

Can anyone help me? None of the players I can find on drupal.org for D7 have documentation on how to do what I need and to me is not even clear if those players can do it (let alone how).

I tried the MediaElement + Link combo (putting the URL in the link field), but there's an issue with query parametesr in URLs being stripped, so it's not working. The say the issue is fixed, but I tested it with MediaElement latest version (7.x-1.2) and it's still there.

# Answer
> 2 votes
If this were me; I'd be using a media-compatible media player (such as MediaElement with the 2.x branch of Media) and using remote stream wrapper to allow me to place the remote URL into the media field: https://drupal.org/project/remote\_stream\_wrapper

This should let you use local media **or** remote media that the media player can play, and will keep things tidy for you to manage.

/Robin

# Answer
> 0 votes
I could be wrong but I believe the MediaFront module can do this.

Here is a quote about it (from the module's project page):

> ... is a front end media solution for Drupal. It employs an innovative and intuitive administration interface that allows the website administrator to completely customize the front end media experience for their users without writing any code. In addition, this module provides an interface to which 3rd party media players can integrate and utilize settings presets to display rich media.

---
Tags: 7, media
---


# Question
Title: Listing top level terms in views including those without children
My vocabulary looks like this

Level 1a

* Child a
* Child b
* Child c

Level 1b

* Child a
* Child b
* Child c

Level 1c

Level 1d

* Child a
* Child b
* Child c

Level 1e

I have managed to display parents and children terms using Taxonomy term: Parent term and filter on (Parent) Taxonomy term: Parent term (not empty). But terms without children on the same level with "parent" are not displayed.

To get the children I used filter “(Parent) Taxonomy term: Parent term (not empty)”. If I set the same filter to “is empty”, I get all level 1 terms including those terms without children just like I want it. So right now it seems like an either-or situation. I can only get the top terms or the children terms but not both.

How do I get the top level terms including those without children and corresponding child terms for those with children?

# Answer
If you add a filter to parent term = "empty (NULL)" it will display all terms that have no parent above them.

For more detailed steps, try this blog post I wrote: http://fdiv.net/2012/08/11/taxonomy-views-browser-arbitrary-depth
> 1 votes

# Answer
The case seems to be old, but just in case someone bumps into it searching for help. Just try Views Tree module, which provides a display plugin (next to grid, table, list, etc.). You'll be able to show the taxonomy exactly as asked here.
> 0 votes

# Answer
Taxonomy Menu Module can help you with this.
> -1 votes

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


# Question
Title: Having trouble seeing YouTube video in Drupal 7 using Media and Media YouTube
I'm having trouble seeing YouTube video in Drupal 7 using Media and Media YouTube.

I've followed this tutorial but I never seem to get a video to show up on my page. http://www.cleverlogic.net/tutorials/drupal-7-video-setup-using-media-and-media-youtube-module

Another thing I've noticed is that when I add a video to some content type, I never see the video's thumbnail.

No errors seem to get displayed.

I'm using Drupal 7, Media 7.x-1.0-rc2 Media YouTube 7.x-1.0-alpha5

Thanks for your help.

# Answer
For future reference, the video\_embed\_field module now works well for youtube and vimeo videos.
> 3 votes

# Answer
Go to admin/structure/file-types/manage/video/file-display and make sure the youtube displays are enabled for the correct viewmode. You may need to create a new viewmode with Display Suite module or entity view mode module.

Then go to your content type at /admin/structure/types/manage/article/display and set the field to "rendered entity" and choose the correct viewmode.

Hope that helps
> 3 votes

---
Tags: media
---


title: Splitting up the .module file

text:
# Question
Title: Splitting up the .module file
I wrote my first module which happens to be in Drupal 7. The module uses hook\_menu to correlate URLs with three custom-coded, page call backs. These callback functions that construct the custom html are currently inside the .module file.

The file is getting a little long and I would like to put the three custom-coded page call backs into another file. My first attempt did not work this morning, I'm not sure what I did wrong...

1) Added this line to the .info file:

```
files[] = my_module.pages.inc

```

2) Placed the callbacks into my\_module.pages.inc

What is wrong or missing in this approach?

# Answer
> 6 votes
You can enter a `file` parameter in the `hook_menu` function and the file will be included before calling the `page callback` function.

```
<?php
function my_module_menu() {
  $items = array();
  $items['my/custom/path'] = array(
    'title' => 'My title',
    'page callback' => 'my_function',
    ...
    'file' => 'my_module.pages.inc',
  );
  return $items;
}

```

Now, you can place your `my_function` in the my\_module.pages.inc file. You can place submit and validate handlers (forms) in this page as well.

```
files[] = my_module.pages.inc

```

will not work. It's to autoload classes. A good example would be Views file includes.

# Answer
> 4 votes
hook\_menu() already provides a method to put page callbacks in other files. Take a look at the `file` parameter

> A file that will be included before the page callback is called; this allows page callback functions to be in separate files. The file should be relative to the implementing module's directory unless otherwise specified by the "file path" option. Does not apply to other callbacks (only page callback).

---
Tags: 7, routes, .info
---


# Question
Title: Display Signup info in custom node template
I seek help on how to display the signup's module info in a custom node template.

I have created a node template for a specific content type, but by looking the variables inside `$content` I cannot seem to find something useful. There are several signup variables but not one "central" that can print the whole signup info. Plus the signup variables change whether the signups for the specific event are closed or open. I was hoping to be able to use something like `print render($content['signup'])` but that doesn't seem possible.

I have already asked help on the module's queue but without any luck. I have found several similar problems but some of the are really old versions and others refer on views integration.

Reference:

I have searched a lot but I am still unaware how I can include the signup info into my node template. With so many people usually templating their nodes I am weird how the solution to this problem is not available.

I would appreciate any help to the right direction. Is there anything I can test out?

# Answer
You can always built your own module and implement a hook\_node\_view() and put this form into the node content like:

```
function YOURMODULE_node_view($node, $view_mode, $langcode) {
 $node->content['signup_form'] = array(
  '#item'     => 'item',
  '#markup' => render(drupal_get_form('this forms ID')),
  '#theme' => 'my_signup_form_theme' //optional
 );
}

```

And to get even more configurable and cool-looking you could insert this new piece of content to the "Display fields" drag and drop form of the respective content type with

```
 hook_extra_fields()

```

like:

```
function YOURMODULE_field_extra_fields() {
    $extra['node']['node-TYPE']['display'] = array(
         'signup_form' => array(
            'label' => t('SignUp form'),
            'description' => t('SignUp form imported to Node Content'),
            'weight' => 10,
         ),
}

```

And now you have

```
$node->content['signup_form']

```

in your tpl
> 1 votes

# Answer
I'm not used to the signup module but AFAIK you can also achieve this goal with the flag module \+ Rules for authenticated users. As you can see here the Subscribe button on d.o issue queue was made using this approach.

Here is an issue that may help you.

There is also a sandbox (Flag Signup) that already implements signup using Flags

For anonymous users I think you can do this using Webform Block so you will be able to insert the form on node templates and maybe using tokens or with a little work using hook\_form\_alter you can auto fill some fields with the node information. Later you can use the Webform Rules module to catch webform submissions.

Sorry if I misunderstood your question, but I think it should work.
> 0 votes

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


# Question
Title: How to export / feature the "picture guidelines" field
I have some legal mentions to put under the file upload form of user account.

I would like to put them a feature some elements about user configuration, but I'm not able to find which variable (i.e. Strongarm or anything else) is mapped to field "Picture guidelines" (available in Home » Administration » Configuration » People).

Could someone give me a hint, or is it even possible ?

# Answer
Use Strongarm to export the variable called `user_picture_guidelines`.
> 1 votes

---
Tags: 7, users, features
---


# Question
Title: Progress of a user on completion of a book
Is there a way to show the progress of a user on navigation through a book?

The best solution will show % of pages that user opened/completed in current book.

# Answer
My approach here would be flagging all the pages of the book and show a overview of total pages / flagged pages.
> 0 votes

---
Tags: 7, nodes
---


title: how to gzip compress js/css in drupal 7

text:
# Question
Title: how to gzip compress js/css in drupal 7
My site will run on D7. but it will too slow. i want to compress (gzip) js and css. I have check my site on https://developers.google.com/speed/pagespeed/insights and it will told me for compression of js can css files.

# Answer
The easiest way is to go to Configuration \> Development \> Performance (`admin/config/development/performance`), and enable:

* Cache pages for anonymous users
* Cache blocks

And also:

* Compress cached pages
* Aggregate and compress CSS files
* Aggregate JavaScript files

For websites with mostly anonymous (not logged-in) visitors, this is often sufficient. Note that if you enable compression in Drupal, you should not enable page compression on the web server level (Apache) as well.
> 7 votes

# Answer
If you are running into a bit performance problem, the following two Q/A are worth to read:
> 0 votes

---
Tags: 7, performance
---


# Question
Title: How to apply spam filter into signatures?
The spam module, does not seem to examine forum signatures against custom spam filters. Spammers have figured this out and just pour their junk links into their signatures. I am wondering how can I fix this loophole.

# Answer
Presumably the content that passes the spam module filter is posted by bots. In that case, using one of the following modules (maybe in addition to the Spam module) may help (by letting the bots fill in hidden forms):
> 1 votes

---
Tags: advertising
---


# Question
Title: How do I save a managed_file to a user profile in a hook_submit
I'm trying to save a file that the user has uploaded using my form.

My form:

```
$form['fifth']['field_cv'] = array(
        '#title' => t('CV'),
        '#type' => 'managed_file',
        '#size' => 19,
        '#upload_location' => 'public://',
    );

```

My validator using hook\_validate:

```
$file = file_load($form_state['values']['fifth']['field_cv']);
// Change status to permanent.
if($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    file_usage_add($file, 'popover', 'document', $file->fid);
}
else {
    form_set_error('CV', t('Er is geen cv geüpload'));
}

```

So now in hook\_submit how do I add this to the user? Do I need to create an extra database field for this? And should I save only the $fid ( file id ) in this field?

OR

Is there a better way so drupal takes care of this and also revisions of this field are saved?

building this in D7

# Answer
> 0 votes
I'm not sure how your collecting this CV (apart of registration process, on your own custom page, apart of the user profile page... whatever).

I would add a field to User Accounts at `/admin/config/people/accounts/fields`, or maybe install the Profile2 module for D7 if you have alot of types of Users.

After you call `file_save($file)` if you use the Devel module you'll see that `$file` should have a new value `fid` so you can then load a user account (or Profile2 profile) and give the CV `$file->fid` as the File field value.

---
Tags: users, forms
---


# Question
Title: Trouble setting up a search for a single field
I am trying to set up a search that will only search a single field of a single content type. I am currently using search api with database search server module. I set up the search to index only this one field and a bundle filter that only returns results from the specified content type. The problem I am running into is the results.

If I set the field type to integer (it is a zip code I am searching through), it returns every search result regardless of if it contains the integer or not. If I set it to fulltext, it doesn't return anything regardless if i type an exact match to one of the fields it is indexing.

Am I setting this up right? Is there a better way to do this?

# Answer
> 1 votes
You can do this with Views.

1. Install Views.
2. Go to Structure\>Views then `+ Add new view`.
3. Set `Show [content] of type [Your Content type here]` (also tick Create a page) then Continue & edit button.
4. Under FORMAT select Show: Fields. Then under FIELDS click Add button and add the fields you want to show in the result. Then click Add button next to FILTER CRITERIA and add your zip-code field. On the settings screen of that field tick "Expose this filter to visitors, to allow them to change it".

---
Tags: 7, search
---


# Question
Title: Next/Previous button for nodes within a book
I want to have Next and Back buttons for nodes within a book.

What is the easiest way to achieve this?

# Answer
> 1 votes
ok, this can be achieved by overriding of modules\books\book-navigation.tpl file. Copy this file to your Theme and change following:

```
 <?php if ($has_links): ?>
    <div class="page-links clearfix">
      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('‹ ') . $prev_title; ?></a>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?></a>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print $next_title . t(' ›'); ?></a>
      <?php endif; ?>
    </div>
    <?php endif; ?>

```

to:

```
<?php if ($has_links): ?>
    <div class="page-links clearfix">
      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('Back') ?></a>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?></a>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print t('Next'); ?></a>
      <?php endif; ?>
    </div>
    <?php endif; ?>

```

# Answer
> -1 votes
You could try one of the following modules: http://drupal.org/project/prev\_next or http://drupal.org/project/custom\_pagers. We've been using the Prev/Next module for a while in a project.

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


# Question
Title: Auto-add today's date and time to new Entity title upon creation?
I'd like to be able to auto-add today's date/time to the title of a particular Entity type when a new entity of that type is created. For instance, if I create an entity called "My New Entity", I'd like the title of that entity to actually be saved as "My Entity - 020513 - 103501" (assuming the entity is created on February 5, 2013, at 10:35:01 am).

Is this possible? If so, how can it be accomplished on a Drupal 7 website?

Thanks!

# Answer
> 2 votes
**Option #1**

For Drupal 7 you're looking at the Automatic Entity Label module if you're after a particular entity.

> "Automatic Entity Label" is a small and efficient module that allows hiding of entity label fields. To prevent empty labels it can be configured to generate the label automatically by a given pattern.

**Possible option #2**

Another option is available if your Entity has actions exposed to Rules. Simple create a rul that reacts on entity creation, and set some conditions as per usual. Then, in the actions do the following:

1) Add an action for *Set data value*

2) Find your entity (node for example) and look for `:title` under data selector (e.g. `node:title`)

3) Click continue

4) On the next page, set the data value to be whatever you need with tokens (so your example *could* be something like as `[node:title] - [site:current-date]`)

# Answer
> 0 votes
With Automatic Nodetitles you can use **PhP** and node tokens to modify your node title.

If you need help for the php to use to render your title as My Entity - 020513 - 103501, don't hesitate to ask in a comment.

---
Tags: datetime, entities
---


# Question
Title: How do i use Webform API to submit my Custom Module form?
OK kinda noob-ish question but im unfamiliar with the programing side of Drupal... Im currently building a Form from scratch in drupal 7 (custom module since im using Form\_Panel to arrange my form fields) and i would like to implement the webform API into my code as the submit handler.(This way i can hopefully use webform UI to deal with submissions and viewing results at least) Currently i have all the form fields and a submit button but not much else...

```
function my_module_menu() {
$items = array();
$items['my_module/form'] = array(
'title' => t('Subscription'),
'page callback' => 'my_module_form',
'access arguments' => array('access content'),
'description' => t('Subscription'),
'type' => MENU_CALLBACK,
);
return $items;
//some random fields from form API after
///////////////////////////////////////////////////
////////////////// Submit button
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Submit',
 '#submit' => array('my_module_my_form_submit'),
);
return $form;
}
function my_module_my_form_submit($edit,$form, $form_state) {
drupal_set_message('Submission recieved.');
}

```

And thats it.It shows perfectly on site and submit refreshes the page.. What i need to know is which function and methods should i use to get webform or drupal period to save my values(create a db table first?) and display them at the necessary time through whatever links on the site.

# Answer
You want to use hook\_schema() in your `module.install` file to make a database table to store your values. A small stupid logging schema I wrote is as follows:

```
function idprocessing_schema() {
  $schema['idprocessing_log'] = array(
    'description' => 'webextract process logging',
    'fields' => array(
      'id' => array(
        'description' => 'id of entry',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'created' => array(
        'description' => 'The Unix timestamp when the entry was made.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'msg' => array(
        'description' => 'whats going on in the processing',
        'type' => 'text',
        'size' => 'medium',
        'not null' => FALSE,
      ),
      'num_students' => array(
        'description' => 'number of students from xpath query',
        'type' => 'int',
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

```

You then insert into the table as needed with say `db_insert()` a Database API function of drupal.

```
  db_insert('idprocessing_log')
    ->fields(array(
      'msg' => $msg,
      'num_students' => $cnt,
      'created' => REQUEST_TIME,
    ))
    ->execute();

```

You would want to insert `$form_state['values']` by the way in your `my_module_my_form_submit` function.
> 0 votes

---
Tags: forms
---


title: Migrating content from older custom CMS

text:
# Question
Title: Migrating content from older custom CMS
## Initial Question

Given an older CMS that kept data in a mysql database, how could we move this into a new D7 install?

It has a mysql database with a content table containing `Title` and `Body` (with HTML content) columns, could I do an import of this into Drupal and fill in the gaps as needed? I'm okay to rebuild menus and tie up other loose ends, but I'm fearing hours of cutting and pasting putting.

## Follow Up and Outcome

:\** After considering all the great advice below, I opened the older database in mysql Query Browser, executed a query on the profiles table to give me a CSV file with the following headers...

* FirstName
* MiddleName
* LastName
* Address1
* Address2
* phone
* Email
* title
* cvFilePublic
* pageContent
* lastUpdateDate
* pageName
* pageURI
* pageID

Then I created a Feed Importer with the following mapping:

# Answer
> 5 votes
The most quick and painless way would be to dump the old content from SQL to a CSV and import using Feeds - this can be done using a SQL program and point-and-click through Drupal. If this is a one-time thing, you should be fine with this. Feeds has mapping for most field types.

If you need to fully integrate, or do a more complex migration (import to field collections, for example, or do something other than create nodes) you can use migrate and directly query the other db then map the fields. This seems like overkill if you're just migrating `title` and `body` fields though. Again, I would use Feeds for something simple like this.

# Answer
> 5 votes
If you know any php I recommend the Migrate module to easily write a `SELECT title, body FROM old_content` and map them to Title and Body fields of a Drupal Page type. You would do this with a Migration class. See documentation on the project page.

You could also try the Feeds project.

There are modules for Migrate to migrate from Wordpress or older Drupal sites. You could use that as example migrations to move content, menus, etc into a new drupal site.

I've migrated pages, and custom Joomla content for courses and instructor content into Drupal content types .... but every migration use-case is always unique; I'm just recommending tools I've used.

# Answer
> 1 votes
One option, though a decent amount of work, is to write a custom import script.

Typically, when I do this I will take the default index.php, copy it to something like import.php, and edit it to remove everything below the bootstrap code.

Then, I add in a loop to query the remote database, build up a node object from the results, and then do a `node_save()`. There are a few ways to build up node objects from scratch. A search will turn them up. Then I will browse to my import script and watch it run. Once the import is done, I will delete the script from the server.

This glosses over a fair number of details. The main advantage of this over Migrate or Feeds, is that it allows you to have more complex logic for how you handle the import, and more control over any data massaging. This is only an advantage, though, if you need these.

---
Tags: feeds, migrations, importing-exporting, nodes
---


# Question
Title: Conditional addition of css - hook_init?
I need to conditionally add css to a page based on the page content / URL. In the past (D6 and down) I was always advised against using hook\_init() mostly because of it's weird load order in the Drupal bootstrap process. It was not uncommon to see the hook fire multiple times on a each page load - this still might be the case.

Looking at the D7 docs for hook\_init() the following code example is provided:

```
function hook_init() {
  // Since this file should only be loaded on the front page, it cannot be
  // declared in the info file.
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }
}

```

The example implies that conditional addition of css makes sense while:

> *To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.*

using a modules .info for site wide css additions.

**Questions**:

* What are the options in adding css via drupal\_add\_css conditionally besides hook\_init?
* Has anyone had luck using the theme hook -\> hook\_html\_head\_alter():

THEME\_NAME\_html\_head\_alter(&$head\_elements) {

```
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }

```

}
* or use the theme engine for the theme hook:

phptemplate\_html\_head\_alter(&$head\_elements)

# Answer
> 3 votes
If that CSS is in your module, then the module should really be implementing the hook.

I don't think you can do anything with CSS and JS in a `hook_html_head_alter()`; that is really to mess with the render array before it is turned into `$head` by `template_process_html()`. Personally, I would use a `template_preprocess_html()`. You can add your logic there. For example,

```
function mymodule_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css');
  }
}

```

---
Tags: theming, hooks
---


# Question
Title: Override menu item weight (bring it to same level as 'user' link) that has user/% path and has to be in user-menu
I need a menu item living in the user-menu, has path like 'user/%something' but i dont want it to have "My account" link as parent (that has path 'user')

i can only change that through the administration but this is not an accepted answer...

Any thoughts?

thnx

# Answer
> 0 votes
Even though the documentation of `hook_menu()` doesn't mention it, the `plid` attribute can be used for specifying the ID of the parent menu link. You can set it to *0* if you don't want your menu item to have a parent.

It's probably not included in the documentation, because it's problematic to know the menu link ID (`mlid`) on that level where you use `hook_menu()`. It's an incremental identifier in the database, so there is no guarantee that it will always be the same (e.g. after reinstalling the site if you work on an installation profile). So I don't think it's a good idea to make a use of this attribute, except of course when you have this simple use case that setting it to zero does the job.

# Answer
> 1 votes
pff got it

had to

```
hook_menu_link_alter

```

and changes this link's plid like:

```
/**
* Implements hook_menu_link_alter().
*/
function YOURMODULE_menu_link_alter(&$item) {
  if ($item['link_path'] == 'user/some-path') {
    $item['plid'] = '0'; // instead of '2' (My Account menu item)
 }
}

```

drupal is a pain sometimes... but we love it anyway

---
Tags: routes
---


title: How to add tabs to panels setting page?

text:
# Question
Title: How to add tabs to panels setting page?
I want to add additional vertical tabs (marked with red) in screenshot, but have had no luck with google or documentation.

How does one add tabs here?

# Answer
Those vertical items are internally called "operations" and are implemented by task\_handlers plugins although some of them are *hardcoded* in page\_manager. You can see some examples in:

```
ctools/page_manager/plugins/task_handlers/http_response.inc
panels/plugins/task_handlers/panel_context.inc

```

You may also find more info in page\_manager\_render\_operations() docstrings.
> 1 votes

---
Tags: panels, chaos-tool-suite
---


# Question
Title: How to overwrite a view template from within a module?
Till now I only used the theme folder to overwrite specific view templates. In order to be able to separate code from theming and bundle functionality I would like to put this view template into a custom module using features.

I guess there won't be a direct way to do this in features itself but that wont be the main problem here.

# Answer
> 3 votes
You can define the views template path directly within your module (following assumes views 2.x):

```
/**
 * Implementation of hook_views_api().
 */
function mymodule_views_api() {
  $path = drupal_get_path('module', 'mymodule');
  return array(
    'api' => 2.0,
    'path' => $path,
    'template path' => $path . '/templates',
  );
}

```

Check out the API documentation built into views for adding templates into your module: http:///help/views/api-default-views (\<-- requires advanced help module)

---
Tags: views, theming, features
---


# Question
Title: How to get url path info into a form variable
I am creating a module for Drupal 7 that has form that will appear in a block. What I would like to do is get the url for the page that the block appears on (when displayed to the user) and store it in a hidden variable so that it can be processed later. Is this possible and how would you go about doing it?

Thanks

# Answer
> 0 votes
How to store the data depends on what you want to achieve with that data or how you want to process it afterwards. The easiest solution for that is probably using watchdog() after form submission:

```
watchdog('myblock', $url);

```

To get the current path there is current\_path():

```
$url=current_path();

```

Please beware that you must disable caching for that block to have the code in your block processed all the time. Here is an answer on how to create a block programmatically in Drupal.

---
Tags: 7, forms, blocks, uri
---


# Question
Title: Negative value for graphicXOffset not being applied
Please compare these two maps.

On this map ... http://dev.lambeth.gotpantheon.com/map Notice the location police helmet image, bottom-left near to Union Road.

On this map ... http://test.lambeth.gotpantheon.com/map The actual location of this police station is indicated by a blue circle.

The problem is that we need to have the graphic raised by 20px or so so that it points to the correct location.

When we add a negative graphicXOffset in the style settings, nothing happens. (A positive value does work, but that's not what we want).

See screenshots here: http://drupal.org/node/1808794

# Answer
> 0 votes
Actually, I've successfully used both negative x and y offsets.

However, since you're trying to raise the graphic (move it up, I'm assuming), you need to be using the y offset. That's the one that controls the vertical placement. ;0)

---
Tags: javascript
---


# Question
Title: Difference between $form_id and $form['#id']?
What's the difference between `$form_id` and `$form['#id']` in `hook_form_alter()` ? Why they have not the same values?

# Answer
Next should make sense:

```
<form action="somepath" id="search-theme-form"> <!-- id = $form['#id'] -->
  <input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form"/> <!-- value = $form_id -->
</form>

```

**Terms:**

`#form['#id']` = store html form attribute id:

> Used to populate form elements' id property. In rare cases, you can set this value yourself on a form element, to override the default setting.

`$form_id` \- point to Drupal form function name, in html it's form hidden element:

> The unique string identifying the desired form. If a function with that name exists, it is called to build the form array.
> 11 votes

---
Tags: forms
---


# Question
Title: Howto drag & drop field images in editor
1. Is there any possibility/ module to multiupload e.g. 3 three images and drag/insert them into the text field (Body) to the position I want the Images?
2. After this it should open colorbox gallery when I click on this images in the content.

I painted my problem:

https://i.stack.imgur.com/wVWrK.jpg

regards, l

# Answer
> 2 votes
> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

2) Vimeo Screencast Colorbox for Drupal 7, part 2: Inline images with the Insert module

---
Tags: media, javascript
---


# Question
Title: Making text fields autocomplete in views exposed filters
I want to make a text field auto complete in a views exposed form. I tried using the following code but nothing happens(I don't see that blue icon in the text field):

```
<?php
function nk_menu() {
    $items['nk/autocomplete'] = array(
        'page callback' => '_nk_autocomplete',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}
function nk_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-my-page')) {
        $form['title']['#autocomplete_path'] = 'nk/autocomplete';
        $form['title']['#default_value'] = 'abcd'; // this one also doesn't work
        print_r($form); // to be sure that properties has been added to the form (they are added)
    }
}

function _nk_autocomplete($string) {
  // ...
}

```

Why doesn't it work? I know that there is a module for that, but I want to know why mine doesn't work?

# Answer
Views change elements after form generation, so you should add own after build function:

```
function nk_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-my-page')) {
      $form['#after_build'][] = 'nk_views_mypage_exposed_after_build';
    }
}

function nk_views_mypage_exposed_after_build($form, &$form_state) {
  $form['title']['#autocomplete_path'] = 'nk/autocomplete';
  $form['title']['#default_value'] = 'abcd'; // this one also doesn't work
//  print_r($form); // I recommend to use dsm function of devel module, instead of print_r.
  return $form;
}

```
> 0 votes

---
Tags: 7, views, forms
---


# Question
Title: Using hook_menu to add a child to a menu item
So I create a menu item called Sponsorship in administration in the following way:

```
function eac_sponsorship_menu() {
  $items['admin/sponsorship'] = array(
    'title' => 'Sponsorship',
    'description' => 'This is where all of the child sponnsorship data is stored',
    'page callback' => 'system_admin_menu_block_page',
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
    'access callback' => 'user_access',
    'access arguments' => array('access sponsorship section'),
    'plid' => 1,
    'weight' => -500,
    'expanded' => TRUE,
  );
    return $items;
}

```

If I want to create another menu item directly after this, in the same function, how do I make it a child to this previously defined 'Sponsorship' menu item?

I have seen examples that use a DB lookup to get the plid value. This seems a bit counter intuitive bearing in mind I've only just created the Sponsorship menu item, is there a simple way to do this using the API?

**For example**

```
$items['admin/sponsorship/child'] = array(
  'plid' => //simple API function to get admin/sponsorship mid?
}

```

**Edit**

I think I've just answered my own question...I don't need to define plid, the path of the array $items is enough:

```
$items['admin/sponsorship/child']

```

Is this correct?

# Answer
> 2 votes
An example child item would just fall under the parent item in the path hierarchy, no need for plid.

e.g

```
  $items['admin/sponsorship/child'] = array(
    'title' => 'Sponsor child',
    'description' => 'This is where all of the child sponsorship data is stored',
    'page callback' => 'mymodule_sponsor_child_page',
    'access arguments' => array('access sponsorship section'),
    'type' => MENU_NORMAL_ITEM
  );

```

system\_menu has some good examples of menu item containers, using system\_admin\_menu\_block\_page, e.g `admin/appearance/*`

Make sure you clear menu cache to get any new menu item to show up there.

---
Tags: routes
---


title: How to categorically theme views?

text:
# Question
Title: How to categorically theme views?
I have a site that has several pages that are just views (a blog page, calendar page, and similar). I want about 50% of my views to collapse the right column. Do I have to create a template for each individual view? Is there any way I can give views 1,2 & 3 a 3-column layout and give 4,5 & 6 a 2-column layout?

Idea: is it possible to add my own custom displays for views and theme those? Right now I have Page, Block, etc - could I have Page2column and Page3column? Then I could make my changes in views-view--page2column.tpl.php and views-view--page3column.tpl.php, right?

# Answer
You could do this with Context. Set the Context condition to be either path or view based (depending on what suits your site structure) and then have the Context reaction take care of block placement (presuming your sidebar will collapse if empty).
> 1 votes

---
Tags: views, theming
---


# Question
Title: How to display IMCE file browser in overlay or popup window?
When users access the IMCE file browser from their user profile it gets integrated in the websites main content. I want it to be displayed in the administrative overlay or even as a popup. Does anyone know how to do that?

I have checked the configuration settings, but it doesn't seem to be that easy, or I overlooked something. I also checked the module ThemeKey, but I think that would be a little overkill.

Any help would be appreciated!

# Answer
Using the Media module instead of IMCE provides a powerful popup media asset browser that integrates with WYSIWYG.
> 1 votes

# Answer
You can use an iframe with src=yoursite.com/imce. The iframe can be displayed anywhere in the page including the popups.
> -1 votes

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


# Question
Title: Would disabling these following functions in PHP.INI affect Drupal 7?
If i disabled the following php functions:

disable\_functions = escapeshellarg,escapeshellcmd,exec,ini\_alter,parse\_ini\_file,passthru,pcntl\_exec,popen,proc\_close,proc\_get\_status,proc\_nice,proc\_open,proc\_terminate,show\_source,shell\_exec,symlink,system

would this affect drupal 7 in anyway? I am disabling them to increase security on my server. This was mentioned on securing an Invision powerboard forum.

# Answer
> 4 votes
Yes, that may cause odd debug issues down the track.

Some of those are required by drush:

i.e:

* escapeshellarg
* escapeshellcmd

symlink is used in system.tar.inc

Modules such as devel and advanced\_help use parse\_ini\_file

Other contrib may use others, e.g print\_pdf uses proc\_open

---
Tags: security
---


# Question
Title: How to change facebook og:image to post image link?
For the facebook comments/share/etc I get the wrong thumbnail and as far as I've googled, it's due to the og:image meta tag. I'm using Drupal for Facebook module, is there a way to alter it? I found that I have to place 'rel="image\_src"' somewhere, but where? At the image tag? And how can I do that using views?

# Answer
> 3 votes
The Metatags module supports OpenGraph meta data with token support, patterns, overrides for individual nodes and so on. It's a really handy module for this kind of stuff.

http://drupal.org/project/metatag

If you're getting the wrong image show up in Facebook you could point it to the correct image using this module's token support.

# Answer
> 0 votes
Put this in your HTML page, inside the `<head>` tag; this will tell Facebook to use this image when any page from your site is posted on Facebook.

```
<link rel="image_src" href="http://www.example.com/facebook-logo.jpg" />

```

# Answer
> 0 votes
Implement

```
hook_html_head_alter()

```

On the pages you like, alter the output of those pages like

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_html\_head\_alter/7#comment-27259

There you can

```
dpm($head_elements)

```

and unset the previous og:image, or if you are in a node page you can load this node and display a field-image ...

This becomes handy when you are not on a node page, e.g. a Views page

---
Tags: social-network
---


title: Youtube video size in grid theme

text:
# Question
Title: Youtube video size in grid theme
I am trying Omega and wondering if there is a way to specify the size of the Youtube video in grid terms, so I could easily show few videos next to each other (in a view for example).

Or if there is a way to make video automatically fit within a cell of a view?

# Answer
Setting the video's width to 100% via CSS should make it fit whatever width you've given its wrapping cell or div.

Check out the FitVids module / library for an all round solution to making videos behave better on responsive sites.

http://drupal.org/project/fitvids

http://fitvidsjs.com
> 1 votes

---
Tags: 7, theming, files
---


title: Random order in a view

text:
# Question
Title: Random order in a view
I'm working on a Drupal 7 site that lists hotels at the moment. To make it fair on the hotels who have signed up the listing page needs to be in a random order on each visit. You can click through to view a hotel's details details on a separate page. I need the site to "remember" the order the hotels were in so that when you go back to the listings they're in the same order and so the next/previous buttons work on the hotel details page.

I'm currently listing the hotels in a view so I'm a bit stumped as to how I can get this to work.

Thanks.

# Answer
> 5 votes
You can setup Views to cache the query. This will probably be globally, (meaning the every one will see the same list for X time). It's not bulletproof but it's an easy solution. Alternatively you need to do some cache per user, which could be quite tricky or some custom code.

### **Update**

By default Views allow you to clear the cache every 5 min (and other predefined values), if you add the cache actions module, you get rules based clearing of cache. With the use of rules you are able to setup the clear cache event to fire at a specific time of day (triggered by cron) and other special conditions that you are able to build with the power of rules.

# Answer
> 2 votes
First of all, in order for the View to "remember" your random order, you will need to cache it. But that will show the same View to every user. The simple solution is to set a relatively short cache time, so that you get a new random order, say every ten minutes.

However, since you would like to take it a step further, you can do the caching "per user context". This will be quite complicated, but I will do my best to explain how you can do this.

I will suggest you use Panels and Page manager, to accomplish this. Both modules are fairly complex tools, that require some understanding to make work properly. I will provide an outline below, and then I suggest these videos, for further information.

I make the assumption here that you have a dedicated "listing page". The solution should be applicate in order situations as well, such as the list being shown on a node-view, but will be slightly different.

1. Install the Chaos tool suite (ctools) module, and Panels, and enable "Page manager", "Views content panes", as well as "Panels".
2. Go into your View, and add a display of type "Content pane", leave it un-cached.
3. Go to admin/structure/pages, and enable create a "custom page".
4. Create a variant of type "Panel", pick any layout for now.
5. Add your your content pane to the panel page.
6. Go to Contexts", in the left menu. Add a "User" context, selecting "Logged in user".
7. Go back to "Content", and in the top right of your view pane, click the little cog, go down to "Caching", and select "Change".
8. Pick "Simple cache", any timeframe you want, and a granularity of "Context".

Now, you will get one individual View cache, per **logged in** user. If you want to make this work for anonymous users, things will become further complicated, since it's not obvious "who is who", so to speak. We first need to agree on what constitutes "a user". A simple answer would be "an ip-adress". Then we need to explain this concept to Ctools, but implementing a new Ctools context. Doing so is well beyond the scope of this question, but there is an example in /ctools/ctools\_plugin\_example/plugins/contexts/simplecontext.inc.

# Answer
> 1 votes
An alternative to caching might be to use the user id (or other integer derived from the session ID) as the random seed. This way each user would always see the same order. Views is adding `ORDER BY RAND()`, and I think hook\_views\_query\_alter could be used to change this to `ORDER BY RAND($uid)`.

# Answer
> 1 votes
Not sure if this is exactly what you're after, but I use Views random seed. This allows you to select "Global: Random seed" as a sort criteria in Views and then set a unique 'seed' for each user and set the time in which the 'seed' resets.

---
Tags: views
---


# Question
Title: How to add alt and title attributes field for user picture?
In my Drupal project I have user picture enabled to all users, I want to add alt field and title field for Drupal user picture feature, so I can add my custom text instead of "user's picture" text.

I also want to utilize both fields in views as well.

Thanks,

# Answer
> 1 votes
My solution to my own question is as follow:

I've created a custom module to change user picture alt and title for the uploaded image

first overrides this function if you need to change "user's picture" in user profile page. (thanks to @jsheffers for pointing this out)

```
function MODULE_NAME_preprocess_user_picture(&$variables) {

  $variables['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t('YOUR CUSTOM ALT TEXT');
      $title = t('YOUR CUSTOM TITLE TEXT');

      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $title));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $title));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array(
          'attributes' => array('title' => t('View user profile.')),
          'html' => TRUE,
        );
        $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }
}

```

To make it work with views you need to create a new views handler field and extend this handler class

```
class views_MODULE_NAME_handler_field_user_picture extends views_handler_field_user_picture {

  function render($values) {
    if ($this->options['image_style'] && module_exists('image')) {
      // @todo: Switch to always using theme('user_picture') when it starts
      // supporting image styles. See http://drupal.org/node/1021564
      if ($picture_fid = $this->get_value($values)) {
        $picture = file_load($picture_fid);
        $picture_filepath = $picture->uri;
      }
      else {
        $picture_filepath = variable_get('user_picture_default', '');
      }
      if (file_valid_uri($picture_filepath)) {
        $alt = t('YOUR CUSTOM ALT TEXT');
        $title = t('YOUR CUSTOM TITLE TEXT');
        $output = theme('image_style', array('style_name' => $this->options['image_style'], 'path' => $picture_filepath, 'alt' => $alt, 'title' => $title));
        if ($this->options['link_photo_to_profile'] && user_access('access user profiles')) {
          $uid = $this->get_value($values, 'uid');
          $output = l($output, "user/$uid", array('html' => TRUE));
        }
      }
      else {
        $output = '';
      }
    }
    else {
      // Fake an account object.
      $account = new stdClass();
      if ($this->options['link_photo_to_profile']) {
        // Prevent template_preprocess_user_picture from adding a link
        // by not setting the uid.
        $account->uid = $this->get_value($values, 'uid');
      }
      $account->name = $this->get_value($values, 'name');
      $account->mail = $this->get_value($values, 'mail');
      $account->picture = $this->get_value($values);
      $output = theme('user_picture', array('account' => $account));
    }

    return $output;
  }
}

```

Make sure to call the new handler instead of the original handler by overriding this function

```
function MODULE_NAME_views_data_alter(&$data) {
  foreach ($data as $table => $config) {
    foreach ($config as $item => $item_config) {
      if (isset($item_config['field']['handler']) && $item_config['field']['handler'] == 'views_handler_field_user_picture') {
        $data[$table][$item]['field']['handler'] = 'views_MODULE_NAME_handler_field_user_picture';
      }
    }
  }

  return $data;
}

```

# Answer
> 1 votes
You would need to override this function in your template.php file and override the `alt` tag.

Another option would be to uncheck `"Enable user pictures"` in account settings and add your own custom imagefield. Then you should be able to enable `alt` and `title` fields in the field settings. You can also use this field in views.

---
Tags: 7, users
---


title: Add hyphen after field

text:
# Question
Title: Add hyphen after field
I have 2 fields; field\_a and field\_b. When field\_b is not empty, I need to append a hyphen after field\_a.

EX: field\_a - field\_b

Then, when field\_b is empty, it doesn't show the hyphen

EX: field\_a

I have been trying THEME\_preprocess\_field and THEME\_field in template.php, but can't get it to work. This is what I have, but its basically just a copy, but I don't need all the extra stuff, and I need it to only show up on field\_a when field\_b is not empty.

```
function THEME_field($variables) {
  $output = '';

  $output .= '<div class="field-itemsuu"' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . ',' . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

# Answer
You can keep it simple and just add the following to your css

```
.field_b:before{
  content:"-";
}

```

It will only show when there is a value for the b field.
> 1 votes

---
Tags: entities, theming
---


# Question
Title: How to SUM/add the values of two fields in a View?
I have two separate fields in a View:

1. Miles on Engine at Time of Purchase/Delivery (field\_engine\_hours\_at\_delivery)
2. Miles added to Engine After Purchase/Delivery (field\_util\_agg\_engine\_hours)

(1) is a standard integer field. (2) is fed by an aggregation of many other content items. My view is set to display these two values in a table, side by side.

I would like to now add those two fields to get a "Total Miles on Engine" value for the view. I tried adding a Views PHP field with the following PHP code, but the result that is returned is blank.

Value Code

```
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_engine_hours_at_delivery'))) + array_pop(array_pop(field_get_items($entity_type, $entity, 'field_util_agg_engine_hours')));

```

Output Code

> `<?php $display_output = $entity_field_item['value']; ?>`

I'm not very well-versed in PHP, so I'm sure I've got something amiss in that code. Can anyone clarify whether this can be done... and if it can, what I need to change in my code to make it work?

P.S., I also tried this version of the Value Code, but still did not get any result:

```
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, '$row->field_engine_hours_at_delivery'))) + array_pop(array_pop(field_get_items($entity_type, $entity, '$row->field_util_agg_engine_hours')));

```

Thanks!

# Answer
I ended up getting it to work. I left the Value Code field blank and added this code to the Output Code:

```
<?php
print $data->_field_data['nid']['entity']->field_engine_hours_at_delivery['und'][0]['value'] +
$data->field_field_include_utilization_engine[0]['rendered']['#view']->result[0]->field_data_field_engine_utilization_hours_field_engine_utili;
?>

```
> 0 votes

# Answer
There's a module for that: Views Calc allows you to SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns in Views.
> 0 votes

---
Tags: views
---


title: form alter user login drupal 6

text:
# Question
Title: form alter user login drupal 6
I have added this:

```
    function ahml_form_alter(&$form, $form_state, $form_id) {
      if ($form_id == 'user_login') {
        $form['my_field'] = array(
        '#type' => 'link',
        '#title' => t('Example link'),
        '#href' => 'login'
      );
    }

```

into a custom module and instead of a link in the output I have two text boxes: one reads "example link title", the other "example link url".

Do I have this wrong of is there just something else in the system causing this to happen?

# Answer
> 0 votes
I recommend you to write the function as follow:

```
function ahml_form_alter(&$form, $form_state, $form_id) {
  //for register page
  if ($form_id == 'user_register') {
    $form['my_field'] = array(
      '#type' => 'markup',
      '#value' => l('Login page', 'user/login'),
    );
  }
  //for login page
  if ($form_id == 'user_login') {
    $form['my_field'] = array(
      '#type' => 'markup',
      '#value' => l('Register link', 'user/register'),
    );
  }
}

```

For additional details, check Drupal 6 Form API Reference

---
Tags: forms
---


title: searching and entity references

text:
# Question
Title: searching and entity references
I have two content types documents and authors. When creating a document a selection list of entity reference's to authors is used to select the author.

Searches for the author name find the correct author, but do not find the document that has an entity reference to the author. How do I get the search engine to to display both the author and the documents the author is referenced from.

EX Book "GOOD BOOK" is has an entity reference to Author "TOM".

When I do a search for TOM I get the "TOM"'s authors information but NOT an entry for "GOOD BOOK"

# Answer
> 0 votes
I suspect you need to configure your search view modes.

For each of your content types, visit the **Magage Display** page, eg admin/structure/types/manage/page/display

Unfurl **Custom Display Settings**, check **Search Index** and **Search Result**, and save.

Then for each, configure the search view modes. **Search Index** will be used to build up the text that gets indexed. Add / remove fields as needed. The **Search Result** will be used to display the search results.

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


# Question
Title: How to declare a click on a particular tab to be a new event for use with Rules?
I want to declare a click on a particular quicktab or any other tab as a new event for use in a rule. For example, when the user clicks that specific tab, an e-mail is sent to an admin. How can I make this click trigger a new event?

# Answer
Possible lead? The Rules Link module. The JavaScript option may be what you're after.

Here is a quote about it (from the module's project page):

> ... lets you create links which trigger arbitrary functionality with the help of Rules.
>
> **Example use cases**:
>
> * Publish/Unpublish content
> * Subcribe users to current group
> * Mark nodes, comments (as Spam), unpublish it and block the author.
> * Batch functions like, delete all comment for a node
>
> And many more...
>
> **Features**:
>
> * Attach the link to any entities.
> * Show the link only for certain bundles.
> * Narrow the entities on which the link will be shown using the visibility conditions.
> * The links are usually displayed using Views.
> * For entities that can be displayed, the links can be shown on node view.
> * Supports an arbitrary number of additional Rules parameters for passing context via Views.
> * 3 types of links: Javascript, Normal and Confirmation form links.
> * Use individual permissions for each link.
>
> **Usages**:
>
> There are three types of links:
>
> * Javascript - Links that will trigger the rules using Ajax.
> * Token - This are basic links, that will reload the page after calling them.
> * Confirmation link - Show a confirmation form before executing the rule.
> 0 votes

---
Tags: 7, rules
---


title: Date question re date_popup

text:
# Question
Title: Date question re date_popup
In the Date module I'm trying to customize #date\_popup; is it possible to completely eliminate the Timepicker field; it currently displays Date + Time fields. I only want the Date field and can't figure out how to remove it in Drupal and/or the Dashboard.

Anyone tried this?

Thanks!!!

# Answer
> 1 votes
On the "Date attributes to collect", uncheck "hour", "minute" and "second". These options are available on the "DATE FIELD SETTINGS" group of the field configuration screen.

---
Tags: javascript, datetime
---


# Question
Title: Gift Certificates for Ubercart 3 & Drupal 7
We would like to add gift certificates to our Drupal 7 site running Ubercart 3. There was a module (UC Gift Certificate) for Drupal 6, which has not been ported to 7.

There appears to be some talk about using UC Discount Coupons, which has been ported to 7, to achieve this functionality, but I am very skeptical (because it was not designed for this, and one immediate problem with it is that there does not seem to be a way to partially redeem a discount coupon.)

Has anyone successfully setup gift certificates on Drupal 7 with Ubercart 3? If so, how?

# Answer
There's an effort going on to port UC Gift Certificate to Drupal 7: link to issue
> 1 votes

# Answer
I have setup a system before for a client which has used purchasable coupons as a special product class to achieve the same results. It allows users to purchase a coupon as a product (which you label as Gift Certificates). A rough guide is below, as best as I can remember it:

After installing Ubercart v3 and the UC\_Coupon Module:

* Go into coupon modules' settings and allow coupons to be purchasable.
* Go into the Coupon section and create some coupons you want to offer on your website.

Ideally you can use the options that coupons provides to get a granular selection of what you want to discount on your website and how.
* Make sure when you're making the coupons that you select the "can be purchased" sounding option.

I don't remember exactly how it's phrased.

After that, go to

* Store \> Product Classes, create a new class of product called "Gift Certificates" and assign varying prices as product attributes ($5, $10, $50 etc..).

Or you could make a separate product class for each price/style of certificate, your choice.

Either way, once you make the product class(es), you can use the created class to create as many "Gift Certificates" as you wish just like any other content type, you need to:

* attach the coupon your selling to the product using the Features tab on the Edit Product screen.

This should allow the same effect of a gift certificate using coupons as a product you purchase.

The coupon module offers some powerful ways to create some nifty promotional sales for your products / services etc if you play around with it.

Good luck!

Edit: The only situation this wouldn't work without some custom coding is if you wanted to offer a "gift certificate" at X amount, where X = price is set by the user.
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: Zen theme not showing second level menu items
I am creating a zen sub-theme and I edited the menu called "Main menu" to have on root level item that has 5 children (second level). The root level item shows up fine but none of the children are ever output in the HTML.

I verified they are all enabled. Just not sure why they aren't being sent back to the client. Does the Zen theme need some modification to support menus that are deeper than one level?

# Answer
> 2 votes
**Edit your page.tpl.php**

Edit the section where the `primary_links` are printed to show the whole primary links menu instead of only showing the first level links of your primary links menu.

```
<?php if (isset($primary_links)) { ?>
     <div id="primary_menu">
<?php print theme('menu_tree',variable_get('menu_primary_menu',0)); ?>
     </div>
<?php } ?>

```

**In Drupal 6**

```
<?php
$menu_name = variable_get('menu_primary_links_source', 'primary-links');
print menu_tree($menu_name);
?>

```

**Drupal 7**

```
<?php

    $menu_name = variable_get('menu_main_links_source', 'main-menu');
    $tree = menu_tree($menu_name);
    print drupal_render($tree);
?>

```

# Answer
> 0 votes
Use Superfish or Nice Menus module to show 2nd level menu items.

---
Tags: routes, theming, navigation
---


# Question
Title: Set the "from" header in the email to be in the format "Full Name" <email@address.com>
How can I change the *from* header in the email sent from Drupal to be in the format `"Fullname" <email@address.com>`?

I managed to do it on a Drupal 6 site at one point in the past, but I no longer have access to that site, and I don't remember how to do it.

# Answer
> 17 votes
You can use `hook_mail_alter()` to change the "from" email address of any email sent out from your site. The email address used needs to conform to the RFC standard, which it does is your question's title. But user names can be tricky and might contain illegal characters. There's a comment on the D6 docs that provides a code sample for properly formatting the email address. Your code would look something like...

```
function yourmodule_mail_alter(&$message) {
  $message['from'] = $message['headers']['From'] = '"Full Name" <email@address.com>';
}

```

Also, keep in mind that just setting the "from" address may not have the desired results in all email clients (see the discussion on the Drupal issue queue). You might also need to set "sender", "errors-to" and "reply-to" based on your requirements. Those values are in the "header" of the `$message` variable from the code sample above.

# Answer
> 11 votes
This is the method from Drupal 6 to add the the site name to the email. Substitute variable\_get('site\_name, Drupal') with The Site Full Name you want.

```
/**
* Implementation of hook_mail_alter().
* Here we allow the site name to be used as the senders name for outgoing email.
* see http://drupal.org/node/209672
*/
function mymodule_mail_alter(&$message){
  $default_from = variable_get('site_mail', ini_get('sendmail_from'));

  if($message['from'] == $default_from){
    $message['from'] = '"'. variable_get('site_name', 'Drupal') .'" <'. $default_from .'>';
    $message['headers']['From'] = $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['headers']['Errors-To'] = $message['headers']['Reply-To'] = $message['from'];
  }
}

```

the function for hook\_mail\_alter() has not change in Drupal 7, so this should work.

# Answer
> 3 votes
Regarding the settings you have to change, this is still an issue in D7. If in doubt, use the following code in your hook\_mail\_alter :

```
$message['from'] = $from;
$message['headers']['From'] = $from;
$message['headers']['Sender'] = $from;
$message['headers']['Return-Path'] = $from;

```

---
Tags: 7, emails
---


# Question
Title: Add a custom form only to a particular content type
is there any way to add a form only to a particular content type so that in all nodes of my content type, say, My\_Custom\_Content, that form is displayed but not on any other nodes

# Answer
If I'm not wrong, I think you are trying to display your custom form in the node view of a particular content type. You can do this in two ways.

The first approach is to implement hook\_node\_view() from the module level.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if($node->type == 'your_content_type'){
            $node->content['my_form'] = array(
                '#markup' => drupal_get_form('your_form_id'),
                '#weight' => 1,
            );
        }
    }
}

```

The second approach is to implement hook\_preprocess\_node() from the theme level.

```
function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    if($variables['node']->type == 'your_content_type'){
        $variables['content']['my_form'] = drupal_get_form('your_form_id');
    }
  }
}

```
> 4 votes

---
Tags: forms
---


# Question
Title: Automatically shorten URLs on website with other domain name that I own
Yesterday I purchased the domain stps.me to be able to shorten URLs for my other website setups.co.

I found two modules, Shorten URLs and ShURLy, that were able to shorten URLs.

However, I can't find the option to use my own domain name, and therefore I'm asking you for help.

I know there's a free tool to make your own URL shortening service called Yourls, but I can't figure out how to implement this to Drupal to automatically shorten and display a URL when I upload new nodes.

Thanks in advance :)

# Answer
> 1 votes
Found this module, Yourls, that works exactly like I described above.

---
Tags: 7, uri
---


# Question
Title: How to improve search results filtering on taxonomy
I would like to know the best way to filter drupal search results using taxonomy. I want users to be able to search for particular results from a particular taxonomy..this can be done to refine already searched results, or can be done from scratch.

Any module for Drupal 7 that does this well?

# Answer
> 0 votes
Use Custom Search module.

> This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box

Or, the other best solution is to use create a view with exposed filters. Here is article about it

# Answer
> 0 votes
I think you should give a try to Extending Drupal 7 search. The form ID on the search result page would be `search_form`. You can use hook\_search\_execute() to filter the result as you need.

Or you could also try the Extended search page module, but it is in beta and it requires Search API and Search API pages.

Personally I would write a custom module rather than installing many modules.

# Answer
> 0 votes
One of the best solution to this is using Faceted search. You need to switch search engine to Solr to get that. There are several different vendors that sell Solr hosting if you don't want to set that up yourself, including Acquia.

Drupal integration is provided either by Apache Solr search integration or Search API.

---
Tags: 7, taxonomy-terms, search
---


# Question
Title: How can I add a page from the Views module to a taxonomy menu?
How can I add a page from the Views module to a taxonomy menu? I have a taxonomy menu like the following.

* A
    + A1
    + A2
* B
    + B1
    + B2
* C

In C, I want to display my view page output. How can I do it?

I am using drupal 6.

# Answer
> 1 votes
For Drupal 6, there's the Taxonomy Views Integrator module.

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice.

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


# Question
Title: Identifying the level of menu items in the item array?
I have a D7 menu of nearly 300 terms in a 3-level hierarchy. Rather than generate them one at a time in the UI, I would like to generate them using code. I am using the book 'Pro Drupal Development' and the Drupal API documentation for menus and the menus.module to attempt this, but am confused about how to establish the structure of the three tiers.

Creating a menu item appears to be fairly simple, implementing hook menu and creating item arrays with values assigned to 'title', 'page callback', 'access callback', and 'type'. My problem is that I must define the hierarchy and I am not clear on how that is done. **How do I identify the parent in the array structure?**

EDIT - additional information

The menu items, at all levels must have a callback to a view definition following the pattern `View_Name/tid/display_type`. The first level of the URL will be a unique label for the View being called. The next level is a term id identifying the specific term from a vocabulary that defines the relationships of the menu options. The third level determines which view page in the definition provides the view output for display. My question is addressing how to duplicate the taxonomy hierarchy in a code generated menu? How do I tell the Drupal the relationships between the links to duplicate the three tier menu system when the links are created? I can provide my customized callbacks but haven't found the correct array key-value settings to generate the menu correctly.

I have experimented using the Taxonomy\_Menu module to generate the menu directly, but I cannot find a way to generate different third level URL values within the module. The module generates a menu of taxonomy links and Drupal does not expose the links for editing.

# Answer
> 2 votes
I'm not sure to understand your problem, but as you define everything by code, it should be straightforward.

You can create any menu entry you want, on any existing or newly created entry.

As for the hierarchy, you just have to define your paths like any URL path. As per the doc : If you have

```
function mymodule_menu() {
    $items['abc'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
}

```

You can then define a child entry like this :

```
function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_def_view',
    );
    return $items;
}

```

This will give an entry at the root level 'abc' and a child entry 'abc/def'.

HTH.

# Answer
> 0 votes
Well check out my question Override menu item weight (bring it to same level as 'user' link) that has user/% path and has to be in user-menu

and use

```
'plid' => '0' or the mlid of the menu you want as parent

```

in the $items of hook\_menu()

---
Tags: routes
---


# Question
Title: Correct way of passing variables between hook and tpl.php
I asked a similar question a few months ago, but the truth is that there is very little information about the correct way of doing this.

The simplest way is to use the arg() function, but as the docs clearly state, that is the wrong way of doing it. While trying to follow the correct steps, this is what I have so far:

A menu with the necessary paths:

```
$items['products/search/%/%'] = array(
        'title'             => 'Products search filtering',
        'description'       => 'Show review categories.',
        'page callback'     => 'ThemeSearchProducts',
        'page arguments'    => array(2,3),
        'access callback'   => 'user_access',
        'access arguments'  => array('access content'),
        'type'              => MENU_NORMAL_ITEM,
        'file'              => 'includes/mymodule_reviews.inc',
);

```

These arguments are sent via ... arguments (sorry for the joke). to the themesearchproducts function

```
/**
 * THEME List of reviewable products
 *
 */
function ThemeSearchProducts($arg1, $arg2){

//  $output = theme('search_products', $arg1);
  $output = theme('search_products', 'test');

  echo 'args in theme: ' . $arg1 . $arg2 . ' || ';

  return $output . theme('pager', 10);
}

```

The echo works fine, but now the question becomes how do I send this variable to the hook\_theme of the module, and from there to the tpl.php? I have something like the following:

```
function MYMODULE_theme ($existing, $type, $theme, $path) {
    $path = drupal_get_path('module', 'MYMODULE'); // . '/templates';
    // ADD THE templates DIRECTORY
    $path = $path . '/templates';

    return array(
            // as in 'theme('verbose_method',...)
            'main_reviews' => array(
            'template' => 'MYMODULE-main_page_reviews',
            'path' => $path,
            'variables' => array('forums' => NULL, 'topics' => NULL),
            ),

```

as you can see, the module now calls the tpl in templates/MYMODULE-main\_page\_reviews.tpl.php, but I cannot find the correct way to send a variable from the previous callback to the hook\_theme. Adding a new argument to the MYMODULE\_theme throws an error, and I cannot get rid of it, not even by adding (for example) this new argument in ThemeSearchProducts, like this:

```
 $output = theme('search_products', 'test');

```

Is using variable\_set also incorrect? I'm trying to follow the "Drupal Standard Practices" as much as possible, but this last step is eluding me.

# Answer
The arguments you pass to `theme()` when you invoke a theme function are not passed to `hook_theme()`, and from there to the template file. They are passed directly to the theme function, or the template file, in the case the theme function is using it.

`hook_theme()` defines the arguments used from the theme function. How those arguments are then passed to `theme()`, and to the theme functions, depends from the Drupal version:

* With Drupal 7, they are all passed in an array, which in your case is similar to the following one:

```
array('forums' => $forum, 'topics' => $topic);

```

`hook_theme()` defines the default arguments used for the variables when no value is given. In your case, you could use `array('forums' => $forum);` and `NULL` will be used for `'topics'`. (Replace `$forum` with the value you need to use.)
* With Drupal 6, you pass the variable as single arguments to `theme()`, for example as in `theme('search_products', $forum, $topic)`. As with Drupal 7, the default value is used when you don't pass that argument.

In both the cases, the variable declared for the theme function in `hook_theme()` is the name of the variable passed to the template file. In your case, `$topics`, and `$forums` are two variables accessible from the template file.

As side note, the template file you declare in `hook_theme()` with "template" for your `theme_search_products()` needs to be search-products, or search\_products; Drupal will add the extension .tpl.php to the name, when looking for the template file. You cannot have a theme function that is declared as example\_one, and the template file that declared to be example\_two. Also, you are trying to use `theme_search_products()`, but your `hook_theme()` implementation doesn't define that theme function. The code you are showing contains the definition for `theme_main_reviews()`. If the theme function you are calling is not defined from another module, that code will not work.
> 3 votes

---
Tags: theming, hooks
---


# Question
Title: Custom form which on submit click inserts into the database
I have created a custom form in my module so that when the user clicks submit, some changes are performed in the databases and other actions follow. The form is an empty form with only the submit button nothing else. When the user clicks the Submit button, a function is called to perform some tasks. However, I am getting some errors. Here's the code:

My module folder is formtest and is placed in sites/all/modules/

formtest.info

```
name = Test Form
description = Accept Challenge Form Submit
core = 7.x

```

formtest.module

```
function formtest_menu() {
$items['formtest'] = array(
'title' => 'Accept Challenge',
'page callback' => 'drupal_get_form',
'page arguments' => array('formtest_form'),
'access callback' => TRUE,
);
return $items;
}

function formtest_form($form,&$form_state) {
  $form['button'] = array(
  '#type' => 'submit',
  '#value' => 'Accept Challenge',
  '#submit' => array('formtest_action'),
   );
  return $form;
}

function formtest_action($form,&$form_state) {
  $query = db_insert('challenges')
    ->fields(array(
    'cid' => '$node->nid',
    'uid' => '$user->uid'
    ))
   ->execute();
}

```

/\** * To display the form on a particular content type \*/

```
function formtest_node_view($node, $view_mode = 'full', $langcode = NULL) {
      if($view_mode == 'full') {
        if($node->type == 'challenge') {
          $node->content['my_form'] = array(
            '#markup' => drupal_get_form('formtest'),
            '#weight' => 1,
         );
     }
   }
  }

```

Well that's all. There's no form showing up..no error messages..nothing...I tried a var\_dump() but nothing...That custom content page is displaying as it was but there seems to be no effect of this code. Would appreciate your help in any manner. Thanks

# Answer
When I make custom forms I first register them as blocks.

```
function mymodule_block_info() {
  $blocks['review_membership'] = array(
    'info' => t('Membership'),
  );
  return $blocks;
}

```

Implement the view of the block

```
function mymodule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'review_membership':
        $node = menu_get_object();
        $block['subject'] = t('Membership');
        $form = drupal_get_form('mymodule_review_membership_form');
        $block['content'] = drupal_render($form);
        break;
  return $block;
}

```

Then I have the body of the form

```
function mymodule_review_membership_form(){

    $form = array();
    $node = menu_get_object();
    $preverified = $node->field_mng_accepted['und'][0]['value'];

    $form['accept'] = array(
        '#type' => 'submit',
        '#value' => t('Accept'),
    );
    $form['reject'] = array(
        '#type' => 'submit',
        '#value' => t('Reject'),
    );
    if(!$preverified){
        $form['reason'] = array(
            '#type' => 'textarea',
            '#title' => t('Reject reason'),
            '#default_value' => NULL,
            );
    }

    return $form;
}

```

and the reaction on the form submit (the name is automatic based on the name of form)

```
function mymodule_review_membership_form_submit($form,&$form_state){
.....

```

Once all is defined I just add the block wherever I want
> 0 votes

# Answer
`drupal_get_form` doesn't return a markup as such. it returns an array of the form structure. to get the html out put you should run the drupal\_render function.

something like `drupal_render(drupal_get_form('formtest');`
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: Getting menu links: correct chain of API functions
In my module, I need to create sort of a menu block consisting of certain menu items collected from various menus, and flattened into one level.

I'm not sure about the correct chain of the Menu API functions to call. My first attempt was as follows:

```
function _MYMODULE_block_view(){
  $html = '';

  $menu_link = menu_link_get_preferred('node/287');
  $html .= theme('menu_link', $menu_link);
  dpm($menu_link);
  return $html;
}

```

but it raises an error about several #attributes missing, so I guess this is not the right kind of object to get markup from. The API docs don't really help in understanding what kind of objects/parameters are returned/expected by functions, hence the question.

**Edit:**

Having given what Drupal complained about, the code now is as follows:

```
function _MYMODULE_block_view(){
  global $language;
  $langcode = $language->language;

  $html = '';

  $paths = array(
    'node/287',
    'node/3',
  );

  foreach($paths as $path){
    $translations = i18n_get_path_translations($path);
    if(!empty($translations[$langcode])){
      $i18n_path = $translations[$langcode]['href'];

      $menu_link = menu_link_get_preferred($i18n_path);
      $link = array(
        '#theme' => 'link',
        '#text' => $menu_link['link_title'],
        '#path' => $path,
        '#options' => array('attributes' => array('title' => $menu_link['link_title'])),
        '#below' => NULL,
        '#title' => $menu_link['link_title'],
        '#href' => $path,
        '#attributes' => array(),
        '#localized_options' => array(),
        '#prefix' => '<li>',
        '#suffix' => '</li>'
      );
      $html .= theme('menu_link', array('element' => $link));
    }
  }

  return "<ul>$html</ul>";
}

```

It does not spit out errors but... should I really trust it?

# Answer
> 0 votes
Since you're using `menu_link_get_preferred()` I'm guessing Drupal 7 here...

Theme functions have changed, and parameters now need to be named in an associative array passed to the theme function. So per the `theme_menu_link()` docs:

```
$html .= theme('menu_link', $menu_link);

```

becomes

```
$html .= theme('menu_link', array('element' => $menu_link));

```

---
Tags: 7, routes
---


# Question
Title: Would changing the permissions implemented by a module require a new version of the module?
I have created a module, and I have to change the permissions implemented (and used) from the module. Should I create a new major version (e.g. passing from 7.x-1 to 7.x-2), or is it fine to create a minor version (e.g. passing from 7.x-1.3 to 7.x-1.4)?

I am talking of a module for which there is already an official release, not of a module that has only a development snapshot.

# Answer
If it changes significant behaviour from previous version I recommend changing the major version. Even if its just a single adjustment like permissions. Wrong or missing permissions may cause huge problems on a site running your module.
> 1 votes

# Answer
I personally dont think that there should be a new branch for this altogether, or is required. We can very well get away with releasing an updated version of it, however if any Db changes are required, we will have to incorporate those as well.
> 0 votes

---
Tags: 7
---


# Question
Title: How to disallow certain strings in signatures?
As I mentioned here, spam filters do not apply to forum signatures. This opens the door to human spammers to put their spam content in their signature. I am wondering what is the easiest way to tackle this problem? One obvious solution is to extend the signature or spam modules to fix this loophole. But that is beyond my coding capacities as I know very little of drupal API.

So I am wondering whether this can be done using some sort of preprocessing or defining some rules to check the signature for certain regexps and disallow registration/saving profile when the string is flagged as potential spam? I really appreciate your hints as I'm badly suffering from this problem.

# Answer
In drupal, whichever field you are taking input as, you need to make sure that only plain text is inserted by the user. This way, drupal will run check\_plain function to the text added, and no links, xss attacks can be made.
> 0 votes

---
Tags: advertising
---