# Question
Title: Will this php code (field_view_field) work if i put this inside body field of a node with php filter?
Will this work if i put this inside body field of a node with php filter?

```
<?php echo "<h4>How are doing? Rate this site</h4>" ?>
<?php print render(field_view_field('node', $node, 'field_fivestar_rating')); ?>

```

I tried in there but its displays an error.

Notice: Undefined variable: node in eval() (line 2 of C:\ssatempsite\modules\php\php.module(80) : eval()'d code).

EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7562 of C:\ssatempsite\includes\common.inc).

# Answer
Use the following code.

```
  $node = node_load(1);
  print render(field_view_field('node', $node, 'field_fivestar_rating'));

```
> 1 votes

---
Tags: nodes, entities
---


title: Display referencing entity in panels

text:
# Question
Title: Display referencing entity in panels
I have two content types. 1. Lecture 2. Notes

Notes have an entity reference field which references lecture. Different users create different notes each referencing to a lecture.

Now, How do I display note created by user on lectures page.

# Answer
> 1 votes
I know how to do it with Views and Panels modules. First you need to create two Views:

1. First one is **Lecture\_view** create a block and add fields you want to display(Title, body, most important - **Content: Nid** and any other fields your Content type has).
2. Second one is **Notes** view, create same block but fields for notes to display, and also in a **Contextual filters** menu add new filter `(Content) Content: Nid`

Now you should go to *Lecture view* and in **Advanced** menu, click on **theme** *information* link, and you need to create template file, find row with `Field Content: Nid` and create one of suggested fields, something like `(views-view-field--conversations--page--nid-1.tpl.php) in /sites/all/themes/YOURTHEMENAME/views/YOURVIEWNAME(lecture_view--block)/YOURTEMPLATEFILE(views-view-field--conversations--page--nid-1.tpl.php)` in this file you will past code from theme view, its something similar to

```
<?php print render($output); ?>

```

you need to add one more thing embed that views:

```
<?php print views_embed_view('notes', $display_id='default', $row->nid); ?>

```

your contextual filter should work, and now you can add this view to your Panel to display, in Panel menu.

***Maybe this is not the best way to do this***

---
Tags: panels, entities
---


# Question
Title: How to display form module in two coloms?
I again looking for your help. I have a form module that should be displayed in two coloms, like this one: http://www.quickbase.com/help/images/form\_example.gif

I did a lot of researches for how to solve this and couldn't find so much.

1. do I need both functions `hook_form_alter` and `hook_theme`?
2. should they look like this?

```
function my_module_form_alter(&$form, &$form_data, $form_id){ if(stripos($form, 'my_module_form') === 0 && $form['#parameters'][2]->type =='product') {
        $form_data['#theme']  = 'mytemplate';
         }
}

function my_module_theme()
    {
          return array(
            'my_module_form' => array(
              'arguments' => array('form' => NULL),
              'template' => 'mytemplate',
            ),
          );
        }

```
3. What should contain file mytemplate.tpl.php ?

**Here is part of my form:**

```
function my_module_form($form_data) {
    $form['contact_information'] = array(
        '#value' => variable_get('contact_form_information', t('Please fill in all fields.'))
    );
    $form['first'] = array(
        '#type' => 'textfield',
        '#title' => t('First name'),
        '#maxlength' => 20,
        '#required' => TRUE,
    );
    $form['last'] = array(
        '#type' => 'textfield',
        '#title' => t('Last name'),
        '#maxlength' => 20,
        '#required' => TRUE,
    );
    $form['street'] = array(
        '#type' => 'textfield',
        '#title' => t('Street Address'),
        '#required' => TRUE,
    );
ect

```

**Finally I solved it:**

```
function my_module_theme($existing, $type, $theme, $path) {
  $hooks['my_module_form'] = array(
    'template' => 'mytemplate',
    'arguments' => array('form' => NULL),
  );
  return $hooks;
}

```

and here is mytemplate.tpl.php

```
<div style="float:right; width: 100%; height:20px; text-align:left;">
        <?php print_r(drupal_render($form['contact_information'])); ?>
    </div>
<div style="margin-top: -1em;">
    <div style="float:left;">
        <strong><?php print_r(drupal_render($form['first'])); ?></strong>
    </div>
    <div style="float:right;">
        <strong><?php print_r(drupal_render($form['last'])); ?></strong>
    </div>
    <div style="float:left;">
        <strong><?php print_r(drupal_render($form['street'])); ?></strong>
    </div>
    <div style="float:right;">
        <strong><?php print_r(drupal_render($form['city'])); ?></strong>
    </div>
    <div style="float: left;">
        <strong><?php print_r(drupal_render($form['postal'])); ?></strong>
    </div>
    <div style="float:right; width:385px;">
        <strong><?php print_r(drupal_render($form['state'])); ?></strong>
    </div>
    <div style="float:right;">
        <strong><?php print_r(drupal_render($form['mobile'])); ?></strong>
    </div>
    <div style="float:right; ">
        <strong><?php print_r(drupal_render($form['ext'])); ?></strong>
    </div>
    <div style="float:right;">
        <strong><?php print_r(drupal_render($form['phone'])); ?></strong>
    </div>
    <div style="float:left;">
        <strong><?php print_r(drupal_render($form['home_phone'])); ?></strong>
    </div>
    <div style="float:right;">
        <strong><?php print_r(drupal_render($form['email'])); ?></strong>
    </div>
</div>

    <div style="background-color:#EEEEEE;
        float:left;
        margin-bottom: -5%;
        width: 100%;
        text-align:right;">
                <?php echo drupal_render($form['submit']),
                            drupal_render($form['clear']); ?>
</div>

```

# Answer
You can use the markup-type in your form array to group form items and then style the groups. The code below will wrap the three items with a div which has the class **column-left**. Do the same for the right column.

To clear things up: The **column\_left**-item is of the type **markup**, which is the default type.

```
$form['column_left'] = array(
    '#prefix' => '<div class="column-left">',
    '#suffix' => '</div>',
);
$form['column_left']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#maxlength' => 20,
    '#required' => TRUE,
);
$form['column_left']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    '#maxlength' => 20,
    '#required' => TRUE,
);
$form['column_left']['street'] = array(
    '#type' => 'textfield',
    '#title' => t('Street Address'),
    '#required' => TRUE,
);

```

For Drupal 7, you can use the container-type and use the attributes array to add the class. A div is generated automatically.

```
$form['column_left'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('column-left'),
  ),
);

```
> 3 votes

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


title: node form validation not called

text:
# Question
Title: node form validation not called
I would like to add some custom validation to a node form. But for some reason the validate function is skipped, the submit function does gets called.

```
/*
 * Custom Form settings
 */
function frontpage_banners_form_promo_banner_node_form_alter(&$form, &$form_state, $form_id) {

  $form['#validate'][] = 'frontpage_banners_form_promo_banner_node_form_validate';
  $form['#submit'][] = 'frontpage_banners_form_promo_banner_node_form_submit';

  dpm($form_id);
  dpm($form);

}

function frontpage_banners_form_promo_banner_node_form_validate(&$form, &$form_state) {

  drupal_set_message('error');

  form_set_error('', t('Email must be valid format if entered.'));
}

function frontpage_banners_form_promo_banner_node_form_submit(&$form, &$form_state) {
  drupal_set_message('submit');
}

```

I tried several function names but nothing seems the work.

From the $form array:

```
#validate (Array, 2 elements)
0 (String, 18 characters ) node_form_validate | (Callback) node_form_validate();
1 (String, 54 characters ) frontpage_banners_form_promo_banner_node_form_v... |

```

# Answer
Found the problem, i use the More buttons module and there seems to be something wrong with way the hook\_form\_alter is handled in the module, fortunately there is a fix.
> 5 votes

# Answer
try this:

```
$form['#validate'] = array('frontpage_banners_form_promo_banner_node_form_validate');

```
> 1 votes

# Answer
I had same problem . I try to `dsm();` in `#validate` function and didn't see anything.
Your method is ok and have no problem.
they called correctly and run. To sure that your function called I suggest you put `die('this is worked`);\` in your callback function . I surly say your method is correct and your function will call after your form submiting.

please test this

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

  $form['#validate'][] = 'frontpage_banners_form_promo_banner_node_form_validate';
  $form['#submit'][] = 'frontpage_banners_form_promo_banner_node_form_submit';

  dpm($form_id);
  dpm($form);

}

function frontpage_banners_form_promo_banner_node_form_validate(&$form, &$form_state) {

  var_dump($form_state);
  die('this worked');
}

function frontpage_banners_form_promo_banner_node_form_submit(&$form, &$form_state) {
  var_dump($form_state);
  die('this worked');

}

```
> 0 votes

---
Tags: 7, forms
---


title: custom.module vs template.php

text:
# Question
Title: custom.module vs template.php
This is a not-so-targeted question but I can't find any good information on this.

When is it considered correct practice to put code inside your template.php file and when to implement it in a module?

I mean in my current example I need to call hook\_preprocess\_node and inside perform a drupal\_get\_form and render that form. I've put my logic inside template.php.

Is that correct? If not, can you give me a short list of DOS and DONTS regarding the issue?

# Answer
There are two things I try to keep in mind when making this decision.

Is this a functional feature, or a purely visual one? Functional components go in modules. Purely visual ones go in the theme.

What happens if I alter or radically change the theme down the road and/or allow multiple themes for my site? If you don't want to replicate the feature, then it should go in a module.

Drupal does make it easy to intertwine content, business logic, and presentation. For the long term maintainability of a site, you really need to be careful when you implement things.

A good rule of thumb is that a theme should not need to know about IDs (`$nid`, `$uid`, `$tid`, etc) for anything, and should only need to know machine names to alter visual appearance.

In your case, adding a form to a node is a functional change, and I would really put that in a module.
> 8 votes

---
Tags: theming
---


title: Content not showing when logged out!

text:
# Question
Title: Content not showing when logged out!
I don't know why this is happening, but none of my content are displayed when logged out. All the content in views, blocks, everything disappear upon logout. As far as I can remember, I haven't touched any permission. In fact I created this project only a few days ago.

I have two jCarousel slideshows and a few views connected with nodequeues on my site among other things; all of them disappear upon logging out. I have already checked all permissions on views, blocks, and everything I could find.

What can I do to resolve the issue?

As an experiment I searched for a content through the search bar, and the page returned said access denied.

EDIT: Problem solved. The solution has been posted in this thread.

# Answer
> 1 votes
Go in admin/user/permissions and check if the "access content" \[and "search content"\] is checked for the anonymous user

# Answer
> 1 votes
site.com/admin/content/node-settings/rebuild Sometimes Drupal node permissions get corrupted. When this happens, rebuilding the node permissions can solve the problem. Please be advised that if you have a lot of nodes, this can take a very long time.

# Answer
> 0 votes
First of all you should check permission under **Node** for the different content types here http://www.example.com/admin/people/permissions if everything is fine then you have check your code may be you are overriding hook\_node\_access in your custom module.

# Answer
> 0 votes
You probably have a problem with cache. Check it turning cache off for page and blocks.

---
Tags: users, nodes
---


title: How do I add the file size to a view?

text:
# Question
Title: How do I add the file size to a view?
After reading and searching through related topics, I have not seen any clear answer about how to show the file size in a Views created file list. Im using Drupal 7 and having File 7.14 field installed.

I was expecting to select a field in Views in order to show it as a third column in a list of files that can be downloaded (after Title and File).

I am not a programmer, and the only related issues I've seen so far is about editing php files.

Currently, as administrator, I see the file size when I edit the node containing the file. Why can this value not be used other than in edit mode?

---

To be complete I've added the query how it is now:

```
SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language,   file_managed_file_usage.filesize AS file_managed_file_usage_filesize, 'node' AS  field_data_field_file_node_entity_type
FROM
{node} node
LEFT JOIN {file_usage} file_usage ON node.nid = file_usage.id AND file_usage.type = 'node'
LEFT JOIN {file_managed} file_managed_file_usage ON file_usage.fid = file_managed_file_usage.fid
WHERE (((node.status = '1') AND (node.type IN  ('file'))))
ORDER BY node_title ASC
LIMIT 50 OFFSET 0

```

# Answer
> 15 votes
Try creating a reference to the file.

Under **Advanced** in your View, and add a relationship (select *File Usage: File*). If you now go to add a new field in your view, you should see a few more options under File, one of them being *File: Size*.

---
Tags: views, files
---


# Question
Title: Output a Menu with just needed classes for ul and li,. Nothing more
Normally a drupal menu is being rendered like this:

```
<ul class="menu">
<li class="first leaf"><a title="" href="xxx">xxx</a></li>
<li><a class="active-trail active" title="" href="yyy">yyy</a></li>
<li class="last leaf"><a title="" href="zzz">zzz</a></li>
</ul>

```

I want it to be rendered as for a particular menu:

```
<ul class="side-menu">
<li><a href="xxx">xxx</a></li>
<li class="active"><a href="yyy">yyy</a></li>
<li><a href="zzz">zzz</a></li>
</ul>

```

So I have the following in my template.php

```
function mymod_menu_tree__menu_about_us($variables) {
  return '<ul class="side-menu">' . $variables['tree'] . '</ul>';
}

function mymod_menu_link__menu_about_us(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $class = "";
  $classes_of_this_li = $element['#attributes']['class'];
  if (in_array($classes_of_this_li, 'active-trail')) {
    $class = 'active';
  }
  $output = l($element['#title'], $element['#href']);
  return '<li class="' . $class . '">' . $output . $sub_menu . "</li>\n";
}

```

The ul is rendered as i want it to be. But the active class for the li is never there. Something must be wrong with below part

```
if (in_array($classes_of_this_li, 'active-trail')) {
    $class = 'active';
  }

```

Any idea?

# Answer
Try switching the parameters to `in_array`. `in_array` takes the `needle` first and the `haystack` (array) second.

*Edit: unless that was a typo...*

**Edit**

PHP Docs for `in_array()`.

> ```
> bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
>
> ```
>
> Searches haystack for needle using loose comparison unless strict is set.
> 1 votes

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


# Question
Title: Stop Mini Panels adding --1/2/3 etc to blocks
I'm using mini panels in a build and am annoyed that when using a mini panel it adds for example a --1 to the block id in the HTML which makes it really hard to style with CSS.

Is there a way to turn this off so I just get the original block ID?

# Answer
Drupal blocks aren't particularly aware of other blocks on the page, and you could legitimately have a mini panel block added with Panels and another of the same added somewhere else with Drupal's regular block system or some other display module - they would be completely unaware of each other and therefore without the appended numbers could end up with the same ID. Certain things in Javascript can break if two elements on a page have the same ID, so it's pretty important to make sure this can't happen.

The best way to get a good stable clean ID for styling purposes is to add the mini panel block using something with the panels/context interface (panels or page manager (comes with ctools, under Structure \> Pages in menu) or panels everywhere etc), and use the block settings option to set an id that is specific and semantically relevant. It takes slightly longer in the short term, but saves a lot of trouble in the long term and gives you cleaner, more readable, more manageable HTML.

Generally speaking, replacing Drupal's default generated markup with clean lean semantic markup is a good idea (if somewhat tedious and time consuming). Remember that Drupal's default auto-generated markup is intended for stability and flexibility in development more than it is for best practices in production. See also this similar common complaint about messy markup: Changing the HTML produced by Panels: Is it possible?
> 0 votes

---
Tags: panels
---


# Question
Title: Why is the content of existing blocks not editable?
I have inherited the Administration of a *Drupal 6* site with major funkiness going on. In this case I can't even figure out where to look.

There are a few dozen blocks configured and for the most part they are displaying what they are supposed to. However, a few of them are either blank or need tweaking. When I go to the block admin page, I am able to configure the blocks and bring up the `Block specific settings` tab, however the normal fields are all missing. Only `Block Title` shows up and that appears to be blank across the board.

Strangely enough, if I go to add a new block of my own, the form shows up correctly with all the fields.

What could cause these fields to not be displayed for existing blocks or where would I find the content of these blocks to be edited?

# Answer
I suspect that the blocks that are doing this are made via hook\_block and not with the block UI (ie, admin/build/block/add). I just checked a Drupal 6 site that I did a while ago, and all of my custom blocks have this behavior.

The **Configure** link for each custom block should contain the module name that defined it, along with the delta. For example the "Who's online" block has this for the configure link:

> admin/build/block/configure/user/3

It is defined in user.module and if you look at user\_block you will see that the `$delta` for this is 3.
> 5 votes

---
Tags: 6, blocks
---


# Question
Title: How woud you plan a sector directory with Drupal?
I have to realize a sector directory, a directory of restaurants, bars, wineyardsm, carpenter...

So each sector has it's own properties like the menu card or something else. But there are properties like the name, address, telephone number etc. which are the same in for each sector.

I thougt to realize it so: 1 node type: Business (Fields: title, address, city, telephone number...); for each sector one content type with the special fields like the menu card or the wine list; to connect these two nodes i thougt to use the Relation module

What do you think of my plan? Is it used to do it like this or are there other solutions? One problem of my plan would be the backend. I have to edit/create two nodes for one business. For the normal user it would be too complicate. Is there a way to edit the connected node on the same page?

Thanks

# Answer
> 1 votes
Reference entity http://drupal.org/project/entityreference will let you make all the relations you need.

Also, instead of use node I will create my own entities (http://www.istos.it/blog/drupal/drupal-entities-part-1-moving-beyond-nodes) and all the connections with views.

And remember that taxonomies also are Entities, so you can create a Vocabulary that it's "Sector", and every Sector add all the fields you need.

It'll harder but it'll improve the performance.

Oskar

---
Tags: entities
---


# Question
Title: Is there a way to hook rebuild permissions?
I'm working on a module that works with nodeaccess\_userreference, I have to add some actions to the rebuild permissions function of the core. Is it possibile?

# Answer
> 2 votes
For Drupal 7, the submit handler for admin/reports/status/rebuild is `node_configure_rebuild_confirm_submit`, which calls `node_access_rebuild`. Just note that `node_access_rebuild` can take a while (and why it support batch mode).

---
Tags: users
---


title: Node loses title on submit

text:
# Question
Title: Node loses title on submit
I am creating a custom module that allows for users to create blog posts that will be private and related to a project. So I created a new content\_type called "tasker\_blog" that just has a title and body. The user goes to view their projects and clicks a link which takes them to 'tasker\_project/%/blog' % being the id of the project. I have the form being displayed correctly but when I submit the form I have two problems, 1) the title is lost on submit 2) getting this error: EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids().

Here is the code I have written (some non-relevant parts taken out).

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

    $items['tasker_project/%/blog'] = array(
        'title' => 'Private Blog Post',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('tasker_project_blog_form',1),
        'access arguments' => array('view tasker projects'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function tasker_project_blog_form($form, &$form_state) {
    drupal_add_css(drupal_get_path('module', 'tasker_project') . '/tasker_project.css');
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'tasker_blog',
        'language' => 'und',
    );
    node_object_prepare($node);

    $form = drupal_get_form('tasker_blog_node_form',$node);
    $form['hidden_project_id'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

    return $form;
}

```

If I submit with nothing else added I get the error I mentioned above. If I add this (using Kint to display variables):

```
function tasker_project_node_validate($node, $form, &$form_state) {
    s($_REQUEST);
    s($form_state['values']);
    die();
}

```

$\_REQUEST array output:

```
array (9) (
    'title' => string (4) "test"
    'body' => array (1) (
        'und' => array (1) (
             array (2) (
                'format' => string (13) "filtered_html"
                'value' => string (13) "<p>test</p>
"
            )
        )
    )
    'changed' => string (0) ""
    'form_build_id' => string (48) "form-eKWwyFlBOzi4LsajaAiEZBG7J0uOSI1UDVIhiDomeJE"
    'form_token' => string (43) "N421-IiWecixBJGbxTHGcJAIrd6ZutzAW0LAtVSsrJ4"
    'form_id' => string (24) "tasker_project_blog_form"
    'hidden_project_id' => string (2) "10"
    'additional_settings__active_tab' => string (0) ""
    'op' => string (4) "Save"
)

```

$form\_state\['values'\] array output:

```
array (27) (
    'nid' => NULL
    'vid' => NULL
    'uid' => string (1) "5"
    'created' => integer 1347038959
    'type' => string (11) "tasker_blog"
    'language' => string (3) "und"
    'changed' => string (0) ""
    'title' => string (0) ""
    'additional_settings__active_tab' => string (0) ""
    'revision' => bool FALSE
    'log' => string (0) ""
    'name' => string (10) "ndenlinger"
    'date' => string (0) ""
    'status' => integer 0
    'promote' => integer 0
    'sticky' => integer 0
    'submit' => string (4) "Save"
    'preview' => string (7) "Preview"
    'body' => array (1) (
        'und' => array (1) (
             array (3) (
                'summary' => string (0) ""
                'format' => string (13) "filtered_html"
                'value' => string (13) "<p>test</p>
"
            )
        )
    )
    //...MORE HERE REMOVED SINCE NOT RELEVANT
)

```

So I'm not sure if the two problems are related or not. Once the node is saved I am going to add a row to a custom table that store the nid and the project\_id.

# Answer
Found the solution in case anyone else ever has this issue:

```
    drupal_add_css(drupal_get_path('module', 'tasker_project') . '/tasker_project.css');
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'tasker_blog',
        'language' => 'und',
    );
    node_object_prepare($node);
    $form_state['build_info']['args'] = array($node);

    $form = drupal_retrieve_form('tasker_blog_node_form', $form_state);
    drupal_prepare_form('tasker_blog_node_form', $form, $form_state);
    $form['hidden_project_id'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

```

I used drupal\_retrieve\_form and drupal\_prepare\_form and everything seems to work correctly now. Not sure why drupal\_build\_form or drupal\_get\_form don't work correctly.
> 1 votes

# Answer
Test this

```
function tasker_project_blog_form($form, &$form_state) {
drupal_add_css(drupal_get_path('module', 'tasker_project') . '/tasker_project.css');
global $user;
module_load_include('inc', 'node', 'node.pages');
$node = new stdClass();
$node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => 'tasker_blog',
    'language' => 'und',
);
node_object_prepare($node);

$form = drupal_get_form('tasker_blog_node_form',$node);
$form['hidden_project_id'] = array(
    '#type' => 'hidden',
    '#value' => arg(1),
);

return $form;

```

}
> 0 votes

---
Tags: nodes, forms
---


title: How to list articles in user node

text:
# Question
Title: How to list articles in user node
On the user node page, how to automatically show the articles posted by the user?

# Answer
> 2 votes
In short, the Views module can be used to do that. This question and answer from the main StackOverflow site covers the same issue, including a link to a tutorial with more details.

Start by installing the Views module. Create a new view to list content. Under the Advanced section for the view, add UID as a contextual filter. From there, you can either create a block display or a page display, to output the view. If you add a page display, you could have it appear as a tab on the user's page, by setting it as a "Menu tab."

# Answer
> 1 votes
**Note:** user page is not a node; it is stored in different tables and not in *node* or *node%*.

I'm assuming you want to list the articles that a user creates on his/her user page. Drupal core has a module called **Tracker** which does exactly what you want. Enable it and you'll be able to see the articles a user creates on the url http://drupalsite.com/user/%uid/track (%uid being the userid of the user).

---
Tags: nodes, users
---


# Question
Title: hook_taxonomy_term_update(), where does it get invoked in drupal's core code?
I looked after a `module_invoke_all('taxonomy_term_update')` in the taxonomy module (and more in the entire Drupal core) but I didn't find anything.

Where does that hook get invoked in the code?

# Answer
It's invoked from `taxonomy_term_save()`.

The reason you can't find it is because the hook gets invoked via an interpolated string, depending on the current operation (insert or update):

```
module_invoke_all("taxonomy_term_$op", $term);

```
> 3 votes

---
Tags: 7, taxonomy-terms, hooks
---


# Question
Title: What is the proper format for the flag service calls?
I'm running Drupal 7 with the Services 3 and the Flag Service modules installed. I'm having trouble trying to figure out how to format the the call in REST format. Can someone provide a short example?

# Answer
The flag service module (and probably the others you've listed in your comments) define their resources as actions, so you access them at a URL like:

```
http://server/[endpoint]/[module]/[action].json.

```

So for the flag action provided by the flag module that would be something like:

```
http://server/endpoint/flag/flag.json

```

This little snippet works well for me, based on a REST server with no authentication turned on and an endpoint with the path 'api':

```
$url = 'http://server-name/api/flag/flag.json';

$args = array(
  'flag_name' => 'bookmarks',
  'content_id' => 8,
  'action' => 'flag',
  'uid' => 1,

  // You wouldn't normally want this, the flag module provides it as an override
  // but it's a security risk. With proper authentication you can safely remove it.
  // I'm just using it for testing.
  'skip_permission_check' => 1
);

// Perform the curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($args));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($curl);

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

curl_close($curl);

if ($http_code == 200) {
  // Success
}

```

Answering the original question (*What is the proper format for the flag service calls?*), it's simply a matter of calling the correct URL and POSTing the required arguments to it, from whatever programming language you might be using.
> 7 votes

---
Tags: 7, services, flags
---


title: What to change in .htaccess?

text:
# Question
Title: What to change in .htaccess?
I am installing Drupal 7 on a subdomain example.com/exampledev2 and I am running into problems with .htaccess. Meaning when I put the files in the root for the first time I get a 500 Internal Server Error, but if I rename it to .htaccess\_off or something I can begin installation. Then when I get to the last step, after filling in the site info and creating a user, I click the continue button and I get a Error 500 Internal Server error. I am assuming this has something to do with having .htaccess no longer working, but I can't turn it on, or I get the error before installation. Any advice on how to change the file so I can use it?

EDIT: This is the .htaccess file that finally worked for me:

```
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /mysite
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
  # Serve gzip compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

```

EDIT: I think the problem was not totally the htaccess file. The file did "direct" me to a WSOD page if it wasn't fixed, but I don't think it was the reason that when I got to the end of the install process I got an Error 500 screen. I think this was cause by having incorrect access to the database? During the process of install I may have changed the password, and then not updated it in the install.php process. Anyways I got the site up and working and will give some credit to MPD because it is a good answer.

# Answer
> 3 votes
It sounds like you aren't actually running in a subdomain, but rather a subdirectory. If you really are in a subdirectory, you you need to have .htaccess read (line 98ish, without the leading #)

```
RewriteBase /exampledev2

```

A 500 error typically means that something went wrong with Apache and/or PHP. In general, it isn't a syntax error or anything else in code, but usually something configuration related.

The WSOD page should be some help. You really need to see the Apache error\_log to see exactly what went wrong.

If I had to guess, your setup is disallowing one or more directives in the .htaccess file. If you are on shared hosting, this is a real possibility.

Nearly everything in .htaccess is feature detected via `<IfModule>` directives, but there are a few things that may be disallowed. I have worked on systems where the `Options` can't be overridden. Try commenting out those lines. Drupal should still work, though there may be some security implications by not having the `Options -Indexes`.

If you comment out those lines, and everything works, then you need to talk to your sysadmin about how to fix this long term. Ideally, you shouldn't need (or want) to do that.

---
Tags: installation, .htaccess
---


# Question
Title: Term reference field: Checkboxes with add new textfield
I need to change the presentation of a Term reference field. Drupal 7 has 3 widget types:

* Select list
* Check boxes/Radio buttons
* Autocomplete term widget

I need to display check boxes to select 1 or many terms when adding a node, but I also need to display a textfield to allow adding new term.

The autocomplete term widget allows to choose existing terms and add new ones, which is the functionality I need, but what I exactly need is a list of checkboxes with the existing terms and the textfield below that allows adding a new term.

I've searched modules, but I can't find one that allows me to do this. Is there a module that performs this? If not, how do I do this in code? Is there any way to customize the widgets to create that functionality? Thanks.

# Answer
http://drupal.org/node/1208512#comment-5605324

It has been adapted from Select or other to support taxonomy term references.

It is a non-contrib module and you may need to tweak it to your taste, especially as it adds Other: to the term you have added. I just tried it out and that part needs to be fixed, but it shouldn't be difficult.
> 2 votes

---
Tags: taxonomy-terms, entities
---


# Question
Title: Organic Groups - how to display a summary view of members of the group based on a "company" field added to the user profile
I want to create a block to display on my organic group nodes that shows the number of members of the group summarized by a field in the user profile (company) for instance:

Company 1 (4) Company 2 (1) Company 6 (3)

I have played around with relationships adding a few trying to get the field I need and using the "(OG group) OG group: Og group ID" as a contextual filter-- I can get the field label (Company) to show up in the block view but the values don't show up

# Answer
I took the default OG Members view and cloned it (keep the original) and changed from user: name to my field user:company - added aggregation - in advanced settings in the other section - then had to change the contextual filter to use the GID from the active node. then played around with the aggregation to get it to work ... overall it does what I needed.

Lesson learned ... use the views you get from adding modules - smart people built them ;-)
> 1 votes

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


# Question
Title: Two 'add to cart' buttons using different attributes
I am using Ubercart 3 on Drupal 7 for my website.

How am I able to have two "Add to cart" button on a product page that use two different attributes? So for example I can have:

(Buy the large version) (Buy the small version)

Those two buttons match my attributes that I have set in the back, so customers can click on one of those and add the product to the cart directly.

# Answer
A. Enable Ubercart Cart Links (part of core). B. Add necessary attributes and make sure you have a default attribute set.

With UC cart links, you can perform the add-to-cart functionality with many different AND DYNAMIC arguments. Without making a new add-to-cart button using Form API or complicated setups.

You can,

* Add any quantity of any number of products to the customer's cart, with specific attributes and options for each added product, if applicable.
* Display a custom message to the user.
* Track the click for display on a store report.
* Empty the customer's shopping cart.
* Redirect to any page on the site.

Basically you make a URL that will, when opened, adds given items with given parameters to the current user's cart.

```
cart/add/e-p123_a1o2

```

See above link. When opened, it will first empty the cart (`e`), adds product/node ID 123 to the cart(`p123`) with attribute of ID 1 (a1) and that attribute's option ID 2 (`o2`).

You can see a very good help instructions on help section of uc\_cart\_links module's admin page (admin/help/uc\_cart\_links) .

You can build the URLs using Drupal's url() or l() functions.

Put these snippets in your node.tpl.php file of the product node type (node--product.tpl.php) where you want to display buttons.

```
<div id="buy-large">
<?php
 print l(
      t('Buy the large version'),
      'cart/add/'.$node->id.'_a101'
    );
  ?>
</div>
<div id="buy-small">
<?php
 print l(
      t('Buy the small version'),
      'cart/add/'.$node->id.'_a102'
    );
?>
</div>

```

if you are putting this code in a block or anywhere other than node.tpl.php or variants, change `$node->nid` to `arg(1)` . This `arg(1)` thing will only work if the button is being displayed in full content page. if you are placing these buttons in a View, replace `$node->nid` with the appropriate node ID by adding a node: ID field and tokens. If you want to see attribute and option IDs, go to attributes page and you will see the attribute/option ID which is a numeric one.

Good luck!
> 3 votes

---
Tags: ubercart
---


# Question
Title: how to use image for next previous link in pager in drupal 7
I am woking on drupal 7 I want to change link text and replace them with image. How can I achieve following:

* Is there any function in template.php to do so?
* Is there any way to overridden template to pager in custom theme?

# Answer
In template.php

```
function THEMENAME_pager($tags = array(), $limit = 10, $element = 0, $parameters = array()) {

}

```

http://api.drupal.org/api/drupal/includes!pager.inc/function/theme\_pager/7

For api please check above link you can overridden. also check below link.

In drupal 7, How to override theme\_pager?
> 1 votes

---
Tags: 7, paging
---


# Question
Title: How can I make a condition for currently viewed language on a template file?
I have a template called `page-my-view.tpl.php` that overrides a view page `my-view`.

I have directly put the title tags, description and h1 on this template file.

However I need different texts for these tags per language to avoid duplicated tags.

I have 2 languages on my site English and Japanese. Japanese is the default one with no prefix and English is with prefix "en".

So how can I make a condition on this template for currently viewed language?

# Answer
In your template file global variable `$language` is avaible,with below properties

**'language' =\> 'en',
'name' =\> 'English',
'native' =\> 'English',
'direction' =\> 0,
'enabled' =\> 1,
'plurals' =\> 0,
'formula' =\> '',
'domain' =\> '',
'prefix' =\> '',
'weight' =\> 0,
'javascript' =\> ''**

You can achieve your jobs with something like this // if global variable $language not avaible uncomment first line

```
 //    global $language;
if ($language->language == 'en') {
   // do your desires
  }

```
> 0 votes

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


# Question
Title: use an inline javascript function (not jquery) on drupal 7
This is how jQuery is included in d7

```
(function ($) {
  // jquey codes here
})(jQuery);

```

How i can include javascript code (not jquery) in d7?

# Answer
If you want to write a plain JavaScript instead of JQuery, You can proceed with normal function declaration like

```
function sample() {
}

```

and go ahead. It is normal way of the doing things in javascript, More over jQuery is a framework of javascript and as said you can add js files in the traditional way

```
drupal_add_js()

```
> 5 votes

# Answer
jQuery is just a JavaScript library, so you can include plain JS inside the jQuery wrapper and it'll work fine. All the wrapper does is allow you to use the `$` sign for jQuery instead of having to write `jQuery('.xyz')`.

See the following example - standard JS inside a Drupal behaviour.

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      var ip = '<!--#echo var="REMOTE_ADDR"-->';
      alert("Your IP address is" + ip);
    }
  };

})(jQuery);

```

The Managing JavaScript in Drupal handbook page has LOADS of useful information about JavaScript in Drupal, it's definitely worth a read.
> 3 votes

# Answer
This is how jQuery is included so you can use the $ symbol. But you can write any piece of js code in that file without this part:

```
(function ($) {
  // jquey codes here
})(jQuery);

```

But to include files, you can simply use `drupal_add_js()` in code, `scripts[] = script.js` in `your_module.info` or use `$form['#attached']['js'][] = 'script.js'` in a form array.
> 2 votes

# Answer
You can do that by implementing `drupal_add_js()` in your custom module.

```
<?php
  drupal_add_js(drupal_get_path('theme', 'mytheme') .'/mytheme.js');
?>

```

Also you can add the files in your `MODULE.info` file by adding
`scripts[] = youjsfile.js`
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Prevent hook_form_alter to works only on frontend not in admin?
I have used a hook\_form\_alter to alter a form fields value randomly and its working fine, but the problem is that when i open this webform in admin panel its just change the value which i dont. Its should keep the same value which is submitted by frontend user. i want this hook to work in case of frontend only not for admin.

# Answer
If you have multiple admins, then check with user role, lets have admin\_role as a Admin role

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

  if(in_array('admin_role', $user->roles)) {
    return;
  }
 else {
    //alter fields logic goes here
  }
}

```
> 2 votes

# Answer
you could use the global variable `$user` to achieve it.

```
<?php

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

  if($user->uid == 1) {
    return;
  }
  else {
    //alter fields logic goes here
  }
}

```
> 2 votes

# Answer
you should implement some check for the user roles of admin like this.

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

  $adminroleid = 1 ; // It should be id for admin role, you should change this according to your's admin role id.

  if(array_key_exists($adminroleid, $user->roles)) {
    return;
  }
 else {
    // write your's form alter fields logic here .
  }
}

```
> 2 votes

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


# Question
Title: Use hook_menu_alter to change access callbacks
I'm trying to working with hook\_menu\_alter, I'm tryng to change, for example, access callback to an admin path (admin/config/account/people/fields).

I've create a permission and I've added to a role. Now I'm trying this:

```
function mymodule_menu_alter(&$items) {
   $items['admin/config/people/account/fields']['access arguments'] = array('my custom permission');
}

```

But it doesn't work.

Can I edit this "system" modules permissions?

# Answer
Your code is correct (that's definitely the way to override the access arguments for a path using `hook_menu_alter()`).

If it's not working you just need to clear your caches (and of course make sure that your custom module is installed and enabled).

I just copied your code into a test site, cleared the caches, and no longer receive 403 errors when visiting that page as an anonymous user.
> 6 votes

# Answer
You should not edit any core modules of Drupal. It will result in broken upgrade path of drupal instance.

It is always suggested not to edit any core module.

The menu path you are trying to alter doesn't exist in Drupal 7. Not sure what you are looking for.
> 0 votes

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


title: Simple Back button?

text:
# Question
Title: Simple Back button?
I was using window.history.back() ,

```
<a href="#" onclick="goBack()">Back</a>

```

and

```
<script>
function goBack(){
  window.history.back();
}
</script>

```

but it is not working in d7

# Answer
Using jQuery we can

```
(function ($) {
  // Go back
  $('a.back').click(function(){
     parent.history.back();
     return false;
  });
})(jQuery);

```

and add class="back" to your link

```
<a href="#" class="back">Back</a>

```
> 1 votes

# Answer
If you don't want to rely on javascript, you could use `referer_uri()` in Drupal 6. I'm not sure about the Drupal 7 equivalent but I'll update this when I find it.

**Edit:** It would seem as referer\_uri only returns `$_SERVER['HTTP_REFERER'];` anyways which isn't really that reliable. It could however be used with the javascript version as a fallback plan. That way, you'll get some of those with javascript disabled.
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Embedding Views programmatically getting argument overridden title
I'm embedding a View inside my custom module, using views\_embed\_view

From the docs for this function:

> Note that this function does NOT display the title of the view. If you want to do that, you will need to do what this function does manually, by loading the view, getting the preview and then getting $view-\>get\_title().

However, my View has no title, instead I've set my contextual filter to override the title (from the arguments in the url). How do I get this title?

Thanks

Edit: Here is a screengrab of my contextual filter settings. I'm actually currently using the default taxonomy\_term view that comes with Views out of the box.

# Answer
Okay I got it...

After executing the view in your code (e.g. with a $view-\>preview()). You need to find the argument in the view that sets the title, and then call set\_title() on it.

Here's what I did (note that I'm assuming that in the case of multiple arguments setting titles it's the last one that works, hence the array\_reverse, haven't tested this yet).

```
<?php
$view = views_get_view('taxonomy_term');
$view->preview('panel_pane_1', array($tid));
foreach (array_reverse($view->argument) as $argument) {
    if ($argument->options['title_enable']) {
        $page_title = $argument->get_title();
        break;
    }
}
?>

```

Hope that helps someone else out.
> 0 votes

---
Tags: views
---


# Question
Title: Errors after migrating a Drupal 6 to Pressflow
After I migrated a Drupal 6 site to Pressflow, my page started to show the following error messages:

> Notice: Undefined variable: split\_sub\_menu in st\_core\_preprocess\_page() (line 58 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Strict warning: Declaration of views\_handler\_filter::options\_validate() should be compatible with that of views\_handler::options\_validate() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc).
> Strict warning: Declaration of views\_handler\_filter::options\_submit() should be compatible with that of views\_handler::options\_submit() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc).
> Strict warning: Declaration of views\_handler\_filter\_boolean\_operator::value\_validate() should be compatible with that of views\_handler\_filter::value\_validate() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc). Strict warning: Declaration of views\_plugin\_style\_default::options() should be compatible with that of views\_object::options() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc).
> Strict warning: Declaration of views\_plugin\_row::options\_validate() should be compatible with that of views\_plugin::options\_validate() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc).
> Strict warning: Declaration of views\_plugin\_row::options\_submit() should be compatible with that of views\_plugin::options\_submit() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc).
> Notice: Undefined offset: 1 in custom\_breadcrumbs\_home\_crumb() (line 541 of C:\xampp\htdocs\pressflow\sites\all\modules\custom\_breadcrumbs\custom\_breadcrumbs.module).
> Notice: Undefined offset: 1 in \_custom\_breadcrumbs\_create\_crumb\_items() (line 574 of C:\xampp\htdocs\pressflow\sites\all\modules\custom\_breadcrumbs\custom\_breadcrumbs.module).
> Notice: Undefined offset: 1 in \_custom\_breadcrumbs\_create\_crumb\_items() (line 582 of C:\xampp\htdocs\pressflow\sites\all\modules\custom\_breadcrumbs\custom\_breadcrumbs.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Notice: Undefined offset: 1 in custom\_breadcrumbs\_home\_crumb() (line 541 of C:\xampp\htdocs\pressflow\sites\all\modules\custom\_breadcrumbs\custom\_breadcrumbs.module).
> Notice: Undefined offset: 1 in \_custom\_breadcrumbs\_create\_crumb\_items() (line 574 of C:\xampp\htdocs\pressflow\sites\all\modules\custom\_breadcrumbs\custom\_breadcrumbs.module).
> Notice: Undefined offset: 1 in \_custom\_breadcrumbs\_create\_crumb\_items() (line 582 of C:\xampp\htdocs\pressflow\sites\all\modules\custom\_breadcrumbs\custom\_breadcrumbs.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Notice: Undefined index: pager\_container in template\_preprocess\_ddblock\_cycle\_block\_content() (line 1643 of C:\xampp\htdocs\pressflow\sites\all\modules\ddblock\ddblock.module).
> Notice: Undefined index: pager\_event in template\_preprocess\_ddblock\_cycle\_block\_content() (line 1644 of C:\xampp\htdocs\pressflow\sites\all\modules\ddblock\ddblock.module).
> Notice: Undefined variable: count\_sidebar\_left in st\_core\_set\_regions() (line 373 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Strict warning: Declaration of views\_handler\_argument::init() should be compatible with that of views\_handler::init() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc).
> Strict warning: Non-static method views\_many\_to\_one\_helper::option\_definition() should not be called statically, assuming $this from incompatible context in views\_handler\_argument\_many\_to\_one-\>option\_definition() (line 35 of C:\xampp\htdocs\pressflow\sites\all\modules\views\handlers\views\_handler\_argument\_many\_to\_one.inc).
> Strict warning: Non-static method views\_many\_to\_one\_helper::option\_definition() should not be called statically, assuming $this from incompatible context in views\_handler\_argument\_many\_to\_one-\>option\_definition() (line 35 of C:\xampp\htdocs\pressflow\sites\all\modules\views\handlers\views\_handler\_argument\_many\_to\_one.inc).
> Notice: Undefined index: quicktabs\_tabpage in st\_core\_preprocess\_block() (line 212 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: count in st\_core\_preprocess\_block() (line 212 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: width in st\_core\_preprocess\_block() (line 229 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: width in st\_core\_preprocess\_block() (line 229 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined variable: count\_sidebar\_left in st\_core\_set\_regions() (line 373 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Strict warning: Declaration of views\_handler\_filter\_term\_node\_tid::value\_validate() should be compatible with that of views\_handler\_filter::value\_validate() in views\_include\_handler() (line 76 of C:\xampp\htdocs\pressflow\sites\all\modules\views\includes\handlers.inc).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Undefined index: content\_bottom\_home\_left in st\_core\_preprocess\_block() (line 212 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: count in st\_core\_preprocess\_block() (line 212 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: width in st\_core\_preprocess\_block() (line 229 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: width in st\_core\_preprocess\_block() (line 229 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Undefined index: content\_bottom\_home\_right in st\_core\_preprocess\_block() (line 212 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: count in st\_core\_preprocess\_block() (line 212 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: width in st\_core\_preprocess\_block() (line 229 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: width in st\_core\_preprocess\_block() (line 229 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined property: stdClass::$display\_handler in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Trying to get property of non-object in views\_admin\_link() (line 371 of C:\xampp\htdocs\pressflow\sites\all\modules\admin\admin.module).
> Notice: Undefined index: total in st\_core\_preprocess\_block() (line 214 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).
> Notice: Undefined index: width in st\_core\_preprocess\_block() (line 229 of C:\xampp\htdocs\pressflow\sites\all\themes\sttheme\st\_core\template.php).

# Answer
Is the site working apart from displaying those errors? They are all non-critical; you could set your error\_reporting value to not display E\_NOTICE and E\_STRICT
> 1 votes

# Answer
> Strict warning: Non-static method view::load() should not be called statically in view::load() (line 906 of C:\xampp\htdocs\pressflow\sites\all\modules\views\views.module).

for the above error you can write it as

```
 $r = new view();
 $view = $r ->load($name, $reset);

```
> 1 votes

---
Tags: views, 6
---


title: Compare fields and send a message

text:
# Question
Title: Compare fields and send a message
I want to compare a term\_reference field in a node with a term\_reference field in a user profile. If certain terms match, I want to message the users with those matching terms. Is this something that could be achieved with rules?

EDIT: This is my code so far:

```
dpm($node->field_project_resources);
dpm($node->field_project_resources['und']['0']['tid']);

$users = entity_load('user');
$arrayuids = array_keys($users);

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
    ->propertyCondition('uid', $arrayuids, 'IN');

$profile = $query->execute();

$arrayofpids = array();

foreach($profile as $obj){

     foreach($obj as $objinner)
     {
     array_push($arrayofpids, $objinner->pid);
     }

}
$profile2s = profile2_load_multiple($arrayofpids, FALSE);
foreach($profile2s as $obj){dpm($obj);
    foreach($obj as $objinner){
            if(is_array($objinner)){
           foreach($objinner as $i)
           {dpm($i);
                   foreach($i as $n)
                         {

                        }
           }}
    }
}

```

I want to compare for each value in array field\_project\_resources result with the profile2 array field of field\_resources for each user and then return an array of users that have matching fields. I am quite new to this and I would appreciate some help.

# Answer
> 2 votes
Yes, definitely something with rules together with http://drupal.org/project/mimemail (I would also recommend http://drupal.org/project/phpmailer together with mimemail), if you want to mail them, or use the https://drupal.org/project/messaging framework and notifications or similar.

You can use rules scheduler to do this on a schedule or use rules events such as "After saving a new term" to trigger the lookup when a term is saved. The tricky part is the conditions/actions of looking up.

You can use the data comparison condition together with a php evaluation to lookup the user profile/term and then generate an action of sending a mail.

Or you may need to use fetch entity by id/property depending on what you have available to the situation to load the node and the same for the user profile, and then compare those results in a php custom action.

The last option is to use views bulk operations to do the lookup for you and then load the list in the rule using the views bulk operations action.

# Answer
> 0 votes
This is my code so far. I load a list of user profiles using view bulk operation, which made things a lot simpler.

```
<?php

//create an array for the project resources because there may be many

$arrayofprojectresources = array();
array_push($arrayofprojectresources, $node->field_project_resources['und']['0']['tid']);

$usersprofidstonotify = array();

//for each profile
foreach ($entity_list as $obj) {

    //drupal_set_message('pid');
    //dpm($obj->pid);
//make a new array with the profile field resources in
    $profile1 = $obj->field_resources['und'];

//for each inside the 'und' array
    foreach ($profile1 as $innerar) {

//go through each resource in project resource

        foreach ($arrayofprojectresources as $oneresource) {

//see if that resource is in the array of profile resources

            if (in_array($oneresource, $innerar)) {

                //drupal_set_message('the resource');
                //dpm($oneresource);
                //drupal_set_message('is in');
                //dpm($innerar);
                array_push($usersprofidstonotify, $obj->pid);
            } else {
                //drupal_set_message('the resource');
                //dpm($oneresource);
                //drupal_set_message('is not in');
                //dpm($innerar);
            }
        }
    }
}
$useridstonotify = array();
//for each of the profiles
foreach ($entity_list as $obj) {
//check for each of the usersprofilestonotify
    foreach ($usersprofidstonotify as $user) {
        if (($obj->pid) == ($user)) {
            //dpm($obj);
            //dpm($obj->pid);
            //drupal_set_message('is equal to');
            //dpm($user);
            //drupal_set_message('so send message to');
            //dpm($obj->uid);
            array_push($useridstonotify, ($obj->uid));
        }
    }
}

$arrayofprojectresourcenames = array();
array_push($arrayofprojectresourcenames, $node->field_project_resources['und']['0']['name']);

$usersprofidstonotify = array();

//dpm($node);

$name = dpm($node->name);
$resources = array();
$msg = $name;
$msg .= ' has posted a project called ';
$msg .= ($node->title);
$msg .= '</br>';
$msg .= '</br>';
$msg .= 'More details:';
$msg .= ($node->body['und']['0']['value']);
$msg .= '</br>';
$msg .= ' They need a ';
$msg .= implode(",", $arrayofprojectresourcenames);
$msg .= '</br>';
$msg .= 'Can you help them out? ';
$msg .= '</br>';
$msg .= ' If so, please sign up ';
$msg .= '<a href="' . '/node/' . ($node->vid) . '">' . 'here</a>';
//drupal_set_message($msg);
//drupal_set_message('users to notify:');
//dpm($useridstonotify);
foreach ($useridstonotify as $oneuser) {
    privatemsg_new_thread(array(user_load($oneuser)), 'Someone needs your resource', $msg);
}

```

---
Tags: rules
---


# Question
Title: Saving the module configuration form data
I am using Drupal 7.

I want to create an add-on module for Entity External Rating module.

In that I want to give the form to users where users can select the content types, and based on that selected content type links of twitter and facebook will be displayed. i.e if I select '**article**' content type then facebook and twitter links will be displayed on that content type only.

I have created an admin file and configuration form, but i am not sure where should I store the selected values.

I have added the code below which will display the form with listing of all the content types.

```
function entityrating_addone_admin_settings() {
$form['entityrating_addone_content_type'] = array(
        '#type' => 'fieldset',
        '#title' => t('Select content type for Entity Rating'),
        '#description' => t('Define title excluding settings for each content type.'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
);

$node_types = _node_types_build()->names;
foreach ($node_types as $node_type => $node_type_label) {
    $form['entityrating_addone_content_type']['entityrating_addone_content_type_value_' . $node_type] = array(
            '#type' => 'select',
            '#title' => $node_type_label,
            '#default_value' => variable_get('entityrating_addone_content_type_value_' . $node_type, 'none'),
            '#options' => array('none' => t('None'), 'all' => t('All nodes'), 'user' => t('User defined nodes')),
    );
}
return system_settings_form($form);

```

}

Above code will display the list of all the content type for configuration, but i don't know where to store this values, so i can retrieve while displaying node.

# Answer
The form elements saved above will all be stored in the variables table.

Are you wanting to move this data or store it somewhere else? If not, then your answer is already in your code with the `variable_get()` default value.

`system_settings_form()`

> Add default buttons to a form and set its prefix.

System settings form will store your form data in the variables table and key it with the name of the form element. For example, a form element defined as `$form['foo']` will be retrievable by using `variable_get('foo', NULL)`. Because of this I always figure it's a good idea to namespace your form elements as you would functions (i.e. `$form['mymodule_foo']`)
> 1 votes

---
Tags: 7
---


# Question
Title: Conditional drupal_add_css and _js are adding code to every page
I am trying to add a CSS and JS files when a certain content type is being viewed (Drupal 6). The problem is that the code is being added to every page.

I have tried this first, included in template.php:

```
function phptemplate_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if ($node->type == 'mytype') {
        drupal_add_css(path_to_theme() . "/css/mytpess.css");

        drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
        drupal_add_js("$(document).ready(function(){
                          $('.node').masonry({
                            itemSelector: '.field-type-flexifield'
                          });
                        });",'inline');
  }
}

```

Then I moved it out of there and placed it in node-mytype.tpl.php:

```
drupal_add_css(path_to_theme() . "/css/mytpess.css");

drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
drupal_add_js("$(document).ready(function(){
                  $('.node').masonry({
                    itemSelector: '.field-type-flexifield'
                  });
                });",'inline');

```

But either way it gets added to every page. How can I resolve this?

# Answer
> 3 votes
If you are adding drupal\_add\_css or\_js in phptemplate\_preprocess\_node,

1. First fetch all the added css in one variable and assign this for $styles value
2. Same like css you need to do for js also.

Here with see the sample code below

```
function phptemplate_preprocess_node(&$vars, $hook) { $node = $vars['node'];
if ($node->type == 'mytype') {
    drupal_add_css(path_to_theme() . "/css/mytpess.css");

    drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
    drupal_add_js("$(document).ready(function(){
                      $('.node').masonry({
                        itemSelector: '.field-type-flexifield'
                      });
                    });",'inline');
 }
$css = drupal_add_css();
$scripts = drupal_add_js();
$vars['styles'] = drupal_get_css($css);
$vars['scripts'] = drupal_get_js('header', $scripts);
}

```

# Answer
> 2 votes
You can use http://api.drupal.org/api/drupal/developer!hooks!node.php/function/hook\_view/6 hook\_view in custom module to do this.

For example if your module name is "example" then function should be

```
function example_view($node, FALSE, TRUE) {
  if ($node->type == "mytype") {
    drupal_add_css(path_to_theme() . "/css/mytpess.css");
    drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
  }
}

```

# Answer
> 1 votes
Isn't `template_preprocess_node()` too late? Try using `template_preprocess_page()` instead. `$variables['node']->type` as usual.

```
function template_preprocess_page(&$vars) {
  if (isset($vars['node'], $vars['node']->type) && $vars['node']->type === 'mytype') {
    //ADD_JS
    //ADD_CSS
  }
}

```

**Edit:** as a sidenote, `template_preprocess_page` should be renamed to `THEME_NAME_preprocess_page` or `MODULE_NAME_preprocess_page`. Depending on where you place that function.

---
Tags: 6, theming, javascript
---


title: Date module is missing but it's exisit

text:
# Question
Title: Date module is missing but it's exisit
I have installed Date module since i made drupal installation, i built many date fields but Suddenly this message show up when i go to my content type's manage field page "Inactive fields are not shown unless their providing modules are enabled.

The following fields are not enabled:(here my date field and tell me date module is not enabled)"

When open modules page can't find date module but other sub modules exist like (date tools, date views ....)

I tried to recopy the date module and nothing change, date module still lost.

All my date fields disabled please help, thanks.

# Answer
Check the permissions and owners of the date module folder inside your sites/all/modules it should be same as others...

Check drupal watchdog logs for more information on errors....
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Create a Form in a Block using API that sends captured data to email
> **Possible Duplicate:**
> Send email of form data?

So I have a simple three field form which I've created in HTML/CSS, see here:

Now I want to put this into a block module, generate the form fields using Drupal Form API (is this appropriate or should I just stick with my existing HTML markup?). And on submission of the form I want it to email the details to a designated email. Is Drupal Triggers appropriate for this, if not, what is?

Any guidance on where to go with this would be amazing. Thanks so much for your time :)

# Answer
> 1 votes
The easiest way is to create the form using webform module. This will also send an email to a chosen address. Unfortunately this will create just a normal page, not a block.

To show it in a block you'll need to create a view that renders the whole webform (which is a node) or to use mini panels with the same rendered node.

# Answer
> 1 votes
Use simple news module which will give you lots of e-newsletter features out of the box.

For new features you can extend above module to suit your specific requirements.

# Answer
> 0 votes
There are several approaches to this problem,

* You can use "webform " module and theme it using $form\[theme\], your start can be here
* you can use Form API to create a custom form. Your good start is FORM API Guide
* To trigger a Mail on submission, you can use rules OR triggers OR just a submit function

---
Tags: 7, forms, blocks, rules
---


# Question
Title: User Not be Sent to Front Page after Submitting Contact Form
After submitting contact form (on contact page), the user automatically is sent (redirected) to front page. How can I avoid it? (user remain on contact page)

Thanks

# Answer
> 5 votes
You can use form\_state\['redirect'\] in your form alter,

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == ''contact_us_form) {
      $form_state['redirect'] = array('contact/us');
  }
}

```

# Answer
> 1 votes
Create a Rule on webform submission and redirect user to front page.

---
Tags: emails
---


title: Link a view to another view

text:
# Question
Title: Link a view to another view
I have a view block and I want to add a field link so that will displays a view of the content types that I have create not a content type itself is this possible?

# Answer
You can put almost anything you want in a Views Header or Footer, so if you added a Global Text Area field there, you could put in a link to a page display of a view that shows your content types, and that should do what you want.
> 4 votes

# Answer
If you want to display more detail you can use attachment option in views.
> 0 votes

---
Tags: views
---


# Question
Title: Colorbox grouping content linked from same page - how to stop it?
I have a page with two links on it that each open in Colorbox modals.

When I click on one of them, it opens them both, as if they were a gallery, with forward and back arrows to navigate between them.

I have looked through the Colorbox configuration options and I can't figure out how to stop this behavior.

# Answer
> 3 votes
I figured this out, with crucial help from the #Drupal IRC channel.

I was using Colorbox Node along with Colorbox, and I was confusing the documentation from the two of them. Specifically, Colorbox requires links to have the class `colorbox-load` while Colorbox Node requires that they have the class `colorbox-node`. The really confusing thing about this is that if you use `colorbox-load` instead of `colorbox-node`, it works, sort of. It was loading the *entire* page including headers, footers, and all markup and styles, into the modal, as if it were an iframe.

So step one was to start using the correct link class.

After changing the link class to `colorbox-node`, however, all I saw in the modal was the title of the target page, unstyled, on a white background. Poking around in the Colorbox settings was, unsurprisingly, unhelpful. Again, #Drupal pointed me in the right direction: Colorbox Node creates a display of the content type and makes the body hidden by default for some reason.

So step two was going to structure \> content \> \[content type of target node\] \> manage display and choosing "Colorbox" (next to "Default" and "Teaser") to unhide the body of the target node.

Voilá, you now have the title and body pulled out from your target node and appearing isolated in your Colorbox modal.

# Answer
> 1 votes
Not sure how you are using colorbox but if you have image fields in a content type there are setting under "manage display" after you change the field format to colorbox (save it and go back) and look for Gallery (image grouping)

---
Tags: nodes, ajax, media, javascript
---


# Question
Title: Getting $content of content type in template.php
I am trying to get form that is used in content type template in template.php. I am creating node collections with EntityFieldQuery, and I am pulling field values of content type without problem.

But i need to access form, and add it to html stream that i create in template.php

In content type i can do

```
print render($content['add_to_cart']);

```

To get form out.

But now in **template.php** i need that form for specific nodes (im pulling them with EntityFieldQuery) as html, so i can include it to rest of the stream and send the data in variable, and simply output it where i need it (content type page.)

Thanks!

# Answer
> 3 votes
I'm not sure, if this is what you are looking. But if you want to embed a node-add form you could use the following code.

```
<?php
$node = new stdClass();
$node->type = 'machine_name_of_your_content_type';
module_load_include('inc', 'node', 'node.pages');
$output = drupal_get_form('machine_name_of_your_content_type_node_form', $node);
print $output;
?>

```

# Answer
> 0 votes
Thanks to aerozeppelin, i implemented it this way:

in template.php ($node is fetched via EntityFieldQuery)

```
$add_to_cart = array( '#theme' => 'uc_product_add_to_cart',
'#form' => drupal_get_form('uc_product_add_to_cart_form_' . $node->nid, $node), );
$cart_form = drupal_render($add_to_cart);

```

where $cart\_form contains html data form, that i included in my data stream!

---
Tags: nodes, theming
---


# Question
Title: How do I sync taxonomy terms with the second level of a menu?
This question pops every time I create a new e-commerce site.

I have a horizontal main menu with Home, Products, Blog, etc... in it. I need to get the terms from my Product catalogue as the drop down menu underneath Products.

I use Taxonomy Menu to good effect elsewhere in the site, but I can't see any way of moving an entire Taxonomy Menu (or even a sub-set) to underneath a menu link in **another menu**.

My usual method is to hard-code a function into my theme (with appropriate caching of course), which builds up the sub-menu of terms. I then have to create another function to mimic the menu rendering functions, and inject the 'taxonomy menu' when my loop hits a certain menu link ID. Finally I use that function in place of the standard method of outputting menu links in my page template file.

Needless to say that's not a good method and it leaves me feeling dirty every time. I'd really prefer a more opaque method that keeps the menu in sync when terms in the vocabulary are changed.

It seems like this problem would have been solved over and over again, but my Google-fu is failing me.

Anyone got any good suggestions (that don't involve creating a View, which would be way too much overhead)?

I should also mention the lazy man in me is looking for a pre-built module to do this. It would be fairly trivial(ish) to implement the code on a case-by-case basis (see hampusn's comment below) but I'm hoping there's a generic module based solution available.

# Answer
> 2 votes
I used this on a site a few months ago to essentially do the same thing:

```
function _foo_add_submenu ($menu_name, $vid, $plid)
{
  $vocabulary = taxonomy_vocabulary_load($vid);
  $tree = taxonomy_get_tree($vid);

  if (count($tree) > 0) foreach ($tree as $term) {
    $item = array(
      "link_path" => "taxonomy/term/{$term->tid}",
      "link_title" => $term->name,
      "menu_name" => "menu-menu",
      "plid" => $plid,
      "router_path" => "taxonomy/term/%",
    );

    $sql = "
      SELECT menu_links.mlid
      FROM {menu_links} menu_links
      WHERE menu_name = :menu_name AND plid = :plid AND link_path = :link_path
    ";

    $result = db_query($sql, array(
      ":menu_name" => $menu_name,
      ":plid" => $plid,
      ":link_path" => $item["link_path"],
    ));

    $record = $result->fetchObject();

    if (isset($record->mlid) && $record->mlid > 0) $item["mlid"] = (int) $record->mlid;

    menu_link_save($item);
  }

  menu_cache_clear_all();
}

```

`$menu_name` is the menu to mess with, `$vid` is the vocabulary to build from, and `$plid` is the item to add to. When you run this, you will end up with a real menu in admin/structure/menu/manage/menu-whatever. You will need to add some additional housekeeping functions to handle adding terms, removing terms, etc, but they all involve similar functions and menu\_link\_save / menu\_link\_delete and menu\_cache\_clear or menu\_cache\_clear\_all being called from the right taxonomy hook.

---
Tags: 7, taxonomy-terms, routes
---


# Question
Title: How to programmatically modify an exposed filter?
I have an exposed filter on the Title field for my content type; i would like to use the same filter for applying the following condition: select all where (field\_value) like %node.Title% OR %author.Title% where Author is a term reference to an Author vocabulary. I've tried to do this but i wasn't able to solve it. How can i do it? Have tried using views\_query\_alter but without success.

# Answer
Maybe you should make a hook\_form\_alter to build only one box.

And in the validation or submit give the box value to both form\_state options.

Another options is to use hook\_query\_alter to build your own query.

Oskar
> 4 votes

---
Tags: 7, views
---


title: Show announcement on the site

text:
# Question
Title: Show announcement on the site
I want to be able to show an announcement on the site that requires a confirmation by the user before it disappears.

Something similar to Absolute Messages but I don't want to have all status messages shown that way.

# Answer
You can use jQuery for the this purpose. Simply use mouseover event on the announcement DIV. Write a jQuery function to hide this DIV using .hide method of jQuery. like this.

```
$(document).ready(function() {
$("#announcement_div_id").hover(function() {
$("#announcement_div_id").hide();
});
});

```

Here announcement\_div\_id is the id of the div which you want to hide.
> 2 votes

# Answer
I have heard that EU Cookie Compliance works well for one time messages. It is not limited to messages about cookies.
> 2 votes

# Answer
I have done this earlier. The way I achieved is via Jquery.

I added a special ID to the the messages I want this special way, else the other ID's were left to default. Now, if there is no special ID, then use .hide() to hide the div, else let the module do the rest.

Hope that helps.
> 0 votes

---
Tags: status-messages
---


title: Taxonomy Field(s)

text:
# Question
Title: Taxonomy Field(s)
In Drupal 6, is there an easy way to add fields to taxonomy terms where I can use them as flags in Views? Like a 'Hidden' field on a term, so that it is filtered out of a view presentation?

# Answer
> 3 votes
There is a module for Drupal 6 called Term Fields:

> Term Fields allows you to define fields for taxonomy terms in the same way that CCK allows you to define fields for nodes.

The project page also claims views integration. I have only done initial testing with this, but it looks promising and is still being actively worked on.

# Answer
> 1 votes
No, no easy way in drupal 6 from what I've found, unfortunately. You need to write your own module, add the checkbox to the term edit page and expose your custom data to views :/

---
Tags: 6, taxonomy-terms
---


# Question
Title: How to acess node object in hook_form_alter
I am trying to access the node object in `hook_form_alter()`, but it throws the following error:

> Notice: Undefined index: #node in `themename_form_alter()`

The code I am using is the following.

```
function themename_form_alter(&$form, $form_state, $form_id)) {
  $node = $form['#node'];
}

```

Is there any way to access the node object in `hook_form_alter()`?

# Answer
> 8 votes
Not all the forms contains a reference to a node. It is just some node forms which contain a node object, but `hook_form_alter()` is called for every form being output from Drupal.

What you need to do is the following:

* Check `$form['#node']` is set

```
if (isset($form['#node'])) {
  // …
}

```
* Use a different hook, such as `hook_form_node_form_alter()` if you want to alter the node edit form for any content type, or `hook_form_$type_node_form_alter()` for the node edit form of the `$type` content type

---
Tags: 7, nodes, forms
---


# Question
Title: Disclaimer screen when adding new content
I'm looking for a way to have a disclaimer page/popup be a part of creating a certain type of content, in this case a OG group. Is this something that could somehow be done with Webforms?

I found http://drupal.org/project/legal but it just doesn't quite do the trick... Any other ideas? :)

# Answer
One way to accomplish this would be to make a small custom module utilizing hook\_form\_alter(). Substitute "example" with your module name to implement.

example.module

```
/**
* Implementation of hook_form_alter()
* Add Disclaimer Message to Article Create Form
*/
function example_form_article_node_form_alter(&$form, $form_state) {
  if (arg(1) == 'add') {
    drupal_set_message('Legal Disclaimer: By filling out this form you are agreeing.','warning');
  }
}

```

example.info

```
name = "Example module"
description = "Adds a disclaimer to node/add/article page."
package = Example
core = 7.x

```

Or if you want a popup, you could instead use drupal\_add\_js and a little Javascript

example.module

```
/**
* Implementation of hook_form_alter()
* Add Popup Disclaimer to Article Create Form
*/
function example_form_article_node_form_alter(&$form, $form_state) {
  if (arg(1) == 'add') {
    drupal_add_js(drupal_get_path('module', 'example').'example.js');
  }
}

```

example.js

```
// if user agrees continue, else redirect
if (!window.confirm('Legal Disclaimer: Press OK if you agree.')) {
  window.location.href='http://example.com';
}

```

Of course this is all pretty simple and ugly. One could combine both approaches and using CTools Modal or JQueryUI build a prettier dialog. With JQueryUI you might do:

example.js

```
// if user agrees continue, else redirect using JQueryUI
// requires JQueryUI loaded (you can use [drupal_add_js()][5] for this too).
(function ($) {
  $(document).ready( function() {
    $("<div><h3>Legal Disclaimer</h3><p>Do you agree?</p></div>").dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "I Agree": function() {
          $( this ).dialog( "close" );
        },
        "No Way": function() {
          $( this ).dialog( "close" );
          window.location.href='http://example.com';
        }
      }
    });
  });
});

```
> 0 votes

---
Tags: nodes, webforms, organic-groups
---


# Question
Title: Images instead of radio buttons or dropdown list?
I would like the user to choose the category when he creates a new node content. However, instead of radio buttons or dropdown list I would like to have selectable images, with exactly the same logic. Is it possible to somehow ovveride radio buttons / dropdown lists with options being displayed as images? So, for example instead of a radio button with 'Cars' label I would like to have a picture of a car, then for the next category another picture, etc. Any advice appreciated.

# Answer
You can accomplish this with a combination of a little JQuery and CSS.

Here's some starting points

Then use a custom module to load the JS when needed using drupal\_add\_js() typically instantiated with a hook\_form\_alter().

Something like this:

```
/**
* Add example.js to content type 'car' create/edit form for example.module
*/
function example_form_alter(&$form, $form_state, $form_id) {
if ('car_node_form' == $form_id) {
  drupal_add_js(drupal_get_path('module', 'example').'example.js');
}

```

You can find more examples for detecting different forms and patterns on the hook snippets page.
> 3 votes

---
Tags: 6, nodes
---


# Question
Title: Image upload functionality for drupal 7 content
I am using CKEdtor and i want image uploading functionality in drupal 7. What is the solution for that ?

# Answer
> 3 votes
Install the IMCE file browser module. This will let you integrate direct file uploading while editing content, which of course includes images as well. Follow the directions on the module's homepage for linking it with CKEditor.

---
Tags: 7, wysiwyg
---


# Question
Title: Organic groups chat - what are my options?
I have several organic groups which has members added. I want to a chat system that allows members within the same group to communicate amongst each other.

What modules can i do to achieve this? what are my options? I am running drupal 6.

# Answer
I think DrupalChat might integrate with Organic Groups. According to Issue#871238 the patch in comment#2 adds this functionality.

The patch looks like it was committed to the dev branch on January 21, 2012. With the release dates of the beta11 version and the latest dev version, it looks like it might already be in those respective releases. If not, try the patch mentioned above.
> 1 votes

---
Tags: organic-groups
---


# Question
Title: How to have a drupal module respond on node creation
I am trying to convert some of my rules to a custom module for more flexibility and better configuration.

However, I am stuck; I want my module to read some fields on node creation (or update). In rules there is the event property where I can choose 'on creation of node'.

I suppose I have to use a hook of some sort, but hooks like `hook_node_insert()` (and some others) that respond on a node being created (or saved) are depending on a node parameter; `hook_node_insert($node)`.

So how do I get this node property?

# Answer
All credits to Clive, but here is the answer.

You need to write a custom module: Simply write a `MYMODULE_node_insert($node)` function containing the code you want to execute. Drupal will call that function every time a node is created (when the module is enabled).

If you are changing the code of a module that is already enabled, you should clear Drupal caches, as otherwise Drupal will not notice the module contains a new hook implementation. This can be achieved by disabling the module before editing it, and re-enabling it after the code has been changed.
> 0 votes

---
Tags: nodes
---


# Question
Title: hook for disabling fields on add and edit node for a content type
I have a content type called article where i have 6 fields.

But i need to display and hide this fields based on user group while add and edit node.

I am confused about which hook should i use.I am planning to use hook\_page\_alter().Please let me know wheather it is the correct hook i am using.Thanks a lot.

# Answer
> 0 votes
If I understand you right you'd be better off using the Field Permissions module:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you do code it yourself you're going to end up implementing most of that modules functionality, so even if you don't use it it's a great place to look for the right hooks to call etc.

---
Tags: nodes, hooks
---


# Question
Title: How to test if honeypot is working on a form?
I have applied the Honeypot module to my site and set it to protect all forms on the site.

The problem is I am unsure of how to test it to know that it is working as expected.

Can anyone tell me how to do this?

# Answer
> 7 votes
Open up firefox or chrome, and inspect the form (using firebug or any equivalent). If you see any element with the class 'honeypot-\*' and a label 'Leave this field blank'. Then its a honeypot field and its enabled.

To check if it works. Make the element visible by changing `display: none` to `display: block`, enter a value into the input box and hit submit. The validation should fail.

---
Tags: 7, forms, testing, advertising
---