title: Referencing parent entity

text:
# Question
Title: Referencing parent entity
I've just started with Drupal and I'm trying to create the following URL structure with PathAuto and Entity Reference:

Category A -\> Category B -\> Category C

Resulting in

category\_a/category\_b/category\_c

For display purposes, I have to define the entity reference on the parent entity. IE:

On Category A, define an entity reference to nodes of Category B.

However, in PathAuto it appears that I can only reference child entities, not parent entities.

I have referenced this article (Path alias tokens and node references) which describes the solution if the entity reference is defined on the child, not the parent.

Is there any way to achieve the above?

# Answer
I came across this post when facing the same situation so I am posting the solution I found in case someone else needs it.

The only way I found to solve this was declaring a custom token using hooks. This post was really helpful: https://drupal.stackexchange.com/a/78498

Once both hooks are implemented, you will only need to manually load the parent to get the data you need, whether it is the parent URL or the parent title. After that, just use the token you just created and voilá!

Hope it helps!
> 0 votes

---
Tags: 7, entities, path-aliases
---


title: Displaying users who click the button

text:
# Question
Title: Displaying users who click the button
I have 2 user roles in my Drupal 7 site `'A'` and `'B'` respectively:

* users of role `'A'` can create and publish content.
* users of role `'A'` can see content they created on their profile page. (For this purpose I created a block to display content and put it on user's page.)
* users of role `'B'` can **not** create content but they can view all published content.

Content in my case is an invitation to some event (ie "Who wants to play football on Friday?")

Each content has `'Participate'` button which users of role `'B'` can submit.

1. How can I display in `'A'` users pages the names of `'B'` users who want to participate in their event?
2. How can an `'A'` user confirm participation of some `'B'` users and dismiss the rest?

# Answer
This is quite a complex task your planning – and it's hard to answer in just a few lines of text. I can basically just recommend you have a closer look at the mighty Rules module in combination with the Flag and the Entity reference module.

Here's just a vague suggestion / outline of how this *could* probably be done by combining the above modules:

* Put a flag `'participate'` on content type event users of role `'B'` can use
* Define a new content type `'participation'` with checkbox/flag `'confirmed / dismissed'` and reference the event and the user to it, editable by `'A'` users
* Make a rule that generates a new node of content type `'participation'` and alerts users of role `'A'` of a new request
* Extend your profile pages' view with the referenced items of content type `'participation'`

There is probably different ways to do this – most likely also easier ways than the one described above. And then there is also a more specific module 'Rules link event' that might fit your demands.
> -1 votes

---
Tags: views, users
---


title: Show a view's filter as a menu

text:
# Question
Title: Show a view's filter as a menu
I'm recently working on a view and i want to show the filters (two of them) as a menu. This means: That both filters can't be used at the same time (most important, a.k.a if one filter is already used and we click on the second, the first one is initiated), That the list of elements of each filter is shown when the mouse is on (less important) That the -All- should be replaced by the name of the filter (least important)

I have tried to look for it in the internet and find some answers that didn't work for me (here is the solution for an oldest version of drupal https://www.drupal.org/node/1111712)

Thank you ^^ Edit : I've developed a function to choose between both filters, but it's still not working

```
$testpriorite=0;
if((isset($form_state['input']['term_node_tid_depth_1']))&&(isset($form_state['input']['term_node_tid_depth']))){
    if(($form_state['input']['term_node_tid_depth_1']!="All")
      &&($form_state['input']['term_node_tid_depth']!="All")){
        if($testpriorite==1){
            $form_state['input']['term_node_tid_depth_1']="All";
        }elseif($testpriorite==2){
            $form_state['input']['term_node_tid_depth']="All";
        }
        $testpriorite=0;
    }elseif ($form_state['input']['term_node_tid_depth_1']!="All"){
        $testpriorite=1;
    }elseif ($form_state['input']['term_node_tid_depth']!="All"){
        $testpriorite=2;
    }

```

here term\_node\_tid\_depth and term\_node\_tid\_depth\_1 are my two filters. Does someone have an idea ?

thanks again

# Answer
I did manage to find a solution to my problem. For that i create a menu (that looked like the filters), and for each link i entered /(ViewUri)?=. I unactivated ajax and deleted the "$exposed" part in the .tpl.php template file of the view.

If anyone needs more explanation, i'm still here (for now, winter's coming)

Sorry for bothering you all, and thanks again.
> 0 votes

# Answer
Instead of calling directly the view you call a rules link.

The rules link is calling the view with the desisered parameters for the view. In this case the filter can be used as a contextuel filter.

No programming needed.
> 1 votes

---
Tags: views, routes
---


# Question
Title: Is json_decode parse-ability proof of a safe string?
Do I need to use check\_plain (or something else) when displaying a user supplied JSON string, when I have previously checked it successfully parses with json\_decode?

# Answer
**TL;DR: You should `check_plain` it.**

Because the json-enoded string itself can contain insecure code.

This is our example. `$data[1]` and `$data[2]` should not be executed.

```
$data = array(
  'Hukana Matata',
  '<script>alert("Oh no!")</script>',
  '<a href="#" onclick="javascript:alert(\"Oh no!\')">CLick here</a>',
);

```

You encode this with json\_encode. If you `json_decode($data_str)`, and it's a perfectly valid `JSON`.

```
$data_str = json_encode($data);

```

Now, if you print this:

```
print $data_str;

```

Now, you will see that the forward slash is escaped.

```
["Hukana Matata","<script>alert(\"Oh no!\")<\/script>","<a href=\"#\" onclick=\"javascript:alert(\\\"Oh no!')\">CLick here<\/a>"]

```

json\_encode encodes strings for JSON notation. In the example above, we encoded using json\_encode from PHP's implementation. But depending on the flags, you can prevent PHP from doing do.

```
$data = array(
      'Hukana Matata',
      '<script>alert(document.title)</script>',
      '<a href="#" onclick="javascript:alert(\"Oh no!\')">CLick here</a>',
    );
$data_str = json_encode($data, JSON_UNESCAPED_SLASHES);
print $data_str;

```

Notice how the script tag sneaked in:

```
["Hukana Matata","<script>alert(document.title)</script>","<a href=\"#\" onclick=\"javascript:alert(\\\"Oh no!')\">CLick here</a>"]

```
> 4 votes

---
Tags: security
---


# Question
Title: How to select author/creator field of CRM-Core Contact and Activity in views?
I'm building a view for CRM-Core Contact, but I can't find the author/creator field from the Add Fields list.

I have checked the database table, there IS a column `uid`:

> The users.uid that owns this contact; initially, this is the user that created it.

Any idea about this?

And there are no permissions like `Edit own Contacts`, only permissions like `Edit any Contact`. Is it designed on purpose?

# Answer
From what I know, the permissions 'edit any contact' is designed on purpose...module maintaiers claim this allows for custom permissions to be set per your requirement.

As for author / creator field, you have to add a relationship first to your view Try these -

1. CRM Core Activity: Author
2. Entity Reference: Participants

That should probably expose the field you are looking for.
> 0 votes

---
Tags: views
---


title: translate a field before rendering

text:
# Question
Title: translate a field before rendering
I made a content type programmatically with the entity\_translation module. There are about 250 fields.

240 fields are not to translate because their values are identical. So I only want to use entity\_translation for about 10 fields.

Now i have a lot of checkboxes and select fields. This are all associative arrays. Out of the box the values are shown in English for German and English urls.

E.g.: Select list: ("keyA" =\>''valueA", "keyB"=\>"valueB") shows "valueA" or "valueB" as result for the field in the node. I want the t-function included to use a \*.po file for translation. Thus t('valueA') has to be implemented before rendering the field?

How can I do this?

THX in advance,

# Answer
> 0 votes
In short: use hook\_field\_widget\_form\_alter()

```
/*
* translate the form
*/
function mymodule_field_widget_form_alter(&$element, &$form_state, $context){

if(isset($element['#title'])){
  $element['#title'] = t($element['#title']);
}
if(isset($element['value']['#title'])){
  $element['value']['#title'] = t($element['value']['#title']);
}
if(isset($element['#description'])){
  $element['#description'] = t($element['#description']);
}
if(isset($element['value']['#description'])){
  $element['value']['#description'] = t($element['value']['#description']);
}
}

```

This translates titles and edscriptions of textstrings.

To show the fields title and description in the given language in node\_view:

```
function mymodule_preprocess_field(&$vars) {
if ($node = menu_get_object()){
  if($node->type == 'immoclient'){
    // Check to be sure there's a label and it's visible.
    if(isset($vars['label']) && $vars['label_hidden'] === FALSE){
      $vars['label'] = t($vars['label']);
    }
    $field_name = $vars['element']['#field_name'];
    $trans_fields = mymodule_trans_fields();
      if(in_array($field_name, $trans_fields)){
        $items = $vars['items'];
        $result = count($items);
        for($i = 0;$i < $result; $i++){
          $vars['items'][$i]['#markup'] = t($vars['items'][$i]['#markup']) ;
        }
      }
     }
    }
   }

```

and mymodule\_trans\_fields() returns an array of fields to translate.

To show the items (and here the answer) in the appropriate language for selects and checkboxes in the form, I used hook\_form\_FORMID\_alter:

```
function mymodule_form_[mynode_form]_alter(&$form,&$form_state,$form_id){
    foreach($form as $key => $value){
      $field = strpos($key, 'field_');
        //only for fields!
          if($field !== false){
            if(isset($form[$key]['und']['#description'])){
            //seems so that every field has a description, to use it for items too
            //build variables
              $res = $form[$key]['und'];
              $desc_t = t($form[$key]['und']['#description']);
              $form[$key]['und']['#description'] = $desc_t;
                }
               }
             }
           }

```

---
Tags: entities
---


# Question
Title: Anonymous sessions breaking login for Drupal 7
This is my first official post so bare with me if i do not have all the information you may need.

Being a beginner of Drupal from a PHP background I am struggling with SESSIONS.

First, there are conflicting information I am reading on how one should set sessions, some say it we should use a unique key, like so: $\_SESSION\["uniquekey"\] = array(); $\_SESSION\["uniquekey"\]\["variable"\] = 1;

Others say this is sufficient:

$\_SESSION\["variable"\] = 1;

Secondly, I have managed to set Anonymous sessions without problems, this sets the UID to 0 in the sessions table, the problem I am experiencing is when I login.

Login is succeeding but I am getting "you have no authentication etc" and therefore unable to access the CMS. FYI in the session table, it has inserted another session with UID set as 1. I am having to destroy the anonymous session to access the whole CMS but from what I understand the login form should regenerate?

I am setting the sessions in template.php and logging in user /user

Would appreciate if some people can share some light on how one can set sessions without breaking the login?

Your help would be much appreciated

Cheers

# Answer
> 0 votes
If you are actually trying to override the default behaviour of assigning uid, you need to explain why. In order to access the already determined uid information created by Drupal, use this in template.php or a .tpl.php:

```
<?php
  global $user;
?>

```

To see what information is already available in $user, make use of the Devel Module:

> Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries).

specifically, the dpm() function. This can be added just about anywhere as:

```
<?
  php global $user;
  dpm($user);
?>

```

This will present a breakdown of the $user array and all the information it contains.

---
Tags: sessions
---


# Question
Title: Form validation not triggered at first submit, but on second submit
I'm in the need for a extra validation on an existing drupal commerce form (commerce\_cart\_add\_to\_cart\_form\_##), strangely the validation function is not called on the first form submit, but on the 2nd submit and all the submits after the 2nd. There are multiple commerce\_cart\_add\_to\_cart\_forms on a single page.

Here's my module code:

```
function val_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, 'commerce_cart_add_to_cart_form_') !== false) {
        $form['#validate'][] = 'val_commerce_cart_add_to_cart_form_validate';
    }
}

function val_commerce_cart_add_to_cart_form_validate($form, &$form_state) {
    dpm('validating function called');
    form_set_error('quantity', t("ERROR"));
}

```

Any Ideas? And, as a second question: there are different $from\_ids (commerce\_cart\_add\_to\_cart\_form\_##) that will all need the same validation. Is there a way to call them all other than I did?

Thanks!

# Answer
> 0 votes
I added your code to a quick dummy function, tested it, and the it seems to be working fine. I created a dummy item, added it to my cart, and the that produced a print out like:

I also added a watchdog() call to the validate function and that confirmed the validation was being called when it should be. I'm not sure if maybe you have something else interfering with your form alter or possibly your dpm is printing out late (I know it can happen with themes, not sure with modules), but you might want to try using watch dog to see if the validation form isn't being called when it should.

---
Tags: commerce, forms
---


# Question
Title: The 'drupal' way to implement delete button UI
I think I'm missing something fundamental here. What's the 'right' way to implement a delete button on the UI-end?

My app has a classic list-type data model: User has wishlist(s) -\> wishlist has item(s) -\> item has properties. (These are represented in several tables, of course).

The several views are loaded via tpl files using hook\_theme(). When the app has a view loaded for any step of the way (looking at an item in a list, for instance) I want to have edit/delete buttons that act on the item. The CRUD methods are in place, they just need to be wired to the button.

In some places in the app, I've exposed methods via `hook_menu()`, and that works fine by passing the target to `l()` \- I'm using this for many of my "View Item" UIs. Is there another way, though? This seems to be exposing a ton of core logic to the address bar if I keep going that route.

In a nutshell: How do I have a button action similar to pseudocode `button.click=$this->bluenose_app_remove_available_property($property->id);`? Preferrably without routing through `hook_menu()`

# Answer
What you listed is what we normally do.

A menu router item (what you define in `hook_menu` actually serves a lot more than just pointing logical actions to functions/methods. It also makes sure than the items exist, they are accessible, and delivered correctly.

In hook\_menu, you can definite how the access should be granted (with permission system or anything else). You can use wildcard loaders to load items, so you don't have to throw 'page not found' errors yourself.

You don't have to put your logic in the URLs. If you deal with entities, have your entity build the operation URLs, so they become part of your entity class, and not part of the template (the "View" of traditional MVC).

When the entity gets complicated, I often end up writing a single menu router to handle them all. The operation argument of a menu path (edit, delete, clone, disable, etc) can be a wildcard loader as well, and you can easily validate it using a method\_exists() call.
> 1 votes

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


# Question
Title: How do I programatically add fields to the Media module's field tables?
I use the **Media** (ver, 2) module to manage a library of media assets. It allows reuse of the same media in several nodes and keeps track of media use.

When reusing media (e.g.) images, I want to be able to add *different* captions (and maybe other metadata) to each *use* of the same image. I.e.: When I use the same image attached to two different nodes, I want to set the caption for each instance.

There is a great tutorial “How to Add Captions to Images in Drupal” about adding captions – but its approach is to add the caption to the image entity itself. This means that the same caption must be repeated whenever the image is reused. I want an unique caption for each use instance.

I’ve noticed that version 2 (`7.x-2.0-alpha4`) of the **Media** module manage some metadata (e.g. `field_media_description`) about each media instance use in the two tables `{field_data_field_media}` and `{field_revision_field_media}`. I’ve tried to use the already existing field `field_media_description` for the caption. This works, and *almost* does what I want.

However, I want the caption field to be a `textarea` (not a `textfield`), and I prefer not to overload some existing field with new functionality (maybe breaking the initial intent for this existing field) - so I want to add another field (`field_media_caption`) to these tables.

I’ve been digging about the **Media** module for days, trying to figure out *how* to add my own fields to these tables, and have not been able to figure it out.

So:
How do I programatically add *additional* metadata fields to the **Media** module's field tables?

I will also accept an alternative solution that allows me to use a different module to manage a library of reusable images and add captions fields per use-instance.

# Answer
There is a sandbox module I helped with, Media Wrapper, which solves this problem by managing media via a field collection. This has the advantage of making it possible to associate any fields you like with a media file, including captions. And the metadata is all per-use rather than per-file.

As it is a sandbox module, it's not as polished as we would like but it does a reasonable job of solving this problem.

To use it, once installed you create a field collection with your media field and meta data and then configure it via field settings of the field collection to say how each field is to be used (for alt text, title, caption etc).
> 1 votes

# Answer
I know your question specifically aims at the *media module* but still I would like to point you in another direction, since it really was an eye opener for me:

As far as I know the *scald module* can basically do everything the *media module* can, and more. And the feature your asking for is already built in: standard captions (generated from the media item's title) with the option to override the caption on each media instance use.

* fieldable media 'atoms'
* drag'n'drop media into rich text areas and/or media reference fields
* central asset management
* extendable – can handle images, files, video, galleries
* scalable – used by large publishing houses
* drupal 8 branch under way

Here is some details available in case you want to go all the way and migrate to scald.

And here is a series of videos that can be helpful to get started.
> 1 votes

# Answer
I am not sure if you have seen that the Media module (with File Entity) opens up File Types in the Drupal admin. From here, you can define new types and field them.

Off the top of my head, without adding code, you may be able to try and attach metadata via Field Collections to a file type.

For example, a collection that holds caption, title, alt fields, and has a node reference field. Set it to unlimited values.

For the display, I would try creating a view block that shows the image and attach the field collection data on it filtered by node reference ID by the current context of the given node page.

That would most likely be my first approach to adding contextual data to a single media entity without doing a lot of code.
> 0 votes

---
Tags: entities, files, media
---


# Question
Title: AJAX in Form API element returned in another AJAX callback
I have a form like this:

```
$form['my_button'] = array(
  '#type' => 'button',
  '#ajax' => array(
    'callback' => 'my_callback_1',
    'wrapper' => 'some_wrapper',
  )
);

```

Which works fine (code is very simplified). Now, in the callback, I want to return another button, which also has ajax configured:

```
function my_callback_1() {
  return array(
    'my_other_button' => array(
      '#type' => 'button',
      '#ajax' => array(
        'callback' => 'my_callback_2',
        'wrapper' => 'some_other_wrapper',
      )
    ),
  );
}

function my_callback_2() {
  return array('#markup' => 'success!!');
}

```

Now, when I click on the first button, Drupal loads the second button just fine. The problem is, a click on the second button does nothing. Am I missing something?

# Answer
After a lot of reading, I solved this by returning `$form` on the AJAX callback, and including the second button on a form rebuild. My code now looks more like this, and it's working fine:

```
function my_form($form, &$form_state) {
  $wrapper_id = drupal_html_id('some_wrapper');

  $form['#prefix'] = '<div id="' . $wrapper_id . '">';
  $form['#suffix'] = '</div>';

  if (isset($form_state['my_flag']) && $form_state['my_flag']) {
    $form['my_other_button'] = array(
      '#type' => 'button',
      '#name' => 'my_other_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      )
    );
  }
  else {
    $form['my_button'] = array(
      '#type' => 'submit',
      '#name' => 'my_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      ),
    );
  }
}

function my_form_submit($form, &$form_state) {
  switch ($form_state['triggering_element']['#name']) {
    case 'my_button':
      //code for when user presses the first button
      $form_state['my_flag'] = TRUE; //show the other button
      $form_state['rebuild'] = TRUE; //this is necessary!
      break;
    case 'my_other_button':
      //code for when user presses the second button
      break;
  }
}

function my_callback($form, $form_state) {
  return $form;
}

```

I think the problem had to do with a button being outside an actual *form*. I hope this helps others...
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: How to display og group visibility in a view, even if user can't change it
I'm working on a content pane view that displays a list of the groups the current user is a member of. Most properties of the groups are displayed in the view just fine, like the group title. But the group visibility is only shown to specific users.

I'd like to have a note in the group list whether a group is public or private, something along the lines of

> Group #1 | You're a member since... | This group is public
>
> Group #2 | You're a member since... | This group is private
>
> (and so forth)

But when I add the field "Content: Group visibility" to the view, the value only is visible for users that have permission to *change* the respective group's visibility (permission "Administer Organic groups permissions"). For any other user, the "No results behaviour" kicks in. The settings for the field "Group visibility" is public ("author and administrators can edit, everyone can view"), so shouldn't the field's content be visible to everyone?

# Answer
I've found a solution - probably not the most elegant solution and quite "hacky", but it's working so far.

Even though some users are not allowed to see the group's visibility, the information is still provided to the view, but with a marker '#access' set to `false`. It's possible to alter the data displayed by the view by using the hook `hook_views_pre_render`. An implementation, for example in a custom module, could look like this

```
function MY_CUSTOM_MODULE_views_pre_render(&$view) {
  // $view is a reference to the view object

  // alter only the data of the view we want to change,
  // not every view on the website
  if($view->name == "MY_VIEW_NAME" && $view->current_display == "MY_CURRENT_DISPLAY") {
    // iterate over the list of entities, in this case over the list of groups
    foreach($view->result as $index => &$result) {
      // again, have $result as a reference
      // so changes are applied to the "original data", not just to a copy

      // change '#access' field deep in the field data structure
      $result->field_group_access[0]['rendered']['#access'] = true;
    }
  }
}

```
> 0 votes

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


# Question
Title: Drupal 7 views add one field as a URL to another
I am using Drupal 7. I have a view where i filer a certain content type say "A" and display the below 2 fields Content: Title Content: File attachments

My File attachment formatter is set "Url to file".

What i am trying to achieve is to make 'Title' as a link with the 'File Attachment' URL

Thanks in advance!

# Answer
* for the Title, set it 'Exclude from display'
* for the File attachments, 'Rewrite the output of this field' using the token for Title

Make sure the Title field appears above the file attachment, or the file attachment won't recognize it as a valid token when rewriting the output
> 2 votes

---
Tags: views, entities
---


# Question
Title: Hide option Generate automatic URL alias for all languages on user register form?
Do I need to write a hook or may be I can hide this using amdin interface? I am using Pathauto i18n, LoggingToBoggan. The option "Generate automatic URL alias for all languages" is displaying on user register form, and my users can't understand why. I want to hide it only on register form this code is not correct and does not work:

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

  /* hide Generate URL alias for all languages */
  if (isset($form['pathauto_i18n_status'])) $form['pathauto_i18n_status']['und']['#access'] = FALSE;
}

```

# Answer
You can use CSS to hide it or set the option's `#access` value to false using a custom module. The first will hide it but leave it available to be ticked, the second will completely remove it from the page.
> 1 votes

---
Tags: path-aliases
---


title: Trying to make my entire site https

text:
# Question
Title: Trying to make my entire site https
I am trying to make an entire Drupal site https.

I tried enabling secure pages, and this seems to work for every authenticated user.

However any anonymous user either gets only http, or possibly an infinite redirect if I wildcard all possible paths.

How do I get https:// to work on every page, for all users, including anonymous?

This is what my current .htaccess has in the mod\_rewrite.c section:

```
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

```

# Answer
It's usually easier to redirect at the Apache level if you're looking to make the entire Drupal HTTPS. You can place this in your .htaccess file:

```
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```
> 5 votes

---
Tags: security
---


# Question
Title: Missing five core module folders and one enabler
In Drupal 7.36, the "Administration \> Modules" page (/admin/modules) lists 44 core modules. However, the folder "...\htdocs\admin\modules\\" has subfolders for 40 modules, which include those 44, except Field SQL storage, List, Number, Options, and Text, plus Profile.

In other words, there are five core modules that do not have a folder in the core modules folder and there is one core module (Profile) that is not available for enabling on the "Administration \> Modules" page.

Does anyone here know why that is?

The Profile doc page says to "enable in admin/build/modules". That URL on my installation just takes me to the main Administration page. So how does one actually enable this module?

# Answer
The field submodules are inside the field module folder:

```
./modules/field/modules/number/number.module
./modules/field/modules/list/list.module
./modules/field/modules/text/text.module
./modules/field/modules/field_sql_storage/field_sql_storage.module
./modules/field/modules/options/options.module

```

The D7 module overview is at `admin/modules`. `admin/build/modules` was in Drupal 6; a lot of the community docs pages are badly outdated, unfortunately.

Finally, the Profile module is deprecated in Drupal 7, and therefore hidden by default.

```
modules/profile/profile.info:

; The Profile module is deprecated, and included in Drupal 7 for legacy
; purposes only. By default, the module will be hidden from the UI unless you
; are upgrading a site that uses the Profile module to extend user profiles.
; See user_system_info_alter().
hidden = TRUE

```

It's only there to provide an upgrade path for D6 sites; it can't be enabled on a new D7 site without commenting out that line.

(The reason the module is deprecated is probably that the Fields API has taken over what it used to do, so it's obsolete.)
> 0 votes

---
Tags: 7
---


# Question
Title: Drupal 7 -- Would like to use unique profile template per role
I'm working on a Drupal project where we have two main roles (students/teachers) + an admin role. I would like to have entirely different profile pages for the different roles.

At the moment I think the most maintainable method for doing this is going to be to have several profile template files that are called when the specific role is being viewed; I'm just not sure how to preprocess the profile to hint at the correct template.

At the moment, I've built some page pre-processing code to check the role of the profile page we're looking at as follows:

```
function MYTHEME_preprocess_page(&$vars, $hook) {

  // See if we can influence profile pages
  $content = $vars['page']['content'];
  $theme = $content['system_main']['#theme'];

  if($theme == 'user_profile') {
    $roles = $content['system_main']['#account']->roles;

    if(in_array('teacher', $roles)) {
      $vars['theme_hook_suggestions'][] = 'teacher__user-profile.tpl.php';
    }
    elseif(in_array('student', $roles)) {
      $vars['theme_hook_suggestions'][] = 'student__user-profile.tpl.php';
    }

  }

}

```

The conditional correctly identifies the profiles being for teachers or students but I can't seem to influence it by suggesting a profile template.

Any thoughts?

Thanks, Andrew

# Answer
> 0 votes
**SOLVED**

It was just a matter of understanding how $vars\['theme\_hook\_suggestions'\] works.

It works by taking a suggestion in the form of a prefix and then behind the scenes it adds the rest of the parts to create a path to your theme template.

So if you add "**page\__mytemplate**" to $vars\['theme\_hook\_suggestions'\], that suggestion will translate to **page--mytemplate.tpl.php**.

The problem is that I was giving it the whole name and not just the prefix.

The following code updates fixes my original attempt to make Drupal recognize my two custom templates:

* page--teacher.tpl.php
* page--student.tpl.php

Code:

```
function MYTHEME_preprocess_page(&$vars, $hook) {

  // Some variables to identify profile pages
  $content = $vars['page']['content'];
  $theme = $content['system_main']['#theme'];

  if($theme == 'user_profile') {
    $roles = $content['system_main']['#account']->roles;
    if(in_array('teacher', $roles)) {
      $vars['theme_hook_suggestions'][] = 'page__teacher';
    }
    elseif(in_array('student', $roles)) {
      $vars['theme_hook_suggestions'][] = 'page__student';
    }
  }
}

```

Hopefully this will be helpful to someone else too.

Andrew

# Answer
> 0 votes
Have a look at ThemeKey.

From the project page (emphasis added):

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or **role** -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server

---
Tags: theming, users
---


title: Using placeholders in watchdog function

text:
# Question
Title: Using placeholders in watchdog function
I know this is simple. I have a callback function `callback` below:

```
function callback($id = '121-01927'){
    watchdog('print', '%message : Sample',array('%message' => $id), WATCHDOG_DEBUG, $link = NULL);
}

```

After executing the callback function, I viewed `watchdog` table in my database, and it says there.

```
%message : Sample

```

It seems my placeholder `%message` is not substituted by the variable `$id`. Where am I missing?

# Answer
The placeholders are not supposed to be substituted in the database.

This is because the `watchdog()` function can be called from anywhere, for any user, with any language. Mid you call `t()` function, which usually does the placeholder substitutions and translation, that function used the current language to translate to. Now, if you call `watchdog()` to log an error for user A, whose language is `de`, the message should not be saved to the database as the `de`-translated string. That is why the english untranslated strong is stored.

When an administrator views the log (From Admin -\> Reports -\> Recent log items), Drupal does the translation call (`t()`) at that very moment. All entries will then be translated to the language the current user has configured.
> 1 votes

---
Tags: forms, ajax, log-messages
---


# Question
Title: The 'drupal' way to implement delete button UI: part 2
I asked this question earlier The 'drupal' way to implement delete button UI The answer worked perfectly. I would like to take it a step further and make sure my routing is done the best way for Drupal. (I'd hate to think there's some uber-powerful method out there I'm missing out on).

snippet from hook\_menu():

```
$items['bluenose/rmlist/%'] = array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_LOCAL_TASK,
);
$items['bluenose/rmlistitem/%']=array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_LOCAL_TASK,
);
$items['bluenose/rmavailableprop/%']=array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_LOCAL_TASK,
);

```

The method those route to:

```
function bluenose_app_rmelement($type, $id)
{
  switch($type)
  {
  case 'rmlist':
    bluenose_app_remove_wishlist($id);
    drupal_goto('bluenose/wishlists');
    break;
  case 'rmlistitem':
    bluenose_app_remove_list_item($id);
    drupal_goto('');
    break;
  case 'rmavailableproperty':
    bluenose_app_remove_available_property($id);
    drupal_goto('');
    break;
  default:
    break;

  }
}

```

Just to clarify the flow: There are three hook\_menu items that route `$type` and `$id` to a common rm\* method. This method switches among possible `$type` params. When it hits the right one, it calls the appropriate remove method (which performs basic crud), then calls `drupal_goto()` with a url that makes sense to the end-user.

How's that method chain look to you guys? Thanks a lot!

# Answer
> 0 votes
It does look good! But you could remove the repeating hook\_menu items as well.

When I said the following,

> When the entity gets complicated, I often end up writing a single menu router to handle them all. The operation argument of a menu path (edit, delete, clone, disable, etc) can be a wildcard loader as well, and you can easily validate it using a method\_exists() call.

I actually meant that you'd use one menu router item that passes extra variables to resolve the call to an actual function. Now that you have posted some real code, I'd go ahead and show an example for you. Note that this is not an *official* way to do this, but I practice this quite a lot and never had a problem.

The only menu router item we need.

```
$items['bluenose/%/%'] = array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_CALLBACK,
);

```

The `page callback` to handle 'em all.

```
function bluenose_app_rmelement($type, $id) {
  switch($type) {
    case 'rmlist':
      bluenose_app_remove_wishlist($id);
      drupal_goto('bluenose/wishlists');
      break;
    case 'rmlistitem':
      bluenose_app_remove_list_item($id);
      drupal_goto('');
      break;
    case 'rmavailableproperty':
      bluenose_app_remove_available_property($id);
      drupal_goto('');
      break;
    default:
      break;
  }
}

```

Now, you will notice that the menu router item is actually of type `MENU_CALLBACK`, and its not of type `MENU_LOCAL_TASK`. If you want to make it a local task, it has to be defined so in the hook\_menu... But you can also do so in a `hook_menu_local_tasks_alter()` hook implementation.

If you absolutely need to make all the operation links to be `MENU_LOCAL_TASKS`, you can either go for the multiple router item way (from your original question's snippet) or implement `hook_menu_local_tasks_alter()`. With this hook, you are dynamically adding menu router items only when the current router item is what we are after.

Also, note that menu paths that immediately execute the functions are vulnerable to CSRF attacks. When you create the URLs, you should add a token to the link and validate it in the `page callback`. See `drupal_get_token()` and `drupal_valid_token()`.

---
Tags: routes
---


# Question
Title: Is it okay to use PhP include() in body of basic page?
Aside from the usual warnings about using PhP, which I understand and am taking seriously, is there any drawback to using the PhP include() function in the "Body" box of the "Edit Basic page" form?

This is not for users of the site. This is only for me, the creator of the site. No one else will have permission to use PhP code on the site.

The reason I want to do this is as follows: I'm revamping an ASP site into Drupal. I have a page that builds its contents from a large amount of data drawn from a database (which I've imported from Access into MySQL). I'm going to translate the Javascript of the ASP page into PhP to do this in Drupal. But I'm getting tired of working in that little and unintelligent "Body" box in the "Edit Basic page" form. If I just put an include() in that box, then I can work on the PhP code in a file in NotePad++. Then every time I save a change to that file, I can test the effect by just refreshing the page.

Any reason not to work that way?

# Answer
> 2 votes
In reply to your reply in the comments, I thought to post an answer instead.

There are many reasons why it's not OK to embed executable code where we expect to have actual content. This is not Drupal specific. It's not even PHP specific (this one on JS for example).

Since you indicate you are comfortable writing PHP code, why not create a new module instead, and put your code (that you expect to put in the Body) inside the module? You'll be taking a big step in the Drupal learning curve too. It's not that hard to write a simple module!

As for Drupal, the reason is because your PHP code is interpreted very lately, or sometimes, it will not be executed at all. PHP code is executed from the `PHP Filter`, which is only run when you output the code with this filters processed. You can **easily** break your PHP snippet:

* Run some Rules on the Body content (such as a string match). Rules will match the raw PHP content: Not what you expect it to be.
* Email: Modules such as Notifications, Mime Mail can apply different filters on your content (other than PHP Filter), which will make the email content will contain the raw PHP content.
* Views: Filter rewrite features will process and output your raw PHP content.

Other than the above, you are making your core logic **not controllable by version control systems** we have (git for example). It's always easy to keep them in mind, but once you are done with the site and move on, your Neurons do funny things and forget the fact that you have some core logic embed somewhere (is it node 134, 314 or 420?) in the `field_data_body.body_value` column.

**When it's barely acceptable to use PHP in the database?**

Admittedly, there are some situations that we have to use some small PHP snippet here are there to save time creating whole new plugins.

**Views:** Views contextual filters support evaluating some PHP snippet to validate contextual filters.

**Rule:** Rules conditions and actions have "Execute PHP" as an action/condition.

I think above two cases are barely acceptable cases that you can use some PHP. This is because you are supposed to put some PHP code there, and the parent code that evaluates the PHP snippet is well aware that it contains some PHP code. If a field description says "Do *not* use ", that means the field is aware that the input contains some PHP.

**Modules are safe?**

To address your comment to this question, you can use PHP in the module because, well, that is where you code your logic. A malicious snippet is equally harmful regardless where you put it. But when you have it in a module, you can turn it off, other developers know that you put custom code here, and it can be versioned.

Modules are the basic logic behind the entire site. Nodes, user accounts, taxonomy, menu, blocks, they all are modules themselves. Your custom module is equally good enough to implement same hooks. You can only put PHP code where you are asked (Views execute PHP fields, Node content, etc). But with a module, you become your own god that you can implement any hook you want, and have a far wider access to the system.

# Answer
> 2 votes
I assume that you only want to debug a certain code, so you exeute the code inside the node only temporary. I think for that task is much better to just edit the code in your favorite editor wrapped in a function and then call it inside a `/devel/php` page.

For example:

```
function my_code() {

   // Experimental code here.
}

```

Then goto `/devel/php` with Devel module enabled and complete the textarea with:

```
my_experimental_code();

```

You can edit your code and go to the browser window and push 'Execute'. You can use `dpm()` function to show data on the screen. See results, then modifiy your code and then you only have to go to the browser again and just click 'Execute' again.

---
Tags: 7
---


# Question
Title: Making track of who has seen which content
In a system with users number changing anytime, I need to make a system which shares content between them and makes track of who has seen which content.

Is there any module for doing it?

(I read about **Flag module**, but it is sharing one flag for all users, so it's not a good recommendation)

# Answer
The solution is Seen module! Just read and use it
> 0 votes

---
Tags: 7
---


title: Passing HTML to the response object

text:
# Question
Title: Passing HTML to the response object
I had this piece of code in a module developed for some previous version of Drupal 8.

```
protected function getOutput() {
    $content = $this->buildContent();
    //print_r($content);
    $page = array(
      '#theme' => 'html',
      '#page_object' => new Html(render($content)),
    );
    $rendered_page = render($page);
    return $rendered_page;
}

```

Now, in the present beta release, it shows this error:

> Fatal error: Class 'Drupal\hardcopy\Plugin\Html' not found in C:\xampp\htdocs\drupalbeta7\modules\custom\hardcopy\src\Plugin\HardcopyFormatBase.php on line 175

Can someone tell me how to pass the HTML of the whole page in the response object?

# Answer
As D8 uses Symfony responses it's as simple as:

```
use Symfony\Component\HttpFoundation\Response;

...

$response = new Response(
  'Your HTML content here',
  Response::HTTP_OK,
  array('content-type' => 'text/html')
);

return $response;

```

See the docs for more information.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Allow tinymce in WYSIWYG to load different skins per content type
I want to user a different default tinymce editor styles per content type. I basically want to use a different default font in the editor area of tinymce per content type.

I have discovered that the editor of tinymce has some default settings that are not configurable through the WYSIWYG module, but it can by modifying the file jscripts/tiny\_mce/themes/advanced/skins/default/content.css

However, that would apply to all content types.

Is there a way to set a skin for a content type?

This would be a start, but does not apply it per content type:

```
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function custom_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
  $settings['skin'] = 'o2k7';
  $settings['skin_variant'] = 'silver';
  }
}

```

# Answer
I think you're on the right track, but from memory, I don't think you'll have info about the content type or the node form in the $settings and $context variables, As Darvanen suggests.

I'd implement hook\_form\_alter() to match node forms, then read the content type being used, and store it as a static variable through drupal\_static() function. That way you can access the content type info from the snippet you pasted above, using that same drupal\_static() function, and then choose which skin to use.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Is it possible to use multiple captcha based on language selection?
I have a multi-language site.I wish to integrate captcha based on which language is selected.

```
Suppose if i selected language1 then captcha1
language1 => captcha1
language2 => captcha2

```

# Answer
> 1 votes
Well, you should do this in `template.php`. First check the language then add the captcha based on the language. As an example to do this in webforms:

```
function THEME_form_alter(&$form, $form_state, $form_id) {
    global $language;
    if($language->name == "ENGLISH")
    {
        if (strstr($form_id, 'webform_client_form')) {
            $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'image_captcha/Image',
            );
        }
     }
}

```

You can check the language and add the `mollom` programmatically as well. Follow this link to learn how to add mollom by code.

---
Tags: 7, captcha, advertising
---


title: Node/website architecture visualization

text:
# Question
Title: Node/website architecture visualization
I am seeking to build a website which contains quite a lot of information. All this information will be structured in a specific way. As such I am looking for a way to represent this data/articles/nodes visually.

The purpose is to be able to add new articles to an already existing visual structure by simply adding a node and classifying it/linking to existing articles that are already structured/adding taxonomy terms etc.

The visual structure will as such have a changing shape/size. A map of the information presented on the site if you will.

A way to navigate the wealth of information visually.

Does something like this already exist or is there a way to create such a module/program for the site - potentially as a separate site that presents the drupal site?

Thanks,

# Answer
I don't believe there is a Drupal specific option, but you can utilize a module like XML Sitemap:

> The XML sitemap module creates a sitemap that conforms to the sitemaps.org specification. This helps search engines to more intelligently crawl a website and keep their results up to date. The sitemap created by the module can be automatically submitted to Ask, Google, Bing (formerly Windows Live Search), and Yahoo! search engines. The module also comes with several submodules that can add sitemap links for content, menu items, taxonomy terms, and user profiles.

and then use a number of third party online or software based options for visualising xml data. A quick search in google yielded a number of options for 'visualise sitemap'
> 2 votes

# Answer
In addition to Geoff's answer (which is an stroke of genius), note that you can link nodes using Entity Reference, and create heirarchies of nodes using Node Hierarchy.

I recommend the former unless you *really* need to specify which node is parent and which is child, in which case the latter works pretty well.
> 0 votes

# Answer
There is also the often forgotten book module which is part of Drupal core. It allows for nesting of nodes inside other nodes so you can create a book with chapters. (the guide pages on Drupal.org are an example of this.) depending on the stucture you need this could be useful.
> 0 votes

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


# Question
Title: image_style_create_derivative not resizing the image
I am using `image_style_create_derivative` to create image styles on fly. Before that I am using image\_style\_path which creates style path.

```
$derivative_uri = image_style_path([style_name], [source]);
image_style_create_derivative([style_name], [source], $derivative_uri)

```

It generates image. Which is fine. But it is generating image with original size. Not with the size of style\_name.

For example if style name is thumbnail, the generated image style size should be 160x100.

How can I achieve it?

# Answer
> 1 votes
image\_style\_create\_derivative needs the style passed as array.., so _ first you need to load the style or fake the array

> applying all image effects defined in $style\['effects'\]

see: image\_style\_create\_derivative

i usually use image\_style\_url like this (if taken from field), otherwise just pass the source.

```
        $field = field_view_field('node', $node, $field_name, reset($image), $arr_display);
        if ($img_style) {
          $uri = image_style_url($img_style, $field[0]['#item']['uri']);
        }
        else {
          $uri = file_create_url($field[0]['#item']['uri']);
        }

```

---
Tags: media
---


# Question
Title: Create commerce product through web services
I want to create products using commerce services resource module. At this moment, I can create a product calling the resource `.../product` with POST, but It seems that It only creates a product variations, because If I navigate to "manage products" option, I can't see the new product but if I call a GET over resource `.../product` I can see the new one. Then, I'd tried to create a product using `.../node` resource, but I always get an error:

```
"field_product][und][form][commerce_price][und][0][amount": "Price field is required"

```

I don't know what is the right JSON structure to create a node with its product variations. Could some one put here an example of the right JSON structure for creating node products?
Thanks.

# Answer
I've found the error. Firstable, my drupal commerce installation hasn't `product_display` content type. I have to add it manually. I don't know why, but It's missing after clean installation. Secondly, the right JSON structure for `commerce price` section is:

```
"field_product":{ "und" :
            {  "form": {
                   "commerce_price": {
                        "und": [ {
                           "amount": "1234.34",
                           "currency_code": "EUR",
                           "data": { "components": [] }
                            } ]
                      },
                   "sku":"eeaafe3231aa"
          }

```

After this change, I can create products display and I can see it on `product manage` page. Hope It could be useful for other who has the same problem.
> 0 votes

---
Tags: commerce, services
---


# Question
Title: How to change the query value using hook_views_query_alter?
I am having a problem trying to change the query output on my view.

I am using this code:

```
function zed_views_query_alter(&$view, &$query){
  if ($view->name == 'questions_home' && $view->current_display == 'rates_related') {
    $or = db_or();
    dpr($query->where[1]['conditions'][2]['field']->condition());
  }
}

```

I am trying to alter the word `%california%`. The output is the following one.

```
DatabaseCondition Object
(
    [conditions:protected] => Array
        (
            [#conjunction] => OR
            [0] => Array
                (
                    [field] => node.title
                    [value] => %california%
                    [operator] => LIKE
                )

            [1] => Array
                (
                    [field] =>
                    [value] =>
                    [operator] => IS NULL
                )

        )

    [arguments:protected] => Array
        (
        )

    [changed:protected] => 1
    [queryPlaceholderIdentifier:protected] =>
)

```

How can I go about changing the value `%california%`?

# Answer
```
function zed_views_query_alter(&$view, &$query) {
  if ($view->name == 'questions_home' && $view->current_display == 'rates_related') {
    foreach($query->where[1]['conditions'] as $idx => $condition) {
      if (!is_object($condition['field']) && $condition['field'] == 'node.title') {
        $query->where[1]['conditions'][$idx]['value'] = '%whateveryoulike%';
        // or you can unset this condition and write down a new one
        // unset($query->where[1]['conditions'][$idx]);
        // $query->add_where_expression('1', "$field LIKE %" . db_like("california") . "% OR field LIKE %" . db_like("somethingelse") . "%");
      }
    }
    dpr($query->where[1]['conditions']);
  }
}

```
> 3 votes

# Answer
In Case of views query alter hooks we can use syntax similar below mentions

```
function hook_views_query_alter(&$view, &$query) {
  global $user;
  if ($view->name == "Alerts") {
     $query->where [0] ['conditions'] ['0'] ['value'] = '%' . $user->name . '%';
     $query->where [0] ['conditions'] ['0'] ['operator'] = "LIKE";
  }
}

```

Also you can change other $query-\>where positions data, This will impact in your query.
> 0 votes

# Answer
To change query values in Filter criteria, you can use `hook_views_query_alter` in the following way:

```
/**
 * Implements hook_views_query_alter().
 */
function MYMODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {

    // Assign my values.
    $value1 = 'This is my value for filter 1.';
    $value2 = 'This is my value for filter 2.';
    $value3 = 'This is my value for filter 3.';

    // Programatically update the filter criteria of a view.
    array_walk_recursive($query->where, create_function('&$v, $k', '$v = str_replace("_MY_TOKEN1_", "'.$value1.'", $v);'));
    array_walk_recursive($query->where, create_function('&$v, $k', '$v = str_replace("_MY_TOKEN2_", "'.$value2.'", $v);'));
    array_walk_recursive($query->where, create_function('&$v, $k', '$v = str_replace("_MY_TOKEN3_", "'.$value3.'", $v);'));
  }
}

```

Just change your value in your view to some custom token (`_MY_TOKEN1_`) and the function automatically find the right array key and it'll alter its value.

If you're using YQL View, use `hook_yql_views_query_query_alter()` instead.
> 0 votes

# Answer
```
if($view->name == "SomeView_Name"){
       $query->where[1]['conditions'][0] = array('field'=>"node.title","value"=>'%california%',"operator"=>"LIKE");
}

```

I think this will help you.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I add an SQL query with  hook_views_query_alter()?
I have the following SQL query:

```
db_query("SELECT content_id, COUNT(*) as count FROM {votingapi_vote}
          WHERE value_type = '%s'  AND value = 1
          GROUP BY content_id;", "option");

```

If I want to override the view, which code should I put in `mymodule_views_query_alter()`?

The content of `$query` is the following:

```
    views_query Object(
      [table_queue] => Array(
        [node] => Array(
          [alias] => node
          [table] => node
          [relationship] => node
          [join] =>
        )
      )
      [tables] => Array(
        [node] => Array(
          [node] => Array(
            [count] => 1
            [alias] => node
          )
        )
      )
      [relationships] => Array(
        [node] => Array(
          [link] =>
          [table] => node
          [alias] => node
          [base] => node
        )
      )
      [where] => Array(
        [0] => Array(
          [clauses] => Array(
            [0] => node.status  0
            [1] => node.type in ('%s')
          )
          [args] => Array(
            [0] => provider
          )
          [type] => AND
        )
      )
      [having] => Array()
      [group_operator] => AND
      [orderby] => Array(
        [0] => node_created DESC
      )
      [groupby] => Array()
      [header] => Array()
      [distinct] =>
      [base_table] => node
      [base_field] => nid
      [fields] => Array(
        [nid] => Array(
          [table] => node
          [field] => nid
          [alias] => nid
        )
        [node_title] => Array(
          [field] => title
          [table] => node
          [alias] => node_title
        )
        [node_created] => Array(
          [field] => created
          [table] => node
          [alias] => node_created
        )
        [content_id_] => Array(
          [field] =>
          [table] => content_id
          [alias] => content_id_
        )
      )
      [count_field] => Array(
        [table] => node
        [field] => nid
        [alias] => nid
        [count] => 1
      )
    )

```

# Answer
Using `hook_query_views_alter` is something you should do with care as it can very easily come back and bite you when you least expect it. Trust me, I have tried this on some occasions.

`hook_query_views_alter` is powerful as you can create any query you want, but it should be used like the name suggests, as an alteration. It's not meant to be used by creating a view with an arbitrary query and then completely create the actual query from scratch in the alter hook. This will lead to many confusing moments, like *why does the view display something different than what I set up, and why doesn't it change when I change it*.

The query from the View looks something like this:

```
SELECT nid, title, created FROM {node}
WHERE type IN ('provider') AND status = 0

```

Compared to

```
 SELECT content_id, COUNT(*) as count FROM {votingapi_vote}
 WHERE value_type = '%s'  AND value = 1
 GROUP BY content_id;

```

There are two ways to solve your problem, without having to sort to nasty hacks in the hook\_views\_query\_alter function that will be hard to maintain, and probably will give you or the next developer problems down the road.

1. **Use the node table and create a JOIN**

The voting api has Views integration but doesn't support that you query the table with views, using it as the base table. It does however support that you create a join (relationship). Most likely you are voting on nodes. If that is the case you can create a base view from nodes and add in the votes as a relationship. See below SS of how to add the relationship and the fields needed.

SS http://tardis1.tinygrab.com/grabs/99f4a5fef7b5f963fa6a64f0be8ad451af21915caf.jpg
2. **Add info to views about voting tables**

With `hook_views_data_alter`, you can add the needed info about the voting tables to be able to query them directly. Views documentation has great examples of how this is done. Then you could create a view that queries the votes and via the Views interface create a query similar to what you posted.
> 2 votes

# Answer
Try this, First Go with Views as googletorp. It will also helps you

```
   function custom_views_query_alter(&$view, &$query){

    if($view -> name == "SomeView"){

      $sample_query = db_query("SELECT content_id FROM {votingapi_vote}
          WHERE value_type = '%s'  AND value = 1
          GROUP BY content_id;", "option")->fetchField();

      array_push($query->where[2]['conditions'],array('field'=>"node.nid","value"=>array_unique($sample_query),"operator"=>"IN"));

    }

   }

```
> 0 votes

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


# Question
Title: Date field with granularity of Month, Year in Exposed filter, how to alter the default value?
I have a Date field with granularity of Month, Year in Exposed filter. Everything is working fine, but the month and year default values are shown as "-Month" and "-Year".

Let me know how to alter the form to remove the "-" from Month and Year filter.

# Answer
> 2 votes
One method would be to alter the exposed filter form date\_select form element. Add this to a custom module:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
   $form['#after_build'][] = 'views_exposed_form_date_select_alter';
}

/**
 * Alter the label option on Year/Month selector
 */
function views_exposed_form_date_select_alter($form, &$form_state) {
   $form['MY_DATE_FIELD']['year']['#options'][''] = 'Year';
   $form['MY_DATE_FIELD']['month']['#options'][''] = 'Month';
   return $form;
}

```

---
Tags: views, datetime
---


# Question
Title: Hide the "view exposed filter" form or reload the page after submit the form?
I am using view exposed filter on a view display as "block". The block is added to dashboard.

I added a second function to "Apply" button using `hook_form_alter`. I want to hide the expose form of `view` after submit it. I added the jquery to hide the element using `drupal_add_js`. But it didn't work.

Is there any way to hide the form or reload the page after submit of expose form so i can hide the form on page load?

# Answer
> 0 votes
Try this:

```
function custom_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-YOURVIEWNAME') {
    if($_GET['xxx'] == 0){
      hide($form);
    }
  }
}

```

---
Tags: 6, ajax, views
---


title: Webform hours/time field

text:
# Question
Title: Webform hours/time field
How do you add a field where user can set hours when it's best to call for contacting. The Date field gives only days, months and years.

In this thread Webform: Time Field - Changing Variable Increments he states he has some time field for his Webform. But I can't track it down which module is that?

# Answer
Webform module have time field by default.
> 1 votes

---
Tags: 7, entities, webforms
---


title: Override taxonomy term path with Views

text:
# Question
Title: Override taxonomy term path with Views
I need to override by views my hierarchical taxonomy term paths:

```
www.example.com/[vocabulary name]
www.example.com/[vocabulary name]/term1
www.example.com/[vocabulary name]/term1/term2
www.example.com/[vocabulary name]/term1/term2/term3

```

Where

```
term1 has depth = 0
term2 has depth = 1
term3 has depth = 2

```

Vocabulary terms:

```
+ term1
-- + term2
---- + term3
---- + term3.a
---- + term3.b
-- + term2.a
-- + term2.b

+ term1.a
-- + term2.c
-- + term2.d
-- + term2.e

```

Paths have been configured by Pathauto

If the path leads to term with `depth = 0` I'm using view display "Page".

If the path leads to term with `depth = 1` I'm using view display "Page - category".

If the path leads to term with `depth = 2` I'm using view display "Page - subcategory".

I tried to use Taxonomy Views Integrator to override the paths by Views, and it's working, but there is one disadvantage in this solution:

If I add a new content and create a new term (with the help of the Simple hierarchical select module ) then I'll be forced to edit this term and select the appropriate view to override this term path. It might be very time consuming with many terms, so I'm looking for another solution.

**How to set a view display for a specific term depth?**

# Answer
> 1 votes
I've found the solution by myself. It works without the TVI module.

**Useful, but not required modules:** Taxonomy Menu Block

This module allows to create a menu out of your taxonomies and comes with its own theme function and a few hooks (see the .api.php file) that allows you to alter the generated data to your needs. One of these hooks will be used by this solution.

## In genereal there are four steps of this solution:

1. Install the Taxonomy Menu block module if needed.
2. Change the taxonomy term path of specific terms depending on their depth.
3. Create appropriate aliases or update them if they are already exist.
4. Set the new taxonomy term path for a specific view display.

## Step by step

**Install the Taxonomy Menu Block** and go to: `admin/structure/block/add-taxonomy-menu-block`, do some settings and save it.

**Change the taxonomy term path of specific terms depending on their depth.**

Here I'm looking for parents only. If they're exist, that means the term is a child. Otherwise, it is a parent.

```
function YOUR_MODULE_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = 'YOUR_MODULE_taxonomy_term_uri';
}

function YOUR_MODULE_taxonomy_term_uri($term) {
  switch ($term->vocabulary_machine_name) {
    case 'YOUR_VOCABULARY_MASHINE_NAME':
      $parents = taxonomy_get_parents($term->tid);
      if (empty($parents)) {
        return array(
          'path' => 'taxonomy/category/' . $term->tid,
        );
      }
      else {
        return array(
          'path' => 'taxonomy/subcategory/' . $term->tid,
        );
      }
    break;
  }
  // default taxonomy term uri
  return taxonomy_term_uri($term);
}

```

**Create appropriate aliases or update them if they are already exist.**

Go to: `admin/config/search/path/patterns` and set the pattern for all your vocabulary paths: `[term:vocabulary]/[term:parents:join-path]/[term:name]`

**Important:** If you already had pathauto running before having this issue you must rebuild the aliases by going to the `delete aliases` tab and deleting the old aliases for "Taxonomy term paths", then go to the `bulk update` tab and updating the "Taxonomy term paths".

**Alter taxonomy menu block links**

Unfortunatelly, if we change the default taxonomy term path, then neither menu created by the Taxonomy menu nor the Taxonomy Menu Block (TMB) module won't be able to replace system paths by their aliases, but luckily, the TMB allows us to alter the links to our needs:

```
function YOUR_MODULE_taxonomy_menu_block_tree_alter(&$tree, $vid) {

  $vocabulary = taxonomy_vocabulary_load($vid);
  if ($vocabulary->name == 'YOUR_VOCABULARY_MASHINE_NAME') {
    foreach ($tree as $tid => $term) {
      switch ($term['depth']) {
        case 0 :
          $tree[$tid]['path'] = drupal_get_path_alias('taxonomy/category/' . $tid);
          break;
        case 1 :
          $tree[$tid]['path'] = drupal_get_path_alias('taxonomy/subcategory/' . $tid);
          break;
      }
    }
  }
}

```

**View page settings**

In order to use different view display for a specific term depth you need to set the appropriate path under "Page Settings" for each display. For example:

View displays:

Main category page -\> path: `taxonomy/category/%`

Subcategory page -\> path: `taxonomy/subcategory/%`

**Notice:** you can't use `taxonomy/term/%` path any more, because now these specific terms have their own paths.

**That's it!**

In this solution both parent and child terms have their own view displays, so now you can add some new content and associate new terms to it using the simple hierarchical select only.

# Answer
> 1 votes
I think you are making a little mistake that confuses you.

TVI does not allow to define a view for the vocabulary itself so the path www.example.com/\[vocabulary name\] cannot be handled by the module. The vocabulary settings are the default ones for all terms within the vocabulary. These settings can be overriden for each term and can be inherited with the latest version. If you want a specific view for your entire vocabulary, you will have to create it by yourself because no vocabulary page exists by default in Drupal.

If I get your problem described in this post and on drupal.org (https://drupal.org/node/2066015) I can suggest you the following :

* Define view1 as a page display and give it the path related to your vocabulary's name
* Define view2, view3 dans view4 using any path of your choice, it does not matter as TVI will call them directly
* Define view2 as the vocabulary's default view
* Define view3 and view4 as term's specific settings if needed

When trying to show a term page, TVI will do the following :

* If the term has TVI settings, use it
* Else find its first parent having a TVI setting with the "override" option and use it
* If no parent is found, use the vocabulary's TVI settings

If I take your drupal.org sample you will have :

**Terms**

```
Vocabulary (view2)
T 1 (no settings)
    T 1.1 (view 3, not inheritable)
        T 1.1.1 (no settings)
    T 1.2 (view 4, inheritable)
        T 1.2.1 (no settings)
    T 1.3 (no settings)
T 2 (no settings)

```

**Results**

```
T 1 (view 2 from vocabulary)
    T 1.1 (view 3 from itself)
        T 1.1.1 (view 2 from vocabulary)
    T 1.2 (view 4 from itself)
        T 1.2.1 (view 4 from T 1.2)
    T 1.3 (view 2 from vocabulary)
T 2 (view 2 from vocabulary)

```

I hope this will help you to achieve what you want to do.

# Answer
> 0 votes
Try these short workaround called **Taxonomy Views**

Create a module with the following files.

**taxonomy\_views.info**:

```
name = Taxonomy Views
description = It gives links like taxonomy/[vocabulary machine name]/[term id] to taxonomy term pages, so you can set up many Views for taxonomy pages. You can create two Views with paths "taxonomy/products/%" and "taxonomy/news/%" and enable vocabulary verification for each View, for example.
core = 7.x

dependencies[] = taxonomy
dependencies[] = views

```

**taxonomy\_views.module**:

```
<?php

/**
 * @file
 * Views for taxonomy pages.
 */

/**
 * Implements hook_menu().
 */
function taxonomy_views_menu() {
  $items['taxonomy/%taxonomy_vocabulary_machine_name/term/%taxonomy_term'] = array(
    'title' => 'Taxonomy term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'taxonomy_term_page',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'file' => 'taxonomy.pages.inc',
    'file path' => drupal_get_path('module', 'taxonomy'),
  );
  return $items;
}

/**
 * Alter the entity info.
 *
 * Modules may implement this hook to alter the information that defines an
 * entity. All properties that are available in hook_entity_info() can be
 * altered here.
 *
 * @param array $entity_info
 *   The entity info array, keyed by entity name.
 *
 * @see hook_entity_info()
 */
function taxonomy_views_entity_info_alter(&$entity_info) {
  if (isset($entity_info['taxonomy_term'])) {
    $entity_info['taxonomy_term']['uri callback'] = 'taxonomy_views_term_uri';
  }
}

/**
 * Entity URI callback.
 */
function taxonomy_views_term_uri($term) {
  return array(
    'path' => 'taxonomy/' . $term->vocabulary_machine_name . '/term/' . $term->tid,
  );
}

```

Now you can create Views for paths like "taxonomy/\[vocabulary-machine-name\]/term/%" and set pathauto alias to `[term:vocabulary]/[term:parents:join-path]/[term:name]`.

It's good, because you can set a View for a path `taxonomy/products/term/%` and enable vocabulary verification (check vocabulary is "products").

In addition, the old taxonomy term url is still available (`taxonomy/term/%`).

# Answer
> 0 votes
Creata a general Views for a taxonomy term display (it has nothing to do with the path, since the internal path is always "taxonomy/term/%tid". Pathauto paths have nothing to do with thhis) and use a views **Filter** to use it only if the term belongs to a Vocabulary or anything you prefer.

Then clone this Views and change the filter for another views display.

# Answer
> 0 votes
my solution is redirect it to our own views path in `hook_init`

if my views path is `category/%` then something like below code help

```
function hook_init(){
    /// redirect to category
  if(preg_match('/taxonomy\/term\/([0-9]+)$/',current_path(),$matches)){
       drupal_goto('category/'.$matches[1]);
  }
}

```

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


title: theme hook_suggestions not woking

text:
# Question
Title: theme hook_suggestions not woking
I have a content type called event\_page. In event, I have a drop down for selecting templates.

In the templates folder of my active theme, I have included my custom tpl.php files, such as node--event-page--default.tpl.php and node--event-page--blank.tpl.php.

I have used strreplace to remove 'node--event-page--' and '.tpl.php' to populate the types like bank and default from the files in the templates drop down.

Now I am using hook suggestions to take these theme on form submit, but it seems to not working

```
if (isset($variables['node'])) {
  $node = $variables['node'];
  $field_template_list = $node->field_template_list->und[0]['value'];
  if ($node->type == 'event_page') {
    $variables['theme_hook_suggestions'][] = 'node__event_page__' . $field_template_list;
  }
}

```

# Answer
> 1 votes
I hope I understood your question correctly, that you want to apply theme on form submit.

theme\_hook\_suggestions is used when a template is being rendered. I think you don't need to save it on form submit. You just need to provide logic of selecting a template file in preprocess function of template.php file. Drupal looks for the suggested template file to apply to particular page/node etc

As a pseudo code, it would be

```
if(template_type is default)
   apply default type
else if(template_type is blank)
   apply blank type

```

For help, visit this link https://www.drupal.org/node/1089656

Moreover, the example of preprocess function is as follows

```
function THEME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

---
Tags: theming
---


title: Permission Issues for User 1

text:
# Question
Title: Permission Issues for User 1
I have added pages, webform, and views to my site to customize the User profile experience. I can access mysite.org/user and it shows my user profile page as customized. I have a link on that page to Edit the user profile which is formatted as mysite.org/user/1/edit this works fine. I also have realname module installed so the Edit button on the User profile tabs has the url mysite.org/user/my-real-name/edit This link does not work. It gives an access denied when used even from the User 1 account. I have researched this over and over and over. I can't find the cause or the fix. Any ideas?

I've checked permissions, I've gone through the panel page, the view. I've disabled things and tried it and still issues. I'm at a total loss on what to do.

# Answer
I don't think Real Name does what you think it does. At least not by default. The module is primarily for using parts of the user account other than the username when the user account is displayed (such as the by-line on an article).

You can set the edit link to send people to `mysite.org/user/my-real-name/edit` but unless you've done something to make that URL exist, which I'm not sure you can do with this module, it won't do anything.
> 0 votes

# Answer
This has nothing to do with the Real Names module. There are 2 Types of links in Drupal:

* system links like **/user/1** or **/node/240**
* and alias links like **/user/johndoe** or **/content/about** (they point to system links and are generated by modules like Pathauto)

While most of the site is accessible via alias links generated by pathauto, certain admin links require arguments on the system link: **/content/about/edit** does not work – **/node/240/edit** is the correct link, because there is no alias for the edit link.

Same with the user page: You can't mix system links (accepting special arguments like **/edit**) with path aliases. The only way to do that would be to generate a separate alias for all argument links (e.g. an alias for **/node/240/edit**, **/node/240/delete**) – some sites actuallay do that, via Rules for example.
> 0 votes

---
Tags: views, users, panels
---


title: relative url path

text:
# Question
Title: relative url path
In my anchor tag I have hard coded like this `<a href="/escorts'.my_link'"`, I want to get the relative url path. Whenever if the path is some like this in the url `http://drupal.stackexchange.com/questions/ask` and I clicked on the above mentioned link then instead of `http://drupal.stackexchange.com/questions/ask/my_link` it gives me `escorts/my_link`. I know I did not convey my question properly. Hope anybody get my scenerio. Thanx

# Answer
I didn't fully understand your question. But I imagine two cases:

1. If you need a url that works in any page on your website, no matter where you are, you need to use this code:

```
<?php
        global $base_url;
?>
       <a target="_blank" href="<?php print $base_url;?>/escorts'.my_link'"

```
2. On the other hand if you want to attach the url to the current address, use this code

```
<?php

        $path = current_path();
?>
       <a href="<?php print $path ;?>/escorts'.my_link'"

```
> 0 votes

# Answer
Just use the l function it will take care of everything for you, in your example use:

```
print l('Text', 'escorts/' . my_link);

```
> 0 votes

# Answer
Solution:

It will be like this

```
print l('Anchor text', 'my_link');

```
> 0 votes

---
Tags: 7
---


title: Ajax slideshow for D7?

text:
# Question
Title: Ajax slideshow for D7?
I am looking for some kind of Ajax-based slideshow/banner module for D7 for a changeable front-page photo banner. Unfortunately neither Views Slideshow Ajax nor Ajax Slideshow have been ported to D7 yet. I have several megabytes of photo content and would like to load each image on demand, not load them all at once (which is, as I understand, how most of the slideshow modules work). Right now I am just using a view that returns a randomly-chosen image, but I'd rather have it cyclable by the user with arrows or by a timer.

Are there any existing D7 modules that do something like this? There are so many slideshow, banner, and gallery modules: I may have missed the one I need.

# Answer
> 1 votes
The Views Slideshow module relies on the Cycle library, if I'm correct. It supports AJAX / progressive loading in it's current version as seen here:

In my experience, a lot of Drupal modules make the integration of library options unneccessarily complex:
So you could just generate the necessary code via views instead and load the lib yourself via template. Most current slideshow scripts support AJAX loading, so you can choose one that suits you.

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


# Question
Title: How can I add a field to a view description
I'm running into a quite simple problem : I would add fields to a view description, in order to list my views by this field.

Example : add a taxonomy field to the views, let's say "View color". Then, I would create a view of views, only for the views having a color, ordered by their colors and letting me see a XML containing the color and a link to the view's page :

```
<...>
    <view>
        <color>red</color>
        <link>http://example.com/path-to-red-view</link>
        <color>blue</color>
        <link>http://example.com/path-to-blue-view</link>
    <....>
</...>

```

I don't want to generate the links by rewriting (I know how to do that), but really add a field to the views.

The question is a bit wobbly, but I don't figure out how to write it. I found nothing on the web describing what I want to do, maybe due to that.

Thereby, all help is welcome !

Thanks

# Answer
I don't know that it will provide all the functionality you are looking for, but you could look into Views Field View:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
> 0 votes

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


# Question
Title: Deleting a node just after it has been added
I want to delete a node after it has been added (or modified), if certain conditions happen.

Is it possible to do that with `hook_node_insert`? (Considering `hook_node_insert` will actually be executed just before the node is added to the database.)

# Answer
With a bit of twist, I have managed to find a solution (it is not ideal but it works fine):

Instead of checking the conditions after inserting a new node, I have changed the algorithm to validate the node by using *hook\_node\_validate* to avoid saving the node if the conditions have not been met!

In that way I apply my conditions in another function (*YOURMODULE\_validate\_pipeline()*) by checking two reference values against some conditions. I use another variable to check if the conditions have been met (TRUE/FALSE) and set a suitable message accordingly! In my case the type of node was one of main factors to apply different conditions(you can use it in different scenario really)! Here is the code (hope it can help people with similar problem):

```
/**
 * Implements hook_node_validate().
*/
function YOURMODULE_node_validate($node, $form, &$form_state) {
  $YOUR_node_validated = array('validated' => TRUE,
                                 'message' => t('Node has been saved successfully'),);
  switch ($node->type) {
    case 'my_first_type':
      $YOUR_node_validated = YOURMODULE_validate_pipeline($node->field_one[$node->language][0]['target_id'],
        $node->field_two[$node->language][0]['target_id']);
      break;

    default:
      // code...
      break;
  }
  if (!$YOUR_node_validated['validated']) {
    form_set_error($node->type, $YOUR_node_validated['message']);
  }
}

```
> 1 votes

# Answer
I think Rules module will be helpful for you in this kind of scenario. Rules module help us to define actions on different events(like user creation, node creation/updation/deletion). It is a very powerful module.
> 3 votes

# Answer
You can use hook\_view() since this hook is going to be called just after insert/update a node(If you have not changed default behavior after inserting a node). You can add a condition to check the user authority before execute your code.
> 0 votes

# Answer
There seems to be a module that provides post-save hooks... Hook Post Action.

According to its description:

> Currently Drupal core does not offer any hook to do actions after a node/entity is insered/updated/deleted in Database. So this module introduces several new Drupal hooks to overcome this limitation
>
> * hook\_entity\_postsave
> * hook\_entity\_postinsert
> * hook\_entity\_postupdate
> * hook\_entity\_postdelete
> * hook\_node\_postsave
> * hook\_node\_postinsert
> * hook\_node\_postupdate
> * hook\_node\_postdelete

(seen on StackOverflow: https://stackoverflow.com/a/24035797)

Hope it helps,
> 0 votes

---
Tags: hooks, nodes
---


# Question
Title: How to remove chosen comma between taxonomy
How can I remove comma from theese ingrediens and let them float left? I am using chosen for my taxonomyes

# Answer
You need to go to the content type's display settings and change the display format.

```
/admin/structure/types/manage/article/display

```

is an example url you might go to to edit the `article` content type display settings.
> 1 votes

---
Tags: taxonomy-terms
---


title: Help with a custom field widget

text:
# Question
Title: Help with a custom field widget
I am trying to create a custom field widget to be used by the taxonomy term reference field. Basically I would like to select which taxonomy terms can be shown in the select list.

So far I am able to register the widget along with a custom settings page but when I use the widget on a node edit form. The values are not saved.

Here is the code below I have implemented a hook\_widget\_info hook\_widget\_settings\_form and hook\_field\_widget\_form from my understanding those three hooks should be enough

```
function my_module_field_widget_info() {
  return array(
    'my_module_term_reference_limit' => array(
      'label' => t('my module Term reference select'),
      'field types' => array('taxonomy_term_reference'),
      'description' => t('Allows you to limit the number of terms allowed in a select list'),
    ),
    'settings' => array(
        'terms' => array(),
      ),
  );
}

function my_module_utils_field_widget_settings_form($field, $instance) {
  $widget = $instance['widget'];
  $settings = $widget['settings'];
  $vocabulary = taxonomy_vocabulary_machine_name_load($field['settings']['allowed_values'][0]['vocabulary']);
  $type = $instance['widget']['type'];
  $terms = taxonomy_get_tree($vocabulary->vid);
  $options = array();
  $default_value = array();

  foreach($terms as $key => $term){
    $options[$term->name] = t($term->name);
  }

  $form = array();
  if($instance['widget']['type'] == 'my_module_term_reference_limit') {
    $form['terms'] = array(
      '#type' => 'checkboxes',
      '#title' => t('My module terms'),
      '#options' => $options,

      '#description' => t('Select compatible templates'),
  );
}
  return $form;
}

function my_module_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $settings = $instance['widget']['settings'];

 $type = $instance['widget']['type'];

  $options = array();
  foreach($settings['terms'] as $key => $value){
    if($value !== 0){
     $options[$value] = t($value);
   }
 }

$widget = $element;

  switch ($instance['widget']['type']) {
    case 'ii_term_reference_limit':
      $field['cardinality'] = 1;
      $widget += array(
       '#title' => t('my term select box'),
       '#type' => 'select' ,
       '#options' => $options,

  );
      break;
  }

  $element +=  $widget;
  return $element;

}

```

Thank you for your help

# Answer
Looks like you're just missing the column name for the field (`tid`).

Just before the return of the widget form function, try changing

```
$element +=  $widget;

```

to

```
$element['tid'] = $widget;

```
> 1 votes

---
Tags: entities
---


# Question
Title: Print Drupal Statistics in node template?
When the (core) statistics module is enabled, we get a '50 reads' at the bottom of each node.

Is there any way I can pull that '50' (the node view count) and print it in a node template?

I want to accomplish this without a contribute module.

Any ideas?

# Answer
> 3 votes
The statistics module provides that data through `statistics_get()`, which returns

> An associative array containing:
>
> * **totalcount**: Integer for the total number of times the node has been viewed.
> * **daycount**: Integer for the total number of times the node has been viewed "today". For the daycount to be reset, cron must be enabled.
> * **timestamp**: Integer for the timestamp of when the node was last viewed.

e.g.

```
$stats = statistics_get($nid);
$total_count = $stats['totalcount'];
$day_count = $stats['daycount'];

```

To get it into a node template, implement `hook_preprocess_node()`, `hook_node_view_alter()`, or `hook_node_view()` (the latter will need to be in a custom module, the other 2 can go in a theme or module).

`hook_preproces_node()` example:

```
function MYTHEME_preprocess_node(&$vars) {
  $stats = statistics_get($vars['node']->nid);
  $vars['stats_total_count'] = $stats['totalcount'];
}

```

And in the template

```
<?php echo $stats_total_count; ?>

```

You'll need to clear Drupal's cache after adding the hook so the theme registry picks it up.

---
Tags: 7, nodes
---


# Question
Title: Panelizer: displaying node reference field
I have an "Event" content type with a node reference field of type "Host".

"Host" content type has an "Affiliation" field.

I would like to display the event details though Panelizer, so that it would show not only the host name, but also their affiliation. How can I access a node reference field through panelizer?

My guess is that it should be done though the "Existing Node" option, but I might be wrong.

# Answer
You'll have to create a custom formatter where you can control the output of the node reference. To create a custom formatter follow this tutorial: http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-formatters

After that in panels when you add the node reference you can choose the custom formatter you've created:
> 1 votes

---
Tags: views, nodes, panels
---


title: Where are hooks stored/cached?

text:
# Question
Title: Where are hooks stored/cached?
I have a `hook_form_alter` in a module, and it should be firing, but it appears it's not. I've cleared caches and rebuilt the registry. Is there someplace in the database or somewhere else where I can see if my hook is registed? FWIW here is my hook:

```
/**
 * Implements hook_form_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
}

```

# Answer
The hook implementations **ARE** cached inside the database.. this is why it's necessary to clear cache in order for a newly implemented hook to fire.

Taking a look, inside the `cache_bootstrap` table, there is a row with `cid` value of `module_implements`, and it's `data` value is a very large serialized string. When unserialized, it is an array of the form

> 'hook\_name' =\> array('module1', 'module2', 'module3', ...)

The hook names have the `hook_` beginning lopped off, so `hook_block_info()` will appear as `block_info`. I believe the value is the list of modules which implement that hook, so...

> 'block\_info' =\> array('views', 'webform', 'my\_module')

Means that the following hooks are registered and should be fired:

```
views_block_info()
webform_block_info()
my_module_block_info()

```
> 10 votes

# Answer
If you're running drush, you could try fn-hook. That will print out a list of all the modules that are using a given hook. At the very least this will tell you if the Drupal thinks the module is using the hook
> 2 votes

---
Tags: hooks
---


# Question
Title: Views Filter Content Type Drop down option sorting
I have a view to with the Filter of Content Type in drop down and based on selection it is displaying the nodes.

Now I need to alphabetically order the Content Type options into Filter Drop down.

Currently the content type listed into drop down as

* Press Release
* News
* Event

and I need to display it as

* Event
* News
* Press Release

There is no such way I found into views configuration. Do any one have idea how to do so ?

# Answer
One solution here is to use the `Grouped filters` option the `Filter type to expose` setting. In each grouped filter you can use the Is one of... operator and select the type. Grouped filters have weights that you can drag around to any arbitrary ordering.

As an example, here's a reverse ordering of content types:
> 0 votes

---
Tags: views
---


title: Views attachments and filters

text:
# Question
Title: Views attachments and filters
I've created a view from geocoded nodes which shows nodes on a map. I've also created an attachment view which I've attached to this map view. This is to have a listing under the map view to make items more accessible.

However, I can't get that to work properly e.g. filter properly. The following describes filters on the map view:

* Content: Geocodes (field\_geocodes) - proximity (exposed)
* Content: Date(Exposed Popup date) | Setting
* Content: EventType (exposed)
* Content: Type (= Event)
* Content: Published (Yes)

On the attachment view I checked that it inherits contextual filters and filters. However,

* I'm no aware that is it inheriting filter values e.g. that I need to create those filter again in this view?
* Or does inherit whole filtering as is?

Anyhow, attachment results won't filter and shows all from first published node or by changing view settings it won't show anything i.e. filters and there's no results.

# Answer
if Inherit exposed filters and Inherit contextual filters in Attachment settings is set to Yes then it will inherit filters and it's values
> 0 votes

---
Tags: views
---


# Question
Title: How do I remove comments from an existing webform?
After the fact, I learned how to make comments `<hidden>` by default for new webforms. However, for the forms I've already created, there is no option to remove comments. How do I remove comments for these already published forms? Do I have to make a whole new form, or edit the database directly somehow?

Thanks for any help, and please let me know if there is any other information I need to provide.

# Answer
> 2 votes
No need to do either; you can edit any existing webform and toggle the `Comment settings` menu to `Hidden` on each published form.

# Answer
> 2 votes
If you really want to delete those comments you could build a View and include a Views Bulk Operations field and then using filters find all comments of nodes of type Webform, and bulk delete them

# Answer
> 1 votes
You need to delete all the comments on that node. There might be a lot of comments in lots of webforms. So to make your task easy follow below steps:

1. Download module admin\_views and enable it.
2. Go to `admin/content/comment` and run a search based on the title of the node, then delete all the comments. See in image

---
Tags: forms, webforms, comments
---


# Question
Title: Why is my field not showing up in the template?
I created a new field of the type Link for the Basic page content type and the field name is field\_secondary\_links.

All the pages on the site operate based on custom templates and I edited node--page.tpl.php in order to show the links on the page. I added this:

```
<div id="secondary-links"><?php print render($content['field_secondary_links']); ?></div>

```

The div appears in the HTML structure, but it turns out empty, even though I know for sure the fields aren't empty. What am I doing wrong?

Using print\_r($node), I found out the field is indeed there:

```
[field_secondary_links] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [url] => http://www.google.com
                            [title] => Link 1
                            [attributes] => Array
                                (
                                )

                            [html] => 1
                            [query] =>
                            [fragment] =>
                            [absolute] => 1
                            [display_url] => http://www.google.com
                        )

                    [1] => Array
                        (
                            [url] => http://ww.google.com
                            [title] => Link 2
                            [attributes] => Array
                                (
                                )

                            [html] => 1
                            [query] =>
                            [fragment] =>
                            [absolute] => 1
                            [display_url] => http://ww.google.com
                        )

                    [2] => Array
                        (
                            [url] => http://www.google.com
                            [title] => Link 3
                            [attributes] => Array
                                (
                                )

                            [html] => 1
                            [query] =>
                            [fragment] =>
                            [absolute] => 1
                            [display_url] => http://www.google.com
                        )

                )

        )

```

# Answer
> 2 votes
Your code is right. If field\_secondary\_links is in $content, it should be rendering it out. You might want to double check that the field is named correctly. If you have devel installed, try using `dpm($content)` to make sure the field is in there, that it is named right, and the the correct data is getting pulled in.

EDIT ======================================================= If $content is unavalible for whatever reason, you can still render this from $node, but it's a bit diffrent. Your code should look like this:

```
<div id="secondary-links"><?php  print render(field_view_field('node', $node, 'field_secondary_links', array('label'=>'hidden'))); ?></div>

```

You can remove the `array('label'=>'hidden')` from field\_view\_field() if you want the label to show up.

That should prerender and then render the field for you. Not sure why your $content is missing though, but this should be a workable work-around.

---
Tags: theming
---