# Question
Title: How to email all group members after a new node is added when using the Group module?
I have created one group using the Group module. In that group I have 1 node type and 3 members.

I want to send a confirmation email to group members whenever I add new nodes of that node type. How can I do that?

**Notes**:

# Answer
# Only using the Groups module

The Group module is an upcoming alternative for the Organic Groups module for D7, for which right now there is only a beta version available. **Remark**: the Groups, Communities and Co module (= GCC) is yet another alternative (with an official release for D7).

The Group module appears to be an interesting alternative, though it doesn't come with a lot (if any) documentation so far.

The best docu available, I think, is to read its sources. In doing so, I learned that its Group Invite submodule "*Allows **group members** to invite people into their group*", which will trigger appropriate eMails. Of course, that implies that the user who wants to send these invites, is already a group member. But this "function" is not really what you seem to be looking for (as per your additional comment to my answer here).

Instead, you want to "Send an email to group members of particular group when a new node is created". To do so, I'd narrow down your question to 3 sub-questions (= tasks), and try to implement this using the Rules module, as further detailed below ...

# Also using the Rules module

### Rules Event

That's easy, more or less out-of-the-Rule-box: ***When a new node is created***.

### Rules Condition

This is your **Challenge 1**: Only if "Node type of the created node belongs to some group".

### Rules Action

Create a Rules "component" to send an eMail (anybody can do that, right?). Here is a typical sample of such component (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "New node was added",
          "message" : "New node was added for content type ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

This is your **Challenge 2**: construct the "To" content of such eMail, i.e. all eMail IDs of all members of the group. That is what the value should be for `user-to-notify:mail` in the Rules component shown above.

# Write your custom Rule(s)

To address the above **Challenges 1 and 2**, you could write your custom module, in which you basically would do 2 things:

If you're looking for more Rules related coding samples, you may want to look at the Rules URL Argument module. Here is a quote about it (from its project page, bold markup added here):

> ... provides two rules **conditions** based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an **action** that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*".
> 3 votes

# Answer
Install and enable Rules module. Now you can see there is a already created inactive rule at admin/config/workflow/rules path. Just enable this rule and you are done.
> 1 votes

---
Tags: 7, users, emails, group
---


# Question
Title: How to fix the Feeds import error when trying to import a price field?
I have a little problem with Feeds module, I read a lot on forums how to fix this error but I can't find a fix...

I'm importing products to the shop, this module can import thing pretty well but when I add `list_price` or `sell_price` to the mapping the import is stuck.

I get this error:

> SQLSTATE\[HY000\]: General error: 1366 Incorrect decimal value: '' for column 'list\_price' at row 1

Yes I use CSV files, with `utf8 encoding`.

Don't know why I get this error I just write into the column for the price: 20.10

```
array(
  'név' => '100% BEEF Concentrate 1000g',
  'cikkszám' => '1',
  'description' => 'Tartalom',
  'image' => 'scitec_100_beef_concentrate_1000g_caramel_vanilla.png',
  'catalog' => 'Proteíny',
  'gyártók' => 'Scitec Nutrition',
  'nyelv' => 'sk',
  'súly' => '1000',
  'mértékegység' => 'g',
  'listázási ár' => '21.00',
  'akció' => 'uncheck',
  'kiemelt' => 'uncheck',
  'újdonság' => 'check',
)

```

Is this possible to fix somehow?

Another small question is that how can I check and uncheck chechboxes with feeds? What should I write into the CSV column?

# Answer
you should remove single quotes form decimal value and replace uncheck/check to false/true based on value.
> 1 votes

---
Tags: ubercart, feeds, importing-exporting
---


# Question
Title: How do I print the node creation timestamp in a computed field?
I want to store the node creation timestamp in a computed field. I know I should use `date_format()`, but I don't know which code should I use for the field value.

Which code should I use?

# Answer
> 1 votes
```
$timestamp = date($entity->created);

```

---
Tags: 7, nodes
---


# Question
Title: Spambots causing server crashes. How do I block them?
I have a Drupal 7 website on a shared hosting account that uses an Apache server. It is getting continuously battered by spam bots who try to post junk comments and create fake accounts. What methods can I use to block them from accessing the site and/or doing any operations there.

Currently, I have the following modules installed to block and combat spam:

Spambot - https://drupal.org/project/spambot

Spamicide - https://drupal.org/project/spamicide

Hashcash - https://drupal.org/project/hashcash

AntiSpam - https://drupal.org/project/antispam

Cloudflare - https://drupal.org/project/cloudflare

I tried installing Bad Behavior (https://drupal.org/project/badbehavior), but there appears to be some error in its installation procedure.

I do not want to use captcha to block spambots.

# Answer
This is better solved at the Apache level. The industry standard method for doing this is to create a honeypot directory, make it off-limits to bots in `robots.txt`, then logging the IP-address of those who still go there, and block it.

For an example of this, see the this page: http://www.kloth.net/internet/bottrap.php. You can set up this on shared hosting as long as you can edit `.htaccess`.

For a more sophisticated solution, take a look at Project Honeypot (NB: no relation to the Drupal **Honeypot** module). There is already an Apache module which interfaces with Project Honeypot's IP blacklist. To install this, you ned to have access to the Apache config (usually not available on cheap shared hosting).

Edit: There already exists a Drupal module, http:BL, that uses Project Honeypot's IP blacklist, that may save you some time setting this up (thanks to @vr3690 for pointing this out).
> 8 votes

# Answer
We have had great success with uncpatchalous and its successor http://dgo.to/BOTCHA. What's nice about these is that they do not impact "normal" users.

Disclaimer: our site doesn't allow comments or registration, but since installing the above on our Contact form, all bot-initiated SPAM has gone away.
> 2 votes

# Answer
Give the BadBot module a try. I'm the developer of it, and can pretty much guarantee it'll block spam registrations. Functionality for other form submissions isn't in place yet, but will be.

Jan 2nd, 2014 edit: BadBot now supports all Drupal forms.
> 2 votes

# Answer
I have recently started using the Bad Behavior module, which not only used Project Honeypot Blacklist feature but also allows from IP tracking and reasons WHY an IP was blocked. It has a few more features than the honeypot module by itself and combines those rather nicely.

Alternatively there is also the goAway module which lets you see the IP addresses of any comment or posts made on your site and block them directly via a link or a form in the admin section.

And then there is Mollum.com, which does all this 'sort of stuff' in the back and only presents you with a confirmation if it cannot determine if content added is spam or not. Free only for personal sites, but very affordable for organizations, etc.

Hope this helps.
> 1 votes

# Answer
I have the same issues. I was fighting with spam bot for 2 days, but now it's come to an end.

When I said end, its mean completely stop, spambot no longer able to access my site.

I use two module, **mollom and honeypot**.

Honeypot is the key here, the trick is to install honeybot and also **create a rules** which ban the spam bot IP when it fails in honeypot.

You just create a rules to trigger the IP ban when it fails to comply with honeypot.

On my site "recent log message" page, I was sit back and smile, when I saw the spam bot get banned many many times by my honeypot rules.

Hope it will help.
> 1 votes

---
Tags: security, advertising
---


# Question
Title: created block for image is not displaying
I created the block for a image where in I want to display in all pages, but after creating the blocks once I see the page the created block is not displaying.

Following method followed to create a block.

1\] Structure-\>Blocks-\>Add Block

2\]specified the name and browsed the picture( i have installed IMCE)

3\] and chosen to display in bottom fist and also in all pages then save the block.

But couldn't see the block in all pages, if any one know please help me.

# Answer
> 0 votes
when you create block then you have options for visibility where you want to show this block like below:

---
Tags: blocks
---


# Question
Title: RDF core module doesn't seem to work after security upgrade
I updated from Drupal 7.36 to 7.38 for security reasons. Now the nodes don't get displayed in RDF any more. For example: http://bartoc.org/en/node/112, add .rdf and you get the message "The requested page "/en/node/112.rdf" could not be found." The RDF core module is checked. Am I missing something?

# Answer
Here is a workaround at #9 that solved the problem for me.

> As workaround, you could use the RDFa Distiller and add the following code to .htaccess:

```
<IfModule mod_rewrite.c>
   RewriteEngine on
+  # call W3C RDFa Distiller to extract .rdf/.ttl/.nt files
+  RewriteRule (.*)\.rdf$ http://www.w3.org/2012/pyRdfa/extract?uri=http://%{HTTP_HOST}/$1&format=xml [L,R=307]
+  RewriteRule (.*)\.ttl$ http://www.w3.org/2012/pyRdfa/extract?uri=http://%{HTTP_HOST}/$1&format=turtle [L,R=307]
+  RewriteRule (.*)\.nt$ http://www.w3.org/2012/pyRdfa/extract?uri=http://%{HTTP_HOST}/$1&format=nt [L,R=307]
+
   # 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.

```

> ```
> Many thanks to jneubert!
>
> ```
> 1 votes

---
Tags: updating, rdf
---


# Question
Title: How to access block fields programmatically?
I display a block of type **Assignment** on the top of a page when I'm creating a node of type **Submission**. I need to access the fields of the **Assignment block** programmatically with my custom module.

**Are there any built in Drupal functions that will allow me to do so?**

I'm currently using `hook_form_alter()` but that does not give me access to the block elements.

# Answer
> 1 votes
I found the value by first grabbing the assignment value from the URL, then looking up the path to find the node id, then loading that node and using a wrapper to find the value of that specific field.

```
        $url = $_SERVER['REQUEST_URI'];
        $pos = strpos($url, '?') + 1;
        $assignment = substr($url, $pos, strlen($url)); //get the assignment from the URL

        $nodeID = drupal_lookup_path('source', "student-assignments-new/" . $assignment);//get the path from the assignment - e.g. node/145
        $pos = strpos($nodeID, '/') + 1;
        $nid = substr($nodeID, $pos, strlen($nodeID));//get the node id

        $node = node_load($nid);

        ~~$wrapper = entity_metadata_wrapper('node', $node);~~
        ~~$fieldValue = $wrapper->field_file_type_text->value();~~

        $output = $node->field_file_type_text[LANGUAGE_NONE][0]['value']; //field_file_type_text is my own field name
        return $output;

```

---
Tags: 7, blocks
---


# Question
Title: What does a/ and b/ stands for in patch header?
The first line of patches always has this kind of code:

```
diff --git a/i18nviews.inc b/i18nviews.inc

```

or

```
diff --git a/plugins/views_plugin_localization.inc b/plugins/views_plugin_localization.in

```

What does the a and b stand for?

# Answer
A' and the 'B' are prefixes to differentiate source and destination.

You can change the prefixes with

```
--src-prefix=<prefix>
Show the given source prefix instead of "a/".

--dst-prefix=<prefix>
Show the given destination prefix instead of "b/".

```

From http://git-scm.com/docs/git-format-patch
> 3 votes

# Answer
As a rule of thumb, just consider `a/` to refer to the "old" file (with filename indicated following the `a/`), and `b/` to refer to the 'new file (with filename indicated following the `b/`).

As an illustration, consider the patch attached to comment nr 15 in issue nr 1632898, which looks like so:

```
--- a/panels_ipe/plugins/display_renderers/panels_renderer_ipe.class.php
+++ b/panels_ipe/plugins/display_renderers/panels_renderer_ipe.class.php
@@ -137,7 +137,10 @@ class panels_renderer_ipe extends panels_renderer_editor {
   function render_pane_content(&$pane) {
     $content = parent::render_pane_content($pane);
     // Ensure that empty panes have some content.
-    if (empty($content) || empty($content->content)) {
+    if (empty($content) || !is_object($content) || empty($content->content)) {
+      if (!is_object($content)) {
+        $content = new StdClass();
+      }
       // Get the administrative title.
       $content_type = ctools_get_content_type($pane->type);
       $title = ctools_content_admin_title($content_type, $pane->subtype, $pane->configuration, $this->display->context);

```

In regular English you could say "Remove that 1 line from `a/` (indicated with '-', located at line 141 in a/`) and insert again these 4 lines from`b/\` (indicated with '+', starting from line 141)".

Some more details about the `-137,7 +137,10` part of this patch example: if you'd browse the `a/` (old) file, this is how these **7 lines** look like, starting from **line 137**,

```
class panels_renderer_ipe extends panels_renderer_editor {
   function render_pane_content(&$pane) {
     $content = parent::render_pane_content($pane);
     // Ensure that empty panes have some content.
     if (empty($content) || empty($content->content)) {
       // Get the administrative title.
       $content_type = ctools_get_content_type($pane->type);
       $title = ctools_content_admin_title($content_type, $pane->subtype, $pane->configuration, $this->display->context);

```

So to know what the content of `a/` actually looks like (by just looking at the patch), ignore the lines with a "+", and replace any "-" with a blank.

And if you'd browse the `b/` (new) file, this is how these **10 lines** look like, starting from **line 137**:

```
class panels_renderer_ipe extends panels_renderer_editor {
   function render_pane_content(&$pane) {
     $content = parent::render_pane_content($pane);
     // Ensure that empty panes have some content.
    if (empty($content) || !is_object($content) || empty($content->content)) {
      if (!is_object($content)) {
        $content = new StdClass();
      }
       // Get the administrative title.
       $content_type = ctools_get_content_type($pane->type);
       $title = ctools_content_admin_title($content_type, $pane->subtype, $pane->configuration, $this->display->context);

```

So to know what the content of `b/` actually looks like (by just looking at the patch), ignore the lines with a "-", and replace any "+" with a blank.
> 0 votes

---
Tags: version-control
---


# Question
Title: How to customize the "Remove" button in a multiple field (collection)
So, you have a field (collection, it's the same there) defined with unlimited values, and thus have an "add more" button and a row per distinct value. Let's call the field `termine`.

Now you have to theme the "remove" button in each row, e.g. to change the text to an imagebutton, and you wonder why your usual `$form['field_termine']['und'][$k]['remove_button']['#value']="Kill";` in `xxx_form_alter` does not stick when adding another row via AJAX.

# Answer
> 1 votes
The solution is easy, but it took me a couple of hours wading through Drupal Core nevertheless:

```
foreach($form['field_termine']['und'] as $k=>$v) {
  if(!is_numeric($k)) //we only want the individual items...
    continue;
  $form['field_termine']['und'][$k]['remove_button']['#value']="Kill";
}

```

Note that you will get in trouble with multi-language support with this, YMMV.

---
Tags: entities
---


# Question
Title: Changing label of views exposed date filter select list
Trying to change the label of a views exposed date filter based on Year granularity which is a select list. I have given date range to the filter thus it does not generate the "#options" array.

It creates a dropdown with year values and a "-Year" to display all values.

I want to rename this "-Year" label. Could not find any options within the view to change this label. So is there any hook or alter that can be used here ?

Yes i am using Better exposed filter and trying to use Date filter based on Content Post Date. After applying BEF i get a select list to the exposed date filter. I need to change the "-Year" label inside this dropdown. tried using hook\_form\_alter but not able to search this label and change it.

Attached a screenshot of the settings page for the Date filter. And under BEF settings I selected the Default select list option. Could not find any way to rename the "-Year" label.

# Answer
Looks like this is something we have already on drupal issue-queue as https://www.drupal.org/node/2296607.

I was expecting the options to be alterable by any hook, unfortunately could not find any.

I explored the code in date module, and found the elements are processed by a function as date\_parts\_element, under which it appending '-' before the label.

Now, while the following will fix your issue but I would nor recommend it to you until it is approved by community. The hack is

In your date\_api\_elements.inc file(date/date\_api) inside function `date_parts_element` add this line `drupal_alter('date_process_element', $sub_element);` in the bottom just before `return $element;` so it looks as

```
    .....
    if ($element['#date_label_position'] == 'within') {
      $sub_element['ampm']['#options'] = array('' => '-' . $label) + $sub_element['ampm']['#options'];
    }
  }
  drupal_alter('date_process_element', $sub_element);
  return $sub_element;
}

```

This will allow any custom module to alter the elements of date filter. Now in your custom module let's say named as my\_module implement the hook we have added as following

```
/**
  * Implements hook_date_process_element_alter.
 */
function my_module_views_date_process_element_alter(&$element) {
  foreach($element['year']['#options'] as $key=>$value) {
    if($value == '-Year') {
        $element['year']['#options'][$key] = 'Year';// Or whatever you like to give.
    }
  }
}

```

I will be adding the same suggestion on drupal issue page.

**Update**

Indeed no patch required, date module provides the hooks out of the box, got to know from update mentioned issue feeds, didn't try the cpde myself but looks promising

```
function MYMODULE_date_select_process_alter(&$element, &$form_state, $context) {
  // Tweak the -Year filter to remove the -
  if (empty($element['year'])) return;
  foreach ($element['year']['#options'] as $key => $value) {
    if ($value == '-Year') {
      $element['year']['#options'][$key] = 'Select Year';
      break;
    }
  }
}

```
> 1 votes

# Answer
You can use the following code in the template.php file

```
if ($form_id == "views_exposed_form"){
$form['your field_value']['#options']['All'] = t('your word');// overrides <All> on the dropdown }

```
> 0 votes

---
Tags: datetime, views
---


# Question
Title: Creating a loop condition in Rules for Commerce Line items
Certain products on the site can't be shipped using a certain shipping service as they are classified as **dangerous goods**.

So I need to be able to loop through all the items in the cart, check to see if the product has is marked as dangerous (`field_dangerous_goods` on the `commerce_product` entity), if any of the products in the order are marked as **dangerous goods** then that shipping service shouldn't be shown to the user.

I've tried with various different rule components to try and create what I need with not even a glimmer of hope.

# Answer
> 6 votes
Figured it out.

Firstly, you'll need Conditional Rules.

Create a new rule component.

For the variables, add Commerce Line Item as a Parameter and add a Integer as Provided.

Under *Conditions*, add Entity has field, select **commerce\_product**. Then add another *Entity has field* and select your **field\_dangerous\_goods** field from *line-item:commerce-product*. Lastly add a data comparison to check the status of the dangerous goods field. In my case I just had a checkbox, so I used **Data value is empty** and checked the **Negate** box.

This makes the condition return TRUE if the current line item is a dangerous item.

Under *Actions*, choose **Add action** and select the **Set a data value** option. For this set the parameter to the variable you created when you set up the component. Set the value to 1.

```
{ "rules_dangerous_goods" : {
    "LABEL" : "Dangerous goods",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "line_item" : { "label" : "Line Item", "type" : "commerce_line_item" },
      "dangerous_goods" : { "label" : "Dangerous Goods", "type" : "integer", "parameter" : false }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "line-item:commerce-product" ],
          "field" : "field_dangerous_goods"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "line-item:commerce-product:field-dangerous-goods" ] } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "dangerous-goods" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "dangerous_goods" ]
  }
}

```

Then for your shipping service rule, under *Actions*, choose **Add action**. Select **Add a variable**, I called mine **Contains Dangerous Goods (contains\_dangerous\_goods)**. Set the value to 0.

Add a loop.

Then **Add action** to the loop. Select your component. You'll need to set the variable name, this has to be different to the *Contains Dangerous Goods* variable from before, I just called mine **Dangerous Good (dangerous\_good)**.

Now choose **Add conditional** to the loop. Then for the conditional, choose **Add if**. Select the \*dangerous\_good\* which we just set in the loop in the component action. Set the value to 1.

Within the *If*, choose **Add action**. Select **Set a data value**. For the field, choose the **contains\_dangerous\_goods** value. This is the initial variable we set for the shipping service rule. Set the value to 1.

Now outside of the loop, **Add conditional**. Then **Add if**. Choose the \*contains\_dangerous\_goods\* field and set the value to 0.

Then within the *If*, add your shipping rate.

```
{ "commerce_shipping_service_standard_up_to_0_5kg" : {
    "LABEL" : "Rate Standard - Up to 0.5kg",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "commerce_physical",
      "rules",
      "rules_conditional",
      "commerce_shipping"
    ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "contains_dangerous_goods" : "Contains Dangerous Goods" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_dangerous_goods" : {
                "USING" : { "line_item" : [ "list-item" ] },
                "PROVIDE" : { "dangerous_good" : { "dangerous_good" : "Dangerous Goods" } }
              }
            },
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "dangerous-good" ], "value" : "1" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "contains-dangerous-goods" ], "value" : "1" } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "contains-dangerous-goods" ], "value" : "0" } },
            "DO" : [
              { "commerce_shipping_service_rate_order" : {
                  "shipping_service_name" : "standard_up_to_0_5kg",
                  "commerce_order" : [ "commerce-order" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

```

# Answer
> 2 votes
I'd recommend a different route for this. Create a view of Commerce Line items with a conditional filter of Commerce Order ID. Add a relationship to the Commerce Product to get access to the field (make it required). Add a "Bulk Operations: Line items" field so that we can access this under conditions within views (this requires you to have Views Bulk Options installed). Add a filter to show products with field\_dangerous\_goods.

Once you have created the view then add a condition "Check number of results returned by a VBO View". Specify the view you just created and then set the minimum number to evaluate to TRUE as 1.

This is a bit easier and there's only one condition to add to your rule. Sorry if this is a bit late to the party but this seems like it's a bit easier to deal with.

---
Tags: commerce, rules
---


# Question
Title: How to limit the results of a view with flagged content to the flagging user only?
I have created a view which displays a list of flagged content. I have used the Flag module to achieve this. I have named this page as **Bookmarks**, and the URL to this page is `http://example.com/user/%/bookmarks`. User should only able to access their own flagged content.

Consider this scenario:

* User A has his flagged content in `http://example.com/user/2/bookmark` (uid=2 for User A).
* This page should be accessible only by User A and the admin user.
* If User B tries to access `http://example.com/user/2/bookmark`, it should return **access denied**.

How can I get this to work?

# Answer
> 0 votes
Install Views PHP and set access to PHP, then add this code there:

```
global $user;
if(($user->uid == arg(1)) || ($user->uid ==1))
return true

```

# Answer
> 0 votes
ok i understand, you should add contextual filter like given below..

i hope this helps you.

# Answer
> 0 votes
To refine your view so that users can only access there own flagged content, perform these steps using the Views UI:

* Add the relationship "**Flags: Node flag**", which is used to "*Limit results to only those entities flagged by a certain flag; Or display information about the flag set on a entity.*".
* Next you need to "Configure" this relationship like so:
    + For "**Flag**" select the actual flag that you want this view to be about (e.g: select the "Bookmark" flag).
    + Make sure to set "**By**" = *Current user*.
* If you completed the previous steps correctly, in the Views UI you should now have an extra relationship added with something like "*Flags: bookmarks (by current user)*".

With this, "user will only be able to access their own flagged content", since these are the only possible views results that will be shown. Note however that with only these refinements, you will not get an **access denied** (only an empty views result).

**Notes**:

* This will return the same results for the admin user (= only the results flagged by the admin user). If the admin user should be able to see flagged content of any user, I suggest you clone this view in another one, in which you omit this "Flags: Node flag" relationship (or simply keep the view you already have, and limit its access to admin users only).
* With the above approach, the '%' in your URL has become obsolete.

---
Tags: users, views, flags
---


# Question
Title: Required taxonomy term fields for node publishing?
I want to create content which has shared some aspects. I am doing this through a taxonomy reference. The taxonomy has certain fields that describe each piece of content (in my case used cars).

In my workflow, I only want the content published if the taxonomy term reference has all its fields filled out. How can I automate this workflow?

# Answer
> 0 votes
This is a workflow requirement that can be handled by Rules.

1. Set your *user car* type set to unpublished by default.
2. Create a rule for the **event** *Before saving content of type User Car* (or whatever your node type is called)
3. Add a *Data value is empty* **condition**. On the **Data selector** you'll want something like *node:field-MYTERM\_FIELD:0:field-MYREQUIRED\_FIELD* (it depends on your field names). Make sure to check the **Negate** checkbox so that the rule is triggered when the taxonomy field IS NOT empty.
4. Add a *Publish Content* **action**.

---
Tags: taxonomy-terms, workflows, nodes
---


# Question
Title: Group entity reference field by a field on those entities
I have a content type of **Location** that has a list (text) field with options for **Full Service** or **Quick Stop**.

On another content type, I have an entity reference field that pulls in all the locations (using a select list widget).

On the node creation/edit form, I am trying to group those locations with optgroups into Full Service and Quick Stop based on the value of the nodes in the entity reference field (i.e. a location with **field\_location\_type** of "Quick Stop" would go into the Quick Stop optgroup).

Right now I am manually sorting them with the following, but it would be nice to do it automatically via my **field\_location\_type** field so that new options are automatically added.

```
$form['field_location']['und']['#options'] = array (
   'Full Service' => array(
      19 => 'Main Street',
      20 => 'Oak Hills',
      21 => 'Cherry Trail',
    ),
    'Quick Stop' => array(
      22 => 'Montreal',
      26 => 'Washington Place',
    ),
);

```

# Answer
Use the module Entityreference View Widget and set up a view with grouping based on location type.

Alternatively, using custom code:

```
// Grab our list of all possible location types.
$location_types = list_allowed_values(field_info_field("field_location_type"));
$options = array();

// Cycle through each location type.
foreach ($location_types as $location_type_key => $location_type) {
  // Find all the nodes that are set to use this location type.
  // You may need to adjust this query if you need to limit it to only nodes of a specific type in the event you use field_location_type on other content types that you don't want showing up in this list.
  $efq = new EntityFieldQuery();
  $locations = $efq->entityCondition('entity_type', 'node')
    ->fieldCondition('field_location_type', 'value', $location_type_key)
    ->propertyOrderBy('title', 'DESC')
    ->execute();

  // If any nodes are found with this location type, add them to the options array under the appropriate location type
  if (!empty($locations['node'])) {
    foreach($locations['node'] as $location) {
      $options[$location_type][$location->nid] = entity_label('node', node_load($location->nid));
    }
  }
}

$form['field_location']['und']['#options'] = $options;

```
> 0 votes

---
Tags: entities, forms
---


# Question
Title: Change user field value to value of another user field
I manage a basketball league site with two main user roles, "commissioner" and "player". Every player on the site is assigned to both a Tuesday team (field\_team) and a Friday team (field\_team2) via a user field, which is editable by commissioners. Because of player absences and other variables, the teams are usually different by the end of the week, so there are also two additional fields, Tuesday default team (field\_tuesday\_default) and Friday default team (field\_friday\_default).

See below for an example of what my Tuesday games page looks like to commissioners:

We start each week with a clean slate, i.e., every player back with their default team. Currently, at the end of each week our commissioners have to manually edit every player's user account to get their Tuesday/Friday team values back to the default.

See below for what a player's edit account page looks like to commissioners:

The problem is that it takes a long time and it is very tedious for commissioners to manually edit every player's user account to make their team values equal to their default team values.

Is there a way to programmatically change every user in the "player" role's Tuesday team and Friday team field values to equal their Tuesday default team and Friday default team values? All my research thus far has come up empty and I'm really at a loss at this point. Ideally, I would like to put a nice, big reset button on the Tuesday/Friday games pages that will perform the reset. Any help would be appreciated! Thanks.

# Answer
Yes

Programmatically you have to create a custom form with submit button as the only field, now inside the submit handler it will be 2 step process something as below

following code I have written just to give an idea, and assuming field names in a way you can relate. You have to do the tweaks to make it work for you

```
/**
  * Form Builder
 */
function _my_module_reset_team_selection($form, &$form_state) {
  $form = array();
  $form['reset_options'] = array(
    '#type' => 'select',
    '#title' => 'Reset Options'
    '#options' => array(
      'both' => 'Reset Both Teams',
      'ft'   => 'Reset Friday Team',
      'tt'   => 'Reset Tuesday Team',
    )
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Reset',
  );
}

/**
 * Submit Handler for your custom form.
 * 2 step process 1. Find Users to Update. 2. Update :)
 */
function _my_module_reset_team_selection_submit($form, $form_state) {

  // Logic to decide if to reset both or any one
  // possible values as 'both'/'ft'/'tt'
  $reset = $form_state['input']['reset_options'];
  // Step1. Get All the Users who are part of any team.
  $users_to_reset = _my_module_get_users_to_reset($reset);
  if (is_array($users_to_reset) && count($reset)) {
    // Step2. Update to Reset.
    switch ($reset) {
      case 'both':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_tuesday[$user->lang][0]['value'] = '';
          $user->field_friday[$user->lang][0]['value'] = '';
          user_save($user);
        }

        break;
      case 'ft':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_friday[$user->lang][0]['value'] = '';
          user_save($user);
        }
        break;
      case 'tt':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_tuesday[$user->lang][0]['value'] = '';
          user_save($user);
        }
        break;
    }
  }
}

/**
  *  Helper Function to get list of users to reset.
  *  Allows you to reset any of two Tuesday Team or Friday Team or both.
 */
function _my_module_get_users_to_reset($reset='both') {
  $get_tt_users = array();
  $get_ft_users = array();
  if($reset != 'ft') {
    $get_tt_users = db_select('field_tuesday_team','tt')
                 ->fields('tt',array(entity_id))
                 ->condition('tt.entity_type','user',"=")
                 ->execute()
  }               ->fetchCol();
  if($reset != 'tt') {
    $get_ft_users = db_select('field_friday_team','ft')
                 ->fields('tt',array(entity_id))
                 ->condition('tt.entity_type','user',"=")
                 ->execute()
                 ->fetchCol();
  }
  $users_to_reset = array_unique(array_merge($get_tt_users,$get_ft_users));
  return $users_to_reset;
}

```
> 0 votes

---
Tags: entities
---


# Question
Title: Drupal site Phonegap application field collection
I'm in the process of making a Phonegap application to create nodes of a certain content type. The site I'm writing data to/getting data from utilises Field Collection module, and I've looked at the database structure. It creates additional tables for the contained fields and cross-references them. I was wondering if anyone has come across this situation and how did you manage to solve it.

Note:

I'm using Drupal Services for endpoint, and my request needs to send all those fields in my fiddle altogether (more than one row).

As for what the fiddle does, I'm creating a table then add more rows to the table.

# Answer
> 1 votes
Make sure a field collection exists if you want to go through the Field collection module. When writing code make sure to use the field collection API. See the examples on Programmatically Adding a Field Collection Item to a Node in Drupal or Example: Programmatically adding field collection entries to a node.

You will have to use AJAX from your PhoneGap app, send the data you are collecting to your server, and use code to process and insert, as shown on Can I use PhoneGap jQuery to make AJAX calls?

# Answer
> 0 votes
You can send **JSONP Cross-domain Requests** using ajax call in your **PHONEGAP** application. Cross Domain Request

```
$.ajax({
    url: "http://remote.domain.com/data/?allback=jsonpcallback&id=123",
    jsonp: "jsonpcallback",
    dataType: "jsonp",
    data: {
    id: "123"
  },
  success: function(data) {
  console.log(data);
   }
});

 function jsonpcallback(data) {
  //do stuff with JSON
    console.log(data);
 }

```

Then you can get all post data and save to particular content type using drupal bootstrap.

---
Tags: entities, ajax
---


# Question
Title: How to send message using Organic Groups Invite?
I am trying to use the Organic Groups Invite module along with the Rules and Message modules to send a message to users containing an option to accept or decline an invitation to a group.

I have set up rules to send a message to the user when they are invited. This all works perfectly, however the message does not contain the accept / decline options that I assume come with the Organic Groups Invite Module.

I am new to Drupal, and since this module has no documentation, I wonder if anyone could help me out with adding the accept / decline option to the message.

# Answer
> 0 votes
Not sure if it is an option you're willing to consider, but the OG Invite People module might be used as a possible alternative for send such invitation to a group. Here is a quote from its project page:

> ... adds the missing email invite functionality for OG 7.x-2.x.
>
> When you click on "Invite user" a user is created and invited to the group right after. No registration process is needed. Invitee receives an email with one-time login link.

---
Tags: rules, organic-groups
---


# Question
Title: Publish tweets in drupal 7 site in real time
I need to publish tweets from twitter in my Drupal 7 site. I use twitter module but I need to publish this tweet in real time that's not the case with this module. Any one have an idea to fix this issue ??

# Answer
Try Selective Tweets. As written in comparison to another Twitter module (Tweed Feed), Selective Tweets renders Tweets almost realtime:

> Tweet Feed does periodic imports of Tweets and turns them into nodes, while *Selective Tweets* renders Tweets almost **realtime** and saves none of them in the database as content. This is also the main difference, with the effect that Tweet Feed has a significant delay on the **realtime** Tweets. On the other hand, the Tweet Feed created nodes can be displayed in Views which gives big flexibility in the way of displaying Tweets.
>
> Use *Selective Tweets* when you want a light weight manner of displaying Tweets without database storing and you want no major delay in displaying **realtime** tweets.
> 1 votes

# Answer
Have you looked at https://www.drupal.org/project/activitystream yet? This module will create each tweet as a node so that you could further customize a view to display them in any manner you wish. By looking at the module page, the hashtags for Twitter posts seem to carry over and display naturally, so I don't think you will run into the issues that I ran into with the Feeds module. The Feeds/Feeds Importer module didn't seem to understand specific characters, so I'm curious as to if this Activity Stream would solve your issue and also be able to interpret hashtags as well.

Let me know if it worked out well or if it didn't work at all. I'm curious about this myself and may install it on a local server/test and post back later on.

Note, it seems like Twitter may have changed their API recently since this module came out. There is an updated version of it by the community just for Twitter @ https://www.drupal.org/sandbox/denison/2269357

Hope this helps!
> 1 votes

# Answer
You need to use twitter module which post to their own twitter account or a site-wide twitter account whenever they create new content or based on drupal actions or rules
> 0 votes

---
Tags: 7, social-network
---


title: Certain views for specific user

text:
# Question
Title: Certain views for specific user
I have a page that shows content to all the users in my database but I have an specific username (exchangeStudents) and I want to show in the same page another view that filters the information for that account.

For example... my main page is: **www.housing.com** an when you login you can see **www.housing.com/houses** but I if you login as ***exchangeStudent*** you should be able to only see **www.housing.com/exchange-houses**

**www.housing.com** --\> all users **except** exchangeStudent

**www.housing.com/exchange-houses** --\> only for username: ***exchangeStudent***

# Answer
You can use login destination module, it is easy to use, you just need to create a rule where you can define after login specific role user can redirect to a specific page or you can use write php code too.

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.
> 3 votes

---
Tags: views, users, redirection
---


# Question
Title: How to customize the email subject for a webform?
I am using Webform 7.x-4.0 on Drupal 7.24 and I am trying to customise the email subject for my webform. I have followed the instructions as per the instructions in this post How to use \[submission:values\] in Email template in Webforms but when I save the settings, the email subject is blank.

I entered \[submission:values:event\_type\] for the custom field and my field key is as follows:

After saving the configuration, the field turns up blank.

The email sent out just shows -no subject given as the subject of the email.

# Answer
> 2 votes
So, I think you're using the UI wrong. Each of those email templates you have should be to a different user and it doesn't look like you've added an email to anyone.

Below where you have your Value of "Event Type" line there's the option to send an email to a specific email address (I.E the admin) or to add an email to the value of the Email token, you need to add and save an email to a specific person there and add a subject using your token substitution there. Or at least that's what it looks like from what you posted.

---
Tags: 7, webforms, tokens
---


# Question
Title: Layout of multiple items of the same field in Panels node template
My content type is a preview of a music album so the fields include mp3 file and text fields about the track (title etc). I am using a panels node template which looks like this

This works fine for one track and the result looks like this:

But if I add a second track it looks like this:

ie

All items in Field 1
All items in Field 2
All items in Field 3

How can I make it look like this:

ie

field 1 item 1
field 2 item 1
field 3 item 1
field 4, item 1

field 1 item 2
field 2 item 2
field 3 item 2
field 4, item 2

etc

I think I would have the same problem in Views.

# Answer
> 0 votes
Edit your content type and Use a field collection. instead of multiple fields. It's difficult to achieve what you want without explicit entities.

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

`Field collection` will allow you to add multiple fields into one group, so instead of adding data to each field, you can just keep adding groups of data. This will allow you to add a collection of **Artist, track number, track title, mp3** Then when you call the `field collection` via panels it will give you the results you want.

You are using multiple fields which will list the values from each individual field right underneath eachother.

---
Tags: views, entities, panels
---


# Question
Title: Views: List of recent months containing nodes
Using Drupal 7, views 7.x-3.0-beta3. I am trying to make a display containing a list of links which direct users to an archive page containing posts of that month (eg. all news messages posted in march 2011).

Tried to solve this with a contextual filter 'Created year + month', which, when no parameter is given, gives a summary list of links like 'march 2011, december 2010' linking to the URL 'news/201103', 'news/201012'.

Is there a way to change the formatting of that URL to 'news/YYYY/MM' ?

# Answer
> 0 votes
You can create path alias to make the URL look how you want, but views need the year and month as a single argument.

# Answer
> 0 votes
You can use `hook_url_inbound_alter()` to rewrite the paths generated by the Year + Month argument. It's not pretty, but it gets the job done.

The following is for a view with year and month (and day!) arguments at `news/archive`:

```
function MODULENAME_url_inbound_alter(&$path, $original_path, $path_language) {
    $args = arg(NULL, $path);

    if (
        $args[0] === 'news' &&
        $args[1] === 'archive' &&
        !empty($args[2]) &&
        strlen($args[2]) === 6
    ) {
        $year = array(substr($args[2], 0, 4));
        $month = array(substr($args[2], 4, 2));
        $remaining = array_slice($args, 3);
        $new_args = array_merge($year, $month, $remaining);
        $path = 'news/archive/' . implode('/', $new_args);
    }
}

```

# Answer
> -1 votes
Replace Content: Created year + month with 2 separate contextual filters:

* Content: Created month
* Content: Created year

---
Tags: views, uri
---


# Question
Title: Recommended techniques for changing the appearance/design of my Bootstrap sub-theme?
I use Bootstrap (7.x-3.0 for Drupal 7 which I already created my own sub-theme and I enabled this sub-theme as my default theme. It seems to work so far.

Now, I want to change the appearance/design of my menu. Here is the appearance with the Bartik-theme:

And here is the equivalent using the Bootstrap-theme:

If I want to customize the Bootstrap theme to look similar to the Bartik theme, how do I do this? In the base-theme folder of Bootstrap I found *menu-tree.func* where the menu tags are generated, which looks like so:

```
/**
 * @file
 * menu-tree.func.php
 */

/**
 * Overrides theme_menu_tree().
 */
function bootstrap_menu_tree(&$variables) {
  return '<ul class="menu nav">' . $variables['tree'] . '</ul>';
}

/**
 * Bootstrap theme wrapper function for the primary menu links.
 */
function bootstrap_menu_tree__primary(&$variables) {
  return '<ul class="menu nav navbar-nav">' . $variables['tree'] . '</ul>';
}

/**
 * Bootstrap theme wrapper function for the secondary menu links.
 */
function bootstrap_menu_tree__secondary(&$variables) {
  return '<ul class="menu nav navbar-nav secondary">' . $variables['tree'] . '</ul>';
}

```

Do I have to edit this file? I don't really think so. Further, each element of the menu uses the class called *leaf* which I couldn't find at all in any files of Bootstrap.

Hope my point is clear. I just want to edit the appearance of my menu and also of further elements without creating an entire `custom-node.tpl.php`. Is that possible or do I have to create an entire new file?

# Answer
> 0 votes
Since you're using Bootstrap as a style framework already, I'd recommend you simply restyle the navbar to look like Bartik. You'll have to modify your `page.tpl.php` template to move the various elements of the header around to put the site title and user menu on top of the main menu.

---
Tags: 7, theming
---


# Question
Title: Can you add a 'select all' option to a webform_select_options_list?
I have a webform that collects a list of flagged items. I'd like to add a "select all" option, because the list can get fairly long (50+) selections, and it can be tedious to manually check the boxes.

I'm using webform with views, sessions, and custom webform\_select\_options\_info function.

Any ideas?

# Answer
The Checkall module enables this functionality for any `checkboxes` form element.

> This module provides an extension to the builtin checkboxes element that allows developers add "check all" / "toggle" / "uncheck all" actions to them. This is specially useful for checkboxes that have a lot of elements.

A `hook_form_alter()` on your webform with this module should get you there.
> 0 votes

---
Tags: webforms
---


# Question
Title: How to replace 'reply' link with button?
I want to replace the 'reply' link with button. As an intermediate solution I styled the link as a button with CSS, but I want it to be a real html 'button' element. The reason is, I do not want the reply links being visible to search engines, instead of it, I want to handle clicks on buttons with javascript.

I only found this 10 year old discussion on drupal site: https://www.drupal.org/node/33170.

I created a custom `comment.tpl.php` and tried to modify the `$links['comment']['#links']['comment-reply']` array, but without success.

# Answer
There are two methods below. Both are equally effective except the second one requires that the `<button>` element be taken out of the list of links and put elsewhere in the template. This is either annoying or awesome depending on what outcome you're going for.

### Method 1: Override MYTHEME\_links()

In Drupal 7, you can turn the comment "Reply" link into a `<button>` element by overriding core's `theme_links()` function. It isn't pretty, but it's effective.

Add the function below to your theme's template.php file (replace "MYTHEME" with your theme name). Clear your cache for the change to take effect.

```
function MYTHEME_links($variables) {
  $links = $variables ['links'];
  $attributes = $variables ['attributes'];
  $heading = $variables ['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading ['level'];
      if (!empty($heading ['class'])) {
        $output .= drupal_attributes(array('class' => $heading ['class']));
      }
      $output .= '>' . check_plain($heading ['text']) . '</' . $heading ['level'] . '>';
    }

    $output .= '<ul' . drupal_attributes($attributes) . '>';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class [] = 'first';
      }
      if ($i == $num_links) {
        $class [] = 'last';
      }
      if (isset($link ['href']) && ($link ['href'] == $_GET ['q'] || ($link ['href'] == '<front>' && drupal_is_front_page()))
         && (empty($link ['language']) || $link ['language']->language == $language_url->language)) {
        $class [] = 'active';
      }
      $output .= '<li' . drupal_attributes(array('class' => $class)) . '>';

      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

      elseif (!empty($link ['title'])) {
        // Some links are actually not links, but we wrap these in <span> for adding title and class attributes.
        if (empty($link ['html'])) {
          $link ['title'] = check_plain($link ['title']);
        }
        $span_attributes = '';
        if (isset($link ['attributes'])) {
          $span_attributes = drupal_attributes($link ['attributes']);
        }
        $output .= '<span' . $span_attributes . '>' . $link ['title'] . '</span>';
      }

      $i++;
      $output .= "</li>\n";
    }

    $output .= '</ul>';
  }

  return $output;
}

```

**Breaking it down...**

This bit of code:

```
      if (isset($link ['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= l($link ['title'], $link ['href'], $link);
      }

```

was changed to

```
      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

```

Of course you'll need to customize the output with whatever you need, whether it be a `<form>` wrapper or `onclick` attribute.

Unfortunately we can't use `theme('button'...)` because that would give us an input element. Of course we could change that by overriding `theme_button()` but that would affect all input elements on the site, and you would still need to override `theme_links()` in order to call it.

### Method 2: MYTHEME\_preprocess\_comment()

If you don't mind taking "Reply" out of the links list altogether, this method will also work. It uses the comment preprocessor to unset the link, but not before taking the value of the URL and stuffing it into a new variable.

Again, add the function below to your theme's template.php file (replace "MYTHEME" with your theme name).

```
function MYTHEME_preprocess_comment(&$variables) {
  if (isset($variables['content']['links']['comment']['#links']['comment-reply'])) {
    $variables['reply_url'] = $variables['content']['links']['comment']['#links']['comment-reply']['href'];
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

```

Then add this (or a variation of it) wherever you would like it to appear in your copy of comment.tpl.php:

```
<?php if (isset($reply_url)): ?>
<button onclick="window.location.href='<?php print $reply_url ?>'">Reply</button>
<?php endif; ?>

```

Clear your cache for the change to take effect.
> 5 votes

---
Tags: 7, theming, comments
---


# Question
Title: How to use hook_init in a custom module?
I am trying to use a `hook_init` within my custom module to add a js file. The problem is I do not see where the script is being called or executed on the front-page.

```
/* Implements hook_init. */
function hook_init() {
  if (drupal_is_front_page()) {
      drupal_add_js(drupal_get_path('modules', 'myInfo') . '/myScript.js');
  }
}

name = My Info
description = My Info Evaluation.
core = 7.x
version = 7.x-0.1-dev

```

I even tried to remove the `hook_init` and referenced the JS within the module info, but no luck. What am I missing here?

# Answer
> 6 votes
Some suggestions:

* Is the module enabled? Silly question, but I've forgotten to do that before.
* `hook_init` implementations won't get called until you clear the cache. Did you clear the cache?
* I will sometimes put a `drupal_set_message('this line');` in various parts of the code to see if that's getting called. In situations where a `drupal_set_message` isn't helping, I sometimes will put a `asdf()` so I can get a "fatal error, call to undefined function" message. Then it's really clear whether or not the code is getting called.
* If the hook\_init is not being called and the module is enabled and cache was cleared, then it's probably mis-spelled. The function should be named based on the name of your module: If your module is mymodule.module then the function name is `mymodule_init()`.
* It's possible that the path you are using isn't quite right. Does the file really exist there? I would try: `drupal_set_message(drupal_get_path('modules', 'myInfo') . '/myScript.js');` so you can see the path and confirm that it's right.
* There's some good documentation on Managing JavaScript in Drupal 7 though perhaps you've already read that page.

Good luck!

# Answer
> 5 votes
In your module, did you replace 'hook' with your module name?

Assuming you have `myinfo.info` and `myinfo.module`, the function should be `myinfo_init()` in order to be called when your module is active.

---
Tags: hooks
---


title: POST JSON data denormalization error

text:
# Question
Title: POST JSON data denormalization error
I created rest resource plugin in a custom module and need to send some JSON data with the request, and access it in the post function. At the moment my post function does not do anything but return some dummy JSON data so I know it is working.

It seems that whenever I try to pass JSON data with the request, it will give me this error: "Could not denormalize object of type , no supporting normalizer found."

If I then try to get this data using file\_get\_contents('php://input'), it will give me a 403 forbidden error. But if I try to return the same data that I get from file\_get\_contents('php://input') from the post function, I get the normalizer error again.

I wasn't able to find much information on even making this REST resource and even less on this issue now, so if anyone has any input I would greatly appreciate it, thanks!

# Answer
What has always worked for me when I build custom REST resource plugins for 8 is making the request and payload for the request in HAL+JSON format after activating the format for the endpoint. The return data has always come back as just JSON. Since many times I've already built content entities which have their own GET, POST, PATCH, DELETE operations, I generally build the custom REST resource plugins for custom operations which I create. I've only tested overriding the default core operations a few times and then I had to disable the core's REST endpoint on a specific operation to allow my endpoint to take priority. ie. My POST operation is used rather than the core's. I'm currently using the Beta14 version of 8.
> 0 votes

---
Tags: 8
---


# Question
Title: Altering the view mode of rendered entities in a View Context via Ctools Plugin
I don't even know if what I want to do is possible, so bear with me. My set-up:

I have a View Context that accepts an author UID argument from the Panel context, and then displays content created by that author UID. This View Context has been added to the `user/%user` system Panel in Page Manager. This allows me to create a custom CTools Plugin that takes that View Context, gives it an additional parameter (content type) to filter by, and spit out the final view programmatically.

The purpose of this is to create many small reusable lists of content in different content types that a specific user has authored, with custom more links and other mark-up around those lists. (I.e., we might show 3 of each content type on a profile page, and if they have created more than three, we link to a different `user/%user/this-content-type` page that has the full list of that type and a proper pager.) The custom header/footer/more links, the ability to insert additional custom copy or code between lists of nodes, and manual ordering of content types are the main reasons why I'm not simply using Views' default grouping function.

The relevant View rendering code in the CTools Plugin is something like this:

```
function custom_list_render($subtype, &$conf, $args, $context = NULL) {
  $block = new stdClass();

  if ($conf['type']) {
    $view = views_content_context_get_view($context[0]);
    $view_output = views_content_context_get_output($context[0]);
    $plugin = $view->style_plugin;
    $rows = array();

    foreach ($view_output['view']->result as $row_index => $row) {
      if (custom_content_type_match_function($row, $conf)) {
        $rows[] = $view_output['rows'][$row_index];
      }
    }

    $output = theme($plugin->theme_functions(),
      array(
        'view' => $view,
        'options' => $plugin->options,
        'rows' => $rows,
      )
    );

  $block->content = $output;
  return $block;
}

```

This code works. There's some additional admin form work going on that selects and saves the `$conf['type']` for each iteration of this plugin that you add to a panel.

Right now, the view output is spit out as rendered entities in a custom view mode. I'm wondering if it's possible to alter the View Context at the plugin level so that when you add this plugin to a panel, you can also select which custom view mode you want the rendered entities to render as. (Think Teaser vs Full vs Block.) If so, at what point do I need to disrupt the view (I imagine before `views_content_context_get_view`?) in order to pass it the new view mode, and how?

Alternatively, could I somehow pass an additional custom argument to the view (e.g. "ctools\_view\_mode" or something) and then use `hooks_view_pre_render` to change the view\_mode?

Thanks in advance!

Running: Most recent iterations of D7, Panels, Views.

# Answer
I think you can bypass Views and get what you want with a content type plugin that does a query for the nids you are interested in, then passing that array to drupal\_load\_multiple(), then passing the result of that call to drupal\_view\_multiple().

drupal\_view\_multiple can take whatever view mode you want as a parameter, and will return a render array that you can just throw at whatever custom extra theming you need to do before displaying it.
> 1 votes

---
Tags: views, panels, 7, entities
---


# Question
Title: Why are some CKEditor configurations working and not others?
I am using *CKEditor 4* in Drupal 7 using the *CKEditor* module. I have the following configuration at `/admin/config/content/ckeditor/edit/[profile]`:

```
config.stylesCombo_stylesSet = 'my_styles:/sites/all/libraries/ckeditor-styles.js';
config.stylesSet = 'my_styles:/sites/all/libraries/ckeditor-styles.js';
config.fillEmptyBlocks = false; // Prevent filler nodes
config.language_list = [ "en:English", "es:Spanish", "zh:Chinese", "ar:Arabic:rtl", "fil:Filipino", "fr:French", "ja:Japanese", "ko:Korean", "ru:Russian", "th:Thai", "vi:Vietnamese" ];
CKEDITOR.on('instanceReady', function(ev) {
  ev.editor.on('paste', function(evt) {
    evt.data.dataValue = evt.data.dataValue.replace(/ /g,' ');
     evt.data.dataValue = evt.data.dataValue.replace(/<p> *<\/p>/g,'');
    console.log(evt.data.dataValue);
  }, null, null, 9);
});

```

The *fillEmptyBlocks* configuration is working. Extra returns are removed on save and on paste from Word.

However, the *dropdown* for the language icon only contains the *CKEditor* default of Arabic, French, and Spanish, not the list of 11 languages that I've supplied.

And pasting *A\[tab\]B\[tab\]C\[tab\]D\[tab\]E* from Word, which converts the tabs to a series of non-breaking spaces, retains the non-breaking spaces.

Any ideas why these configurations are being overlooked and how to make them work?

# Answer
> 1 votes
There was an error in my code. The config statments needed to be surrounded by:

```
CKEDITOR.editorConfig = function(config) {

```

and

```
}

```

which I discovered by looking at ckeditor.config.js in the CKEditor module.

---
Tags: wysiwyg
---


# Question
Title: Can someone explain the @RestResource annotation for building a Rest resource?
I am trying to create a RESTful web service. Above the class there is the following comment.

```
/**
 * Represents entities as resources.
 *
 * @RestResource(
 *   id = "entity",
 *   label = @Translation("Entity"),
 *   serialization_class = "Drupal\Core\Entity\Entity",
 *   deriver = "Drupal\rest\Plugin\Deriver\EntityDeriver",
 *   uri_paths = {
 *     "canonical" = "/entity/{entity_type}/{entity}",
 *     "https://www.drupal.org/link-relations/create" = "/entity/{entity_type}"
 *   }
 * )
 *
 * @see \Drupal\rest\Plugin\Derivative\EntityDerivative
 */

```

What does this mean? What is it supposed to do?

I can't find anything useful about this, especially about the uri\_paths array.

# Answer
> 3 votes
Annotations are used in Drupal 8 to provide meta data in the same location as the class definition. It was borrowed directly from Symfony which is used in the Drupal 8 core to take advantage of an existing framework. The meta data is contained from the lines between @RestResource( and the closing ). Everything else is treated as a normal php block comment. For example I have a custom REST resource for which the annotation is:

```
/**
 * Provides a resource for database intermed table entries.
 *
 * @RestResource(
 *   id = "intermed",
 *   label = @Translation("Intermed content entity standard methods"),
 *   serialization_class = "Drupal\intermed\Entity\Intermed",
 *   uri_paths = {
 *     "canonical" = "/intermed/{intermed}",
 *     "http://drupal.org/link-relations/create" = "/entity/intermed"
 *   }
 * )
 */

```

So for this resource intermed is the id and is used in request operations. The canonical form /intermed/{intermed} will be used for operations other than POST which uses /entity/intermed

In the canonical setting the {intermed} denotes a parameter to be passed.

So if I was to send a GET request to site d8beta14.qetm.org as format HAL+JSON for the intermed table entry for which the id was 2:

GET http://d8beta14.qetm.org/intermed/2?\_format=hal\_json

This GET operation requires three headers: Authorization, Accept, Content-Type

---
Tags: 8
---


title: Responsive inline images?

text:
# Question
Title: Responsive inline images?
Recently implemented Omega/ST Alphorn and was hoping for a real responsive/adaptive result. Overall it works as expected, apart from the inline images in articles. (IMCE/WYSIWYG)

Done some searching, done some reading and found that inline images apparently are still a big challenge. It´s either js, cs, php or a combination of those.

Leaves me with two questions:

1. Is there a way to get a true responsive site without first learning php, css, js and then potentially mess up a perfectly working layout?
2. Is it really that hard to make inline images behave well in a responsive grid? I mean... images in websites are not exactly a new phenomena, right?

Cheers

Oh, one more thing... Maybe someone with +300 reputation can create a tag \`inline\_images´ ... the fact that it does not even exist, worries me a bit.

# Answer
You could use Media (7.x-2.x branch) and some modules for managing responsive images (I use Picture).

You should enable this modules and:

* add the "media" button for Wysiwyg (I've tried both Tinymce and Ckeditor)
* configure media to use the "Picture" module for a custom display mode for files

So, when you add a media to a textarea you can choose the display mode for the file. For documentation about Picture please read this.

Obviously you could use also other modules, but the logic is the same: associates a responsive style for a display mode for images.
> 2 votes

# Answer
As an alternative, here is a step by step tutorial on how to do exactly what you're asking. It involves using CKEditor 4, wysiwyg, and the Picture module. It explains how to use those to make responsive inline images:

Pure Web Media - Responsive Inline Images with the Picture module and CKEditor 4
> 0 votes

---
Tags: media
---


# Question
Title: Showing All Taxonomy Terms count based on a given contextual filter
I need to create a `view` that shows All **Taxonomy Terms count** from a `vocabulary` based on a `contextual filter` given.

The `contextual filter` I'm to be passed are Regions and Regions are `taxonomy terms` as well so I pass the term name via URL and the contextual filter will then convert the term name to term id and it's working fine and it's already showing the list of Taxonomy Terms and their count (See pic 2).

My problem is that it's only showing terms that's been used, I need to show all terms even terms that hasn't been used or have 0 result on count. I already supplied 'No Result Behaviors' on the fields yet it's still not showing. Can someone help me on this one? Thanks!

# Answer
> 1 votes
You Did your jobs correctly but you have only one mistake, you should create views according to **nodes then relate it to taxonomy** instead create **taxonomy view then relate it to nodes**. I explain my mean by example

**Nid title termid**
1 title1 55
2 title2 43
3 title3 55
4 title4 --
5 title6 16

So when there is not set termid view has a row result with no termid then this mean you can put 0 value in "No result"

---
Tags: views
---


# Question
Title: Hide row in view if Content: Edit link field is empty
I have a page view that table format. I have `Content: Edit link` field. I want to hide the row that contains that field empty. The following is a screen shot for `Content: Edit link` settings regarding NO RESULTS BEHAVIOR:

And I want to hide the rows like in the below screen shot with no edit link:

**By the way, I hide some of edit links, due to using custom module has a hook implements `hook_node_access` to prevent some users from editing some other user's contents (depending on roles and content ownership)**

# Answer
You can use views\_php

1. Add `Content: Nid` as a Field in your view and exclude it from display (if you not added it before).
2. Add a Global: PHP filter and include the following snippet:

```
return !node_access('update', node_load($row->nid));

```

also another way is using hook\_views\_pre\_render and check you results if user has not access to that row(result) unset it from output array.

**update part**

As @Aaron mention good note in commentI explain second solution with more details

```
/**
 * Implementation of hook_views_pre_render().
 */
function MODULENAME_views_pre_render(&$view) {
  if ($view->name == 'my_view' && $view->current_display == 'my_display') {
    // View result update logic.
    // e.g.
    // $result = array();
    // foreach ($view->result as $k => $row) {
    //   if (!node_access('update', node_load($view->result[$k]->nid))) {
    //     $result[] = $row;
    //   }
    // }

    // Assuming $result has data as per your logic.
    // Update the pager according to result.
    $view->query->pager->total_items = count($result);
    $view->query->pager->update_page_info();
    // Add results to view.
    $view->result = $result;
  }
}

```
> 0 votes

# Answer
If you really are using `hook_node_access` to prevent users from editing those nodes then there's no good solution. You could implement some Views hooks to hide the results, but then things like pagination are going to be screwed up since pagination is done at query time and it's impossible to write a query that will honor the results of hook\_node\_access.

If, on the other hand, you're using `hook_node_access_records` to actually write the node permissions to the database then you can use this Views patch: https://www.drupal.org/node/620392#comment-10222425

The patch will allow you to add a Content Access filter to your view and filter to only show content the user's allowed to edit.
> 0 votes

---
Tags: 7, views, entities
---


# Question
Title: Thumbnail generation with nginx reverse proxy
I'm using nginx as a reverse proxy for a Drupal 7 site running on Apache2.

When I try to view a thumbnail I get the Drupal 404 page saying that the location is not found.

I have implemented the location rules to rewrite requests to the thumbnail to index.php and the error message includes this rewritten request.

These are my nginx location blocks:

```
location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1 last;
}

location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;
}

# Try to serve files with Nginx if possible
location / {
     try_files $uri @proxy;
}

# Pass on php to Apache
location ~* \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    proxy_pass http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
}

location @proxy {
    proxy_pass              http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
}

```

The url of a thumbnail looks like this:

```
http://example.com/sites/default/files/styles/thumbnail/public/pictures/picture-1-1437996028.jpg?itok=19uLP_Ax

```

The error message displayed is:

```
The requested page "/index.php?q=sites/default/files/styles/thumbnail/public/pictures/picture-1-1437996028.jpg&itok=19uLP_Ax" could not be found.

```

I have tried setting the flag to allow insecure content generation (without a token) to test with. Obviously I've removed that flag.

# Answer
that is similar to me, i added this line in my nginx vhost config,

```
location ~* /sites/default/files/styles/ {
    if (!-e $request_filename) {
    rewrite  ^/(.*)$  /index.php?q=$1  last;
    break;
    }
}

```

you need to reload to make the image display, hope someone can improve my answer
> 2 votes

---
Tags: 7, media
---


# Question
Title: Form Validation: Let the comma as separator to be valid in integer field input
I'd like to let my users use separator (Comma) while entering values in an integer field such as price for instance.

I know that we can alter the validation of fields with element\_validate\_integer API, but seems like that I can't get it working.

I appreciate any helps, thanks.

Also note that I'm using Clientside Validation module as well.

# Answer
If you have integer (or Big int) field you can't submit data with `,` in integer field and this means that you should strip all `,` before data passed to Drupal default form submit handler ( as you know before data passed to submit it must be validated first ) So the tiny and quick solution is you set a custom validate handler that called before Drupal node validation handler then in there try to strip all `,` ( manipulate data in your custom validation handler ) and then enjoy it.

```
 // in your custom module

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'your_form_id' ) {
                array_unshift($form['#validate'], '_mycustom_validate_handler');
}
}

function _mycustom_validate_handler($form, &$form_state)
{
$form_state['values']['your_integer_field']['und'][0]['value'] =strtr($form_state['values']['your_integer_field']['und'][0]['value'] , ',' ,'');
}

```

And if you also want save `,` in database(!!!) try text field instead using integer field and then with client side validation Regex Rule validate what you want.
> 1 votes

---
Tags: theming, forms
---


title: How to use form field only once

text:
# Question
Title: How to use form field only once
I'm looking for solution for following scenario in my D7 site. I have form with 2 empty text fields. If user enters value in `field 1` and submits form next time when he opens this form only `field 2` will be available for input.

# Answer
you can achieve it with some code in your custom module

```
function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'your_form_id' ) { // in your custom content type
    if($form["nid"]["#value"]){  //when we are in edit form
      if(isset($form['field_your_field1']['und'][0]['#default_value']['value']) )
          hide($form['field_your_field1']);
     if(isset($form['field_your_field2']['und'][0]['#default_value']['value']) )
          hide($form['field_your_field2']);
    }
}
}

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: How I do configure the BigBlueButton module?
I have installed the BigBlueButton module. Its demo is working fine. How do I create a meeting?

# Answer
I have resolved the problem following these steps.

1. Install the module
2. On the module settings page (admin/settings/bigbluebutton), put values for *Server base URL* and *Security salt key*, and save the settings
3. Create a new content type, for example *Conference*
4. On the content type setting panel (for the *Big Blue Button* module), select *Treat this node type as meeting* and *Display meeting status on node*, and save the settings
5. Create a new *Conference* node and go to meeting
> 0 votes

---
Tags: 6
---


# Question
Title: Node export import into different node numbers
I use node export to export my nodes from Drupal 6 and import into my new site Drupal 7.

The nodes number is not same with nodes in Drupal 6.

How do I set it same as nodes number in Drupal 6.

# Answer
Node ID numbers is an auto-incremented field in the database that is global for the entire Drupal installation. Attempting to replicate the exact Node ID in Drupal can be difficult and cause serious problems if handled incorrectly.

If your issue is URLs, one option is to make a 301 alias for the old URLs to the new URLs. There are modules to easily create the redirects like the Redirect module.

If you must maintain the ID numbers then the solution will have to be custom migration code. The migration process will recreate the nodes in the new site and account for any node deletions.
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: Rendering Content Multiple Times in a Node
I'm starting to dig deeper into themeing and I'm thinking maybe I'm misunderstanding something.

Basically I want to break apart the way the content is laid out in my `node--example.tlp.php` file.

I've started doing that with some simple render statements like `print render($content['group_factory_images']);`

I started running into trouble when I wanted to pull the label off of the normally rendered flow and place them somewhere else with something like `print render($content['group_factory_images']['label');`

This wasn't working so I started to try and pull other items in, to see if it was a syntax issue or something else.

I came away with 2 questions: What is the right syntax to get labels rendered in a node?

And then; Can you only render a piece on content once? For example could I do something like rendering the body twice in the same node? (not that I would want to, but it illustrates the point I think:

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

// other items rendered

print render($content['body']);

```

# Answer
> 0 votes
The display of a label is handled by the Field and not the template. The HTML for the field is passed to the template layer from the field API and the label HTML is lumped in with the field information itself. So basically you cannot alter or move the printing of the label in the template layer of theming. Consider the field data and the field label as one item in templating (i.e. `$content['field_name']` contains the field data and label as one. Altering the label display (display label or not, inline, etc.) is done in the field display settings for the content type. The only way to alter the label is to do so at the field display level and again it is passed to the template with the field data as a final product.

Rendering content more than once, yes it can be done.

---
Tags: theming, entities
---


# Question
Title: Permission error while downloading file through IE8
I have one content type with file upload field. I am saving the files to `drupal/sites/default/files/search/documents` custom folder. The user can download the files from the site. The download works fine in all browsers expect IE8.

I am getting an error pop while downloading a file. Its only happening in IE8 on both windows XP and Windows 7. Once i click on download link this error is comming

"Unable to download 11820 from subdomain.domain.org" "Unable to open this internet site. The requested site is either unavailable or cannot be found. Please try again later."

Here 11820 is the node id. I am using SSL certificate in my site though the url is https://subdomainabc.domainabc.org/

# Answer
> 0 votes
Updated download\_file module header.

```
 $headers = array(
   'Content-Type'              => 'force-download',
   'Content-Disposition'       => 'attachment; filename="' . $file->filename . '"',
   'Content-Length'            => $file->filesize,
   'Content-Transfer-Encoding' => 'binary',
   'Pragma'                    => 'private, no-cache',
   'Cache-Control'             => 'private, no-store, no-cache, max-age=0, must-revalidate',
   'Expires'                   => '0',
   'Accept-Ranges'             => 'bytes'
 );

```

---
Tags: ssl, files
---


# Question
Title: How to implement a trial membership using Organic groups?
I work on a Drupal site with the Organic groups module, where users can `create account`.

When the process for creating an account is finished, users have access to a specific `group` and should have `og role` **Trial member** (automatically assigned) with state **Active**, and this for a limited time period.

After that limited time period is passed, user still has `og role` **Trial member** assigned, but with state **Pending**.

Can someone help me with this?

# Answer
> 1 votes
Sounds like a perfect job to accomplish with the Rules module. Below are the headlines of how you could get this to work ...

# Rule 1 (When user account is created)

* Event: When a new user account is created
* Action:
    1. Grant access to role `Trial member`.
    2. Set some **Date** field value = `expiration date` (cfr. your "limited time").
    3. Set some **State** field value = `Active`.

# Rule 2 (When expired)

* Event: When user logs in
* Condition: if the date indicated in field with `expiration date` is passed.
* Action: Set your **State** field value = `Pending`.

# Recommended video tutorials

### Rules

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

### Organic Groups

If you're not familiar (enough/yet) with Organic Groups, then reviewing the amazing set of videos to Learn Organic Groups might help.

# Other variations

There are other variations to make this work with the Rules module. E.g. by using 'Rules Scheduler' (= sub-module of Rules) to schedule a variation of "Rule 2", to be executed on your `expiration date`.

---
Tags: rules, users, organic-groups, cron
---


# Question
Title: Main_menu Google Analytics Event Tracking
I have been asked to insert a google tracking code to all of my main\_menu Links

```
<a href="/something" onclick="_gaq.push(['_trackEvent', 'Menu', 'link-name', 'Click']);"\ >link-name</a>

```

I try to found a module but i couldn't found how to use it to accomplish this task. https://drupal.org/project/google\_analytics\_et

I thought i can use a hook\_menu but i need some help..

Drupal 7

# Answer
> 2 votes
To do that I was using Menu attributes module with Onclick Event patch. Simply install it, apply patch, enable module and you will be able to add onclick code to menu elements via GUI.

# Answer
> 0 votes
You can also achieve this with hook\_menu() and a preg\_replace:

```
    /**
     * Implements theme_menu_tree__MENU_NAME.
     */
    function mytheme_menu_tree__menu_menuname($variables) {
      $variables['tree'] = preg_replace("@<a(.+)>(.+)</a>@", "<a $1 onclick=\"ga('send', 'event', 'Menu', 'click', '$2');\">$2</a>", $variables['tree']);
      return $variables['tree'];
    }

```

---
Tags: google-analytics
---


# Question
Title: JSON Menu Link Without Invoking Init Hooks?
Our Drupal site utilizes a number of menu hooks to return JSON from an API we manage in a separate Web API. We also have a number of intensive tasks that happen on each page load via the `hooks_init` in several custom modules.

The issue we're facing is that the tasks in `hook_init` are only required for actual pages, and should not be executed when all we want is JSON output. Is there a way to ONLY execute the `hook_menu` endpoint, and no other Drupal code?

We have several pages that make 3-4 requests to Drupal JSON menu links, which means that we also run our unnecessary `hook_init` tasks 3-4 times as well -- plus once for the actual page request.

There must be a way to circumvent the usual Drupal pipeline to perform these actions?

Here is an example of one of our JSON menu hooks:

```
function membership_details()
{

    // Get membership details from API, and return as JSON
    $details =  sendCurlResponse(/* ENDPOINT */);
    drupal_json_output($details);
    drupal_exit();
}

```

# Answer
> 0 votes
`hook_init()` is invoked before the menu system deals with the request, and in the confines of a normal Drupal bootstrap, no, it's not possible to circumvent that workflow.

It's by design though, if you look at the docs:

> Perform setup tasks for non-cached page requests.
>
> This hook is run at the beginning of the page request. **It is typically used to set up global parameters that are needed later in the request**. When this hook is called, the theme and all modules are already loaded in memory.

Emphasis mine.

So for its intended use, `hook_init` should only set up variables *that are required for the current request*. Whether that be a request for HTML, JSON, or whatever else.

You have two pretty reasonable options as far as I can tell:

1. Augment the code you have in `hook_init` implementations to check whether it should be executed based on parameters from the request (accepted content type, file extension, whatever makes the most sense for you use case).
2. Move the logic in `hook_init` to another hook, one that's invoked later in the process (I can't really say which hook that would be without knowing what the code does)

---
Tags: hooks, ajax, routes
---


# Question
Title: Custom facets return no results on search page
I have created a custom field to the node index of apache solr. Here is the code.

```
function myModule_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id) {
  if($node->type == "feature") {
    $support = db_select("custom_table", 'a')
        ->fields("a", array('Support'))
        ->condition('nid', $node->nid)
        ->execute()->fetchField();
      $document->addField('custom_field', $support);
  }
}

```

And then for this custom field I have created the facet. Here is the code.

```
function myModule_facetapi_facet_info(array $searcher_info) {
  $facets = array();
     $facets['custom_abot_support'] = array(
      'label' => t('Custom Facet'),
      'description' => t('Filters by Support'),
      'field' => 'custom_field'
    );
}

```

The facet successfully created and it has been present in the facets list. But the problem is on the search page. When I try to search some thing, on the search results page this facet only display the title of the facet block. It does not display any content.

Any one what is the problem?

# Answer
I have found the solution.

* if you wrote this hook `hook_apachesolr_index_document_build_node` then you have to delete the indexed data from apache solr search index and then reindex all the data. if you only reindex data then it will not work.
* and 2nd point. you have to keep care of the prefixes of the field. if it is a single string then use `ss` if multivalue field then use `sm`
* 3rd point is you have to call `hook_apachesolr_query_alter`.

```
function myModule_apachesolr_query_alter($query){
   $query->addParams(array('fl' => array('ss_custom_field')));

```

}
> 1 votes

# Answer
// module name: apache\_group // publicatin field : field\_publcation\_rits\_dev //people rits : field\_peoples\_rits\_term //research rits : $field\_research\_rits\_term // $term\_id = field\_get\_items('node', $node, $field\_name);

function apache\_group\_apachesolr\_index\_document\_build\_node(ApacheSolrDocument $document, $node, $env\_id) {

```
$support = db_select("node", 'a')
    ->fields("a", array('title'))
    ->condition('nid', $node->nid)
    ->condition('type', 'publications')
    ->execute()->fetchField();
  $document->addField('field_publcation_rits_dev_abc', $support);

```

}

function apache\_group\_facetapi\_facet\_info(array $searcher\_info) { $facets = array(); $facets\['custom\_abot\_support'\] = array( 'label' =\> t('Custom Facet'), 'description' =\> t('Filters by Support'), 'field' =\> 'field\_publcation\_rits\_dev\_abc' ); }

function apache\_group\_apachesolr\_query\_alter($query){ $query-\>addParam('fl', 'im\_field\_publcation\_rits\_dev\_new'); // $query-\>addParams(array('fl' =\> array('field\_publcation\_rits\_dev\_abc'))); }

But no success, what is the issue ??
> 0 votes

---
Tags: 7, search
---


title: List parent terms by vocabulary

text:
# Question
Title: List parent terms by vocabulary
I want to list only parent terms in order to rearrange the orders like **/admin/structure/taxonomy/vocabulary\_name**. Given url have displayed all terms included child terms. I want to avoid term terms. So i've tried to create custom page. I've tried below code but i can't make it work.

```
function test_menu() {
  $items['manage_category/%taxonomy_vocabulary_machine_name'] = array(
   'title' => t('Manage category'),
   'page callback' => 'arep_manage_category',
   'page arguments' => array(1),
   'access arguments' => array('administer taxonomy'),
   'type' => MENU_CALLBACK,
 );
 return $items;
}

function arep_manage_category() {
  $category = arg(1);
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $taxonomy = taxonomy_vocabulary_machine_name_load($category);
  $form = drupal_get_form('taxonomy_overview_terms', 'taxonomy_term', $taxonomy);
  return drupal_render($form);
}

```

I've tried to access this page by vocabulary name. How ot make it work? Is any other idea?

# Answer
> 0 votes
Firstly you add a cck field named **flag** for **levels** to your vocabulary when created, then after that when you import or add terms in this then fill flag value like **"My First Level"/"My Second Level"**. then you can fetch very easily like that..\`

```
/* Get All States From Taxonomies */
  function get_taxonomy_by_flag($flag) {
       $VocabName = "Master Data";
          $myStateArray = array(0=>'-- Select --');
        $Vocabluary = get_vocabulary_by_name($VocabName);
         $query = new EntityFieldQuery();
          $entities = $query->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('vid', $Vocabluary->vid)
->fieldCondition('field_flag', 'value', $flag, '=')
->execute();
if(sizeof($entities)>0)
{
  foreach($entities['taxonomy_term'] as $tid) {

    $term = taxonomy_term_load($tid->tid);
    $name=$term->name;
    $myStateArray[$term->field_code['und']['0']['value']] = $name;
  }
  return $myStateArray;
}
else
{
    return 0;
 }
}

    function get_vocabulary_by_name($vocabulary_name) {
        $vocabs = taxonomy_get_vocabularies(NULL);
         foreach ($vocabs as $vocab_object) {
          if ($vocab_object->name == $vocabulary_name) {
            return $vocab_object;
         }
      }
            return NULL;
      }
     call this function by flag name and you can easily get all parents. because i have used this for **State/District/Block/Village** purpose.
      get_taxonomy_by_flag('STATE');

```

hope this helps you lot...

---
Tags: taxonomy-terms
---