# Question
Title: What are recommended modules or processes which support rating based comments or reviews?
I am new to Drupal and I am planning a directory site where users can review and rate the service of a shop or company.

I'm thinking of something like this (taken from yelp.com):

Any recommended modules or processes which support such feature in Drupal 7, i.e. for rating based comments or reviews?

# Answer
> 2 votes
# Rating

The VotingAPI module (available for both D6 and D7) offers a framework to developers of Drupal modules about voting and/or rating. It uses a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

VotingAPI offers these key features:

* Create/Retrieve/Update/Delete operations for voting data.
* Whenever a vote is casted, it calculates the results and caches them. These calculations can either be the default calculations (average, total, etc), or they can be implemented via custom tallying functions.
* Via its integration with the **Actions** module, it can trigger workflow steps whenever votes are casted and results are tallied, such as promoting a node to the front page, hiding a comment flagged as spam, or sending some eMail.
* It integrates with the **Views** module, which allows for slice and dice of the content of a site based on user consensus. And tt provides functions to format vote data to display them to users.

**Typical rating related modules with a stable release for D7**:

# Views / Rules / Flag / Message

Everything above relates to "Rating" (or voting). Some more modules that you may want to consider (= add to the mix of modules you might want to consider):

---
Tags: 7, comments, rating
---


# Question
Title: hook_form_alter setting select list #options key allow attributes per option
I have a select list that I am populating $form\['field\_my\_field'\]\['und'\]\['#options'\] in a hook\_form\_alter.

I was wondering what a good way to set a data attribute per each option would be. I've thought about adding some inline javascript to add it after it's rendered, but I want to do this with PHP and preferably within the hook\_form\_alter.

Is this possible?

# Answer
> 1 votes
Based on theme\_select which is the one that constructs and styles the Drupal Form API's select type. It uses the form\_select\_options function do create the `<option>` tags.

So you would need to override *theme\_select* and replace the *form\_select\_options* function with your own.

Basically, copy the functions and it's content, rename them and do your modifications.

---
Tags: forms
---


# Question
Title: In drupal, Show own unpublished comments
By default if comment is not approved it is not show to user. In my scenario I want to show own unpublished comment to user in light gray background if comment is not approved

# Answer
Try the view\_unpublished module

> This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.

After installing the module, navigate to your user access page and assign the appropriate permissions to the roles you wish to be able to view unpublished nodes.

Similar module : Comment Access

> Comment Access allows your users to control the comments on their posts. It adds permissions to administer, approve, and delete comments on nodes they create without granting full comment administration access. Permissions are granted by node type, so it's a great way to allow your users to manage comments on their own blogs,
> 0 votes

---
Tags: 7
---


# Question
Title: How can I sort by last word in the node title field?
In one of my content type, we are storing names in the Title field. For example, title is "John Smith". Due to the recent requirement change we now need to sort results by last name.

But since the name is stored in Title how can I sort by last name in the view? Is there a way I can create a field which automatically gets the last word in the title? Or may be some other way that I am missing out?

# Answer
> 0 votes
This is probably not best solution, but it should work:

Try Views PHP. With this module you should be able to create sorting in view which will take only last word of given string (content of your title field) with PHP code (something like this example).

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code.

# Answer
> 0 votes
I'm making an assumption on the Last Name field. If you got the first and last names from a user which is related to the nodes being listed in the view, then you can add a **View: Relationship** to the User entity maybe then order the query by the related user's last name.

---
Tags: 7, views
---


title: How to alter Services Views result

text:
# Question
Title: How to alter Services Views result
How can I alter services views result. Using services view I can easily produce Json data. I have tried function hook\_views\_post\_execute. This hook is working for simple views but not with services Views(Json data).

# Answer
> 1 votes
You can use `hook_services_request_preprocess_alter()` and `hook_services_request_postprocess_alter()` hooks of Services module.

---
Tags: views, services
---


title: Exposed filter show results

text:
# Question
Title: Exposed filter show results
I have a content type say sample. I've created a view page to slideshow all sample content type. I have an exposed filter at the top of the page, people search using id there, on searching it is giving the correct result with the slider but the slider is'nt working at the result page. I want it show the result first and then the others.

Is it possible.

# Answer
> 0 votes
Enable the Use Ajax option under the Other Tab..

---
Tags: views
---


title: Commerce Billy PDF

text:
# Question
Title: Commerce Billy PDF
I'm using Commerce Billy to send an invoice PDF to my customers. When I watch the module page of Billy I see that the customer information is found on the left of the invoice...but when I make my own invoice the customer information is nowhere to find? Does anybody know what I'm doing wrong?

I tried to find an option for this in the module UI in de drupal back-end but I can't find anything? Any suggestions?

Thanks in advance, Joost

# Answer
Sorry, looking at the comment I can see that my question wasn't very clear. So what I meant was that the billing information wasn't displayed on the PDF.

The problem was that there wasn't any billing information. In the Customer Profile Types of Commerce I didn't ask for a name or organisation. I now enabled these options and the billing information is displayed on the PDF.
> 0 votes

---
Tags: commerce
---


# Question
Title: Translate homepage meta Title and description
I have a Multilingual Drupal 7 site using i18.

But how do I get my homepage meta Title and description translated?

# Answer
You need to install the variable translation module.

> The Variable translation module, part of the Internationalization (i18n) package, allows you to translate text and settings that are stored in Drupal as variables. These variables include text such as 'site name' and 'site slogan', as well as settings like 'Default front page' and 'Default 404 page'.

Go to

> admin/config/regional/i18n/variable

and select the variables you would like to translate. Then translate the string(s) at

> admin/config/system/site-information
> 0 votes

# Answer
To solve your query. You need to create a custom module with using Token & Variable module.

I am refer you to this LINK. Hope you can solve by using this link.

**OR**

Use Translation Table module.

> UI for quick translation of taxonomies and menus. The i18n module allows for translation of taxonomy terms and menu items, but the process is tedious - you need to look up strings you want to translate, there is no overview of what's already translated etc.

* Goto `admin/config/regional/translate/translate`
* then filter by metatag and it will show all the metatags that you can translate.
> 0 votes

# Answer
You can use hook\_metatag\_metatags\_view\_alter

```
/**
 * Implements hook_metatag_metatags_view_alter().
 */
 function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
   if (drupal_is_front_page()) {
     $output['title']['#attached']['metatag_set_preprocess_variable'][0][2] = t($output['title']['#attached']['metatag_set_preprocess_variable'][0][2]);
     $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = t($output['description']['#attached']['drupal_add_html_head'][0][0]['#value']);
   }
 }

```
> 0 votes

# Answer
My solution was to install and enable the Translation table module. Then follow these steps

1.Go to admin/config/regional/translate/translate.

2.Then filter by metatag and it will show all the metatags that you can translate.
> 0 votes

---
Tags: 7, i18n-l10n, meta-tags
---


# Question
Title: How to user listen the songs after purchasing their songs or products using Drupal commerce?
I am using Drupal commercekickstart.. I have installed Commerce file module and Commerce license module also.If user purchasing their product after that their can download the files at the same time user can listen the songs through player inside this project.Is it possible? Anyone guide to me?

# Answer
> 2 votes
You could probably place a view on the confirmation / download page to link to the mp3 inside html5 audio tags.

```
<audio controls>
  <source src="mymusic.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

```

You could make the default view in a block, place it on the confirmation page where the link to download the mp3 is, and get the mp3 file with a contextual filter with a default value of get ID from URL.

---
Tags: users, commerce, files
---


# Question
Title: Term reference list with a field for extra information
For a site I'm working on I have a functionality in mind that I simply cannot wrap my head around as to how I would set it up. When creating content of a specific content type I want to have the option to select multiple items using checkboxes from a list of about 30 items, and have the option to add a short piece of text (less than 20 characters) to each of these items if I want to.

Currently I have no real idea on how to set this up. I'm planning on adding the 30 or so items to a vocabulary so I can easily reference them, but how would I be able to select these items and add the piece of text so it's linked to these items as well?

Basically what I'm looking for is the following:

I hope someone is able to shed some light on this for me, any help is appreciated.

# Answer
> 0 votes
As far as I know you can achieve that in two ways.

Using the combination of Double Field and Field group modules.

> Use "Double field" for to make list of checkbox and textfields, and Field Group to make all of them a Group.

There is another option to achieve this. Try the Composed Field module

> Composed Field is an implementation of core's Field UI that allows you to split a single field into as many sub-fields as you like.

This seems very close to your requirement. I've used this one of my project and working fine.

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


# Question
Title: Drupal Commerce: Allow anonymous users to choose their username on checkout
The default setup includes a single option in the "Account Information" pane which allows for an email address. The user's username is then derived from that.

I would like to add another field for "Username" where the user can enter their own username, instead of having it generated for them automatically based off of their email.

# Answer
> 2 votes
Theres a sandbox project here that you will need to download with git that looks like a complete sign up form.

Theres also Commerce User Profile Pane that allows you to choose the fields in the pane. Ive not used it before, but looks like a good place to start.

---
Tags: 7, commerce, rules
---


# Question
Title: Rule to create user on webform submission by anonymous user
I'm trying to create a user with rules on webform submission by anonymous user, as the title says. I set my event (After a webform has been submitted), set my conditions and set my actions. Create a new entity of user whose name will be `[data:name-value]` and e-mail address `[data:email-value]` as seen below . But I get **Unable to evaluate action entity\_create**. However, I know `[data:name-value]` works it prints when I show it on the screen. User creation also works because a user is created when I enter fixed values. What could I be missing?

PS: I could roll my own module for this small task, but why bother when I can do it with rules?

# Answer
> 1 votes
It looks like your issue is about what is described in "Create entity fails when the user is anonymous" (which is an open Rules issue, current status = RTBC).

That issue also contains a patch (attached to comment #4 of that issue), which might help as a (temporary?) work around.

**Note**: another way to get it to work, appears to be to use the token `[data:email-value-raw]`, as suggested in a comment to this answer (credits: olisb).

---
Tags: rules, webforms
---


# Question
Title: Let "Availability Calendars" start on monday
I created this website http://peace-in-the-city.be/en/book-now and on that page you will see I used a Calendar to show the availability of the apartment. ( http://drupal.org/project/availability\_calendars )

I tried to let the calendar start on Monday. I googled for the solutions and did change my regional settings local to start of the week to Monday. It worked after that for a couple days. But for some reasons it went back to Saturday. Changing the regional setting has no effect anymore now.

At this point, I'm clueless... Any tips, links and ofcourse working solutions are welcome.

PS. I did not change anything in the rAvailability Calenda module. I'm just install modules - enable/disable - or change configuration.

# Answer
> 1 votes
As a best practice whenever an issue like this arises - disable the module, uninstall, flush all cache, verify settings for regional locale is set to start on Monday.

Now re-enable the module. Flush all cache. Re-configure. And see if things are working as expected.

As an added additional option if you care to contribute to the community, on a fresh install of Drupal, attempt to recreate the issue that "potentially" caused this issue to arise by re-tracing any steps you may have taken (other contributed modules, other seemingly unrelated changes, etc.). If you're able to trace what caused the issue, then perhaps the potential bug can be fixed.

Of course, regardless if the uninstall, reinstall works and functionality doesn't again fail after a few days then you have solved your issue! This should be a fairly typical go-to strategy of troubleshooting for any module issue.

---
Tags: datetime
---


title: How to import Product Kit via CSV file?

text:
# Question
Title: How to import Product Kit via CSV file?
I am trying to import product kit from CSV file but I am not getting how to import it as I need to link with products in product kit.

I am using Ubercart, Feeds and Ubercart product mapper to import.

Any suggestions?

# Answer
> 1 votes
# Ubercart Feeds Mapper module:

Refer to the answer to the question about "How to import products to UberCart 3 using CSV data?". It contains a link to Drupal 7 Port of uc\_feeds, which seems to include everything that's needed to make this to work by using the Ubercart Feeds Mapper module.

Note: from your recent question "Ubercart Product import containing HTML formatting in product description", I'm assuming that you are referring to the Ubercart Feeds Mapper module (instead of "Ubercart 'product' mapper" ...

# From Ubercart.org:

Importing from CSV files also details the steps required for such import. The process consists of 3 steps. Here is a summary of these steps:

* Prepare product data.
* Activate the Node Import module.
* Import process.

Attention, the 'Node Import' module does not have a D7 version, only a D6 version.

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


title: Rules setup for Drupal Commerce

text:
# Question
Title: Rules setup for Drupal Commerce
I need to setup a rule on the drupal commerce with the following condition.

If Authenticated user added an item in cart and they didn't do the checkout for 24 hours, the site needs to shoot an email to the user with the cart content after 24 hours but only once, dont need to spam in every 24 hours.

How to perform this using rules? Any ideas Champs!!

Thanks

# Answer
> 0 votes
Try the Commerce Order Reminder. It can help you!!

> As the name implies, this light weighted module sends email reminders to website users of the orders that were left uncompleted. The reminders will only be sent about those orders that have the email property filled. This includes even those orders of anonymous users that entered their email in the billing information form but did not complete the checkout process.

---
Tags: commerce, rules
---


# Question
Title: Set multiple items for an argument in embeded view
I'm using this code to display a view inside a node:

```
$view_args = array($node->field_page_cck[0]['value']);
$view = views_get_view('my_view');
$view->is_cacheable = FALSE;
$view->set_display('default');
if (!empty($view)) {
    print $view->execute_display($display_id , $view_args);
}

```

The argument is set with the option **Allow multiple arguments to work together.**

I tried with:

```
$view_args = array($node->field_page_cck[0]['value'], $node->field_page_cck[1]['value']);

```

but no luck.

I also tried to convert to a string like this: argument1+argument2+.... or argument1,argument2,.... still no luck.

Any help, please?

# Answer
The argument itself needs to be configured to take multiple items. There is a checkbox which says "Allow multiple terms per argument".

After that you should be able to have a string with commas separating them

```
$view_args = array($node->field_page_cck[0]['value'] . ',' . $node->field_page_cck[1]['value']);

```

Note that you are still passing an array, but the first item is a comma separated string.
> 2 votes

# Answer
I had problems with setting multiple arguments to contextual filter: Content: Has taxonomy term ID (with depth)

I had checked: Allow multiple values

I had checked Specify validation criteria and that was the problem as it has its own setting for filter value type that in my case was Term IDs separated by , or +
> 0 votes

---
Tags: views
---


title: Add t() function in tpl.php page

text:
# Question
Title: Add t() function in tpl.php page
Hi I have this line in a tpl.php file. I would like to add t () function to be able to translate it. What needs to be changed in this line?

```
print "<div class='confirm-app'><h2><span class='voice-header'>1. Your application</span></h2>".$application."</div>";

```

# Answer
```
print "<div class='confirm-app'><h2><span class='voice-header'>1. " . t('Your application') . "</span></h2>".$application."</div>";

```
> 0 votes

---
Tags: i18n-l10n
---


title: How to add background images to blocks?

text:
# Question
Title: How to add background images to blocks?
How to upload background images to blocks individually ?

Is there any contributed modules available uploading background images to blocks?

# Answer
> 3 votes
Try the Background Images Formatter module

> This module provides an image formatter who allows you to set an image in background of a div.
>
> The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.

This can be done using Views. Create a **block**, select the "Background Image" formatter for your image field, save, place the block, boom, you're done.

# Answer
> 0 votes
I found this module ST Block.

> ST Block is a drupal module allow you easy configure block with very much options as set block id, block animation, block background image, block background video, block background parallax,...

---
Tags: 7, blocks
---


# Question
Title: Is there a way to provide a Select All / Check All checkbox for a field that displays multiple checkboxes in Drupal 7?
Seems like there is no core config to setup a "Check All" checkbox unless I missed where it is. I'm creating a content type and have a taxonomy reference field and I have alot of terms, which means alot of boxes I have to check. Anyway to provide a checkbox to select everything?

# Answer
> 1 votes
Here is an updated version of @duckx code, it has the following improvements :
\- only select the checkboxes of the label that has been clicked
\- allows to toggle checkboxes

```
Drupal.behaviors.selectAll = {
  attach: function (context, settings) {
    $('body.page-node .form-type-checkboxes > label').click(function() {
        $(this).nextAll('.form-checkboxes').find('input[type="checkbox"]').trigger('click');
    });
  }
};

```

# Answer
> 1 votes
You can do a form alter. hook\_form\_alter and attach your js to the form.

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'YOURMODULE') . '/YOURMODULE.js',
);

```

Then add the code as in here

# Answer
> 1 votes
Here's a quick snippet for anyone looking for a quick check all functionality. It will basically make your field LABEL a check all button. **No need to add any extra HTML elements or modules.** This just works.

You can pretty much copy this into your js file and it will just work as i restrained it to working only on content Edit pages.

Obviously this isn't a long term solution, but mainly as a quick band aid patch.

```
jQuery(document).ready(function($) {
  var $checkBoxes = $('input[type="checkbox"]');
  $('body.page-node .form-type-checkboxes > label').click(function() {
      $checkBoxes.attr('checked', true);
  });
});

```

# Answer
> 1 votes
This contrib module appears to do the trick: https://www.drupal.org/project/checkall

# Answer
> 0 votes
There is no core config option for something like this, it would have to be JavaScript/jQuery (http://jsfiddle.net/PtMrM/).

```
<a href="#" class="check-all">Check All</a>
<label><input type="checkbox" name="ny"> New York</label>
<label><input type="checkbox" name="bos"> Boston</label>
<label><input type="checkbox" name="sfo"> San Francisco</label>
<label><input type="checkbox" name="dc"> Wasington DC</label>
<script type="text/javascript">
  (function($) {
    var $checkBoxes = $('input[type="checkbox"]');
    $('.check-all').click(function() {
      $checkBoxes.attr('checked', true);
    });
  }(jQuery))
</script>

```

Please note, that is very quick js, and won't be very user friendly (e.g., they click on it, there is no way to uncheck)

---
Tags: 7, entities, taxonomy-terms, nodes
---


# Question
Title: How to print the timestamp of date in a Views fields?
I am using the Views Data Export module to show feeds as XML. I need to show the created date and updated date in timestamp .

How can I implement it?

# Answer
There is a way:

1. Go to Configuration \> Regional and language \> Date and Time \> Formats (Tab)
2. Then click "add format" to add a new date format and just type "U" in the textfield. The "U" is actually the timestamp.
3. Go back to "Types" tab and add the new date type you just created and give it some name like "Timestamp".
4. In your view select your date field and select your custom date type in "Choose how users view dates and times"

Hope this is what you were searching for.

Otherwise: If you just look for the MySQL like timestamp just select "Plain" as the formatter in your views field.
> 10 votes

---
Tags: views, datetime, importing-exporting
---


# Question
Title: How to embed a Rules Link in a View in order to trigger a Rules link to run?
What is the general process to embed a Rules Link in a View in order to trigger a Rules link to run?

I have used the Rules Link module to create a Rules Link embedded in a View (it's a View that combines all the details of a User).

I want the Rules Link to trigger a Rule which (when the reading user clicks " More Content From Author") will trigger the Rule to show a list of their latest postings in a HTML format.The paths work alright, it just doesn't seem to trigger the Rules Link to run the View.

If I add say a generic link in the Rewrite Result link path (say http://www.google.com), it works fine and finds the target. But my Rules Link URL "More-Content-by-Author" throws a 404 even though the link is set correctly.

I've got most things working, checked all the Permissions and set the "Execute Rules Link" permission in the said View, but still get a 404 error.

I have not added any variables (do I need to?).

After 6 hours, and I'm stumped now. Any suggestions?

Note: All my other Rules links work fine.

# Answer
These are 2 modules that can trigger events based on the 'current URL being viewed' (quotes are from their project pages):

* Rules URL Argument:

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

> ... implements Rules conditions for checking the URL against a given string for triggering actions.

You can also use the Rules Link module to generate a custom link that can trigger a rule. But that requires the link to be clicked to access the page and there might be an issue that the user must be logged in.
> 0 votes

---
Tags: views, rules, debugging
---


# Question
Title: How can I create a link from an organic groups content node back up to the parent OG?
I have used Organic Groups 7.x-2.7 to create groups and can create content which is allocated only to that group. When I am viewing a group content node how do I create a link back up to the parent group? Ideally I'd like to be able to create a views block with this link in it.

# Answer
> 0 votes
In terms of OG Groups I usually have a bigger issue getting what I want on the screen without Panels but for OP's question the answer is pretty easy. So of course there are a couple of ways to complete this but OP wanted a view block with a link to the group to show on group content. So without further ado here is the how to for this.

* First create a new view with a block of unformatted list of content titles.
* Then add a Contextual filters Content: Nid.
* Set that filter to Current OG Group from context (*Please make sure that you have OG Context turned on or this will not work*).
* Save the view.
* Set the block and navigate to a group content page, you should see the block.

I am adding some screenshots just incase anyone needs some visuals, there aren't many but if anyone needs some more visuals just let me know (*and Yes I know I need to upgrade to 7.38*).

**Basic view export**

*This does not have any filtering or anything to make it not show on the actual group screen or anything like that. So you will have to add those things yourself. This is just the basic link back to the group from group content. However, it will not show on node content that is not part of a group at all. So you could technically use block settings to make it show only on the node types that you want.*

```
$view = new view();
$view->name = 'og_block_link';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'OG Block Link';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'OG Block Link';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'og_context';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

*Please let me know if you have any issues with this and I will be happy to add/edit my answer with more information, thanks!*

# Answer
> 0 votes
burnsjeremy was right that the information I need is available to my node itself. To get this into a views block to position in a different place etc I can use contextual filter on 'Content: Nid' and 'When the filter value is NOT available' set the 'default value' to 'Content ID From URL'. I can then add the fields as normal via views.

Next will be the challenge of getting the parent group of a child group when on the node of a piece of content within the child group.

---
Tags: organic-groups
---


title: How to use user feedback from Webforms

text:
# Question
Title: How to use user feedback from Webforms
Say I want to ask the user to rate articles on usefulness from 1-10.

How can I apply that rating to weight calculations for future searches of the same issue/tags?

I would like the most useful articles to appear higher in the search results.

# Answer
Best using of any of below module to solve your query. I think as per your query, no any module for 1-10 rating. Hope these module help you to do same as you want.

1. Star Rating

> Star Rating is a simple module that provides star rating field and display formatter using Drupal 7's Field Type API.

2. Rate

> This module provides flexible voting widgets for nodes and comments.

3. Fivestar

> The Fivestar voting module adds a clean, attractive voting widget to nodes and comments and any entity.
> 1 votes

# Answer
Refer to my answer to the question about "Is there a Drupal rating module that lets you rate from 1 - 10?" for an "inventory" of rating related modules.

Note that quite a few of these modules have the VotingAPI module as a dependency.

To actually "*apply that rating to weight calculations for future searches*", you might consider including these rating results via an appropriate set of fields in a "View" that you'd created to display your search results, which you'd probably then also want to "sort" by the rating results (like 'highest rated' first).
> 0 votes

---
Tags: webforms, search, rating
---


# Question
Title: Search API module causes server error when saving index fields
I am very new to Drupal, so please let me know if I'm doing something wrong.

Using the Search API module, I would like to go change some fields of my Node Index. For example, I would like to uncheck the "Title" field so it is no longer indexed for searching. However, the problem arises when I try to save this or any other change to the fields. I get an error page saying "Your browser sent a request that this server rejected, possibly due to security scanner restrictions." and the fields remain unchanged.

Similar posts have given me the sense that the fix may be to uninstall/reinstall the module. But this module is so fundamental to everything I've been doing over the last few days. If I uninstall/reinstall the module, will it erase everything I've done?

**Update**: I disabled the server and then enabled it and now the index fields are working (yay) but it deleted my search (boo)

# Answer
After you disable a module (not 'server' ... as in the "update" part of the question ...) and then enable it again, problems like these might get resolved. There are other situations (and modules) where some similar issues occur, and then get resolved via such disable/enable.

To avoid loosing data (like your search that got deleted), this is a possible approach you may want to consider:

* look at the module's \`.install) file to find out which table it created (during install).
* perform a backup of the tables that are mentioned in the `.install` file (before uninstalling the module.
* disable the module, which will also perform the steps you can see within the .install file (for uninstall now) and then enable the module again.
* restore your backup of your tables related to the module.
> 0 votes

---
Tags: entities, search, debugging
---


# Question
Title: Display Suite module is not displaying field labels
I am using the Display Suite module (version 7.x-1.9) and Drupal 7.37.

I selected above or inline in the Label column for all the fields, but I don't see the labels on my page for any fields.

I also don't see the display suite tab when I try to edit the page. If I want to change the layout, I have to go to *admin \> module \> ds \> configure* to change the layout.

Can anyone help me workout what's happening?

# Answer
> 1 votes
The page you see is from the "**Default**" Manage Display. Make sure you use this instead of others. The Display Suite layout is based on per content type, not per node. To change the Default display, you should go to "***Structure \> Content types \> Your content type \> Manage display***" or "***Strurture \> Display Suite \> Manage display(your content type)***".

**=== Update: June 25, 2015 at 8:37am - screenshot for @Kaimei Wang ===**

---
Tags: display-suite
---


# Question
Title: Drupal Rule to deselect radio button item?
In Rules, I don't see any option to deselect radio button items.

In my rule, I want an **Action** which is to deselect 'Request Resubmission', as in this screenprint.

# Answer
There is none that I'm aware of.

Radio buttons aren't meant to be deselected (a single selection is required). I would suggest using checkboxes to deselect an option or add a "None" option to your radio group.
> 2 votes

---
Tags: rules
---


title: Programmatically populate a Drupal form

text:
# Question
Title: Programmatically populate a Drupal form
I am very new to Drupal and trying to write a module. I have 2 entities - Membership and MembershipRequest and both are fieldable. A MembershipRequest is a request to the admin of the website to create or update (renew/delete) a Membership entity. On the MembeshipRequest form, I want to populate the form elements with Membership entity values that user are requesting to update. For example, on the request form's First name text box, I want to populate the Membership's First name. I have membership\_id property in the the request entity. But the First name and other fields are attached to both entities via Field API.

I am not sure which object (and how) - $form, $form\_state, $request - I need to modify so that the request form will show up with populated values.

Thanks a lot.

# Answer
If you insist on programming this, and not use and configure contrib modules -

### If fields were added to entity bundle via drupal admin UI

You can use `hook_form_alter()` or `hook_form_FORM_ID_alter`, and in the code there have the particular field populated with desired default value.

* hook\_form\_alter() would be invoked for all forms and you would have to have an if condition to target just the desired form id.
* hook\_form\_FORM\_ID\_alter() would be invoked for particular form.

### If field was attached using Field API code (not the case for this question)

You would have an implementation of `hook_field_attach_form()` to attach fields to your MembeshipRequest entity. It would be in that hook implementation that you would set a `#default_value` to the desired form field.

### Code to use in either of the cases above

```
$form['foo']['bar'] = array(
  '#type' => 'textfield',
  '#title' => t('foobar'),
  '#default_value' => _func_to_get_default_value($member_id),
  '#description' => t('something something'),
  '#size' => 60,
);
// NOTE: Replace foo/bar with the particular field etc.

```
> 2 votes

# Answer
Have a look at Entity reference autofill.

> The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.
> 0 votes

---
Tags: forms, entities
---


# Question
Title: Hitting the back button after a batch process cause a nasty error
I have a batch process (using batch API) that runs when a user on my site tries to launch a non signed Java applet. The batch process does all the needed codesigning and other things and then redirects the user to the applet when it is finished. This all works well but if the user hits back from the applet page they get this nasty error with the text from my batch\_error function.

It seems that this occurs because when you hit back you end up trying to run a batch process that no longer exists. Is there anyway to avoid this?

EDIT:

Here is my function that sets up the batch process:

```
function batch_codesign($node) {
$batch = array(
   'operations' => array(
        array('batch_codesign_process', array("create_jar_files", $node)),
        array('batch_codesign_process', array("output_new_agentsheets_applet_html", $node)),
    ),
    'finished' => 'batch_codesign_finished',
    'title' => t('Codesigning'),
    'init_message' => t('Codesigning ' . $node->title .'.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error has occured while condesigning the project, please try again.'),
    );
batch_set($batch);
$nid = $node->nid;
batch_process("path/to/endpoint");
}

```

# Answer
> 1 votes
Here's a possible solution, however you'll need to alter the menu callback for `batch` and wrap the default page callback.

Create your hook\_menu\_alter() and change `batch` to be your own page callback function, and update the file attribute (unset if in your .module)

```
// Default page for batch operations.
$items['batch'] = array(
  'page callback' => 'system_batch_page',
  'file' => 'system.admin.inc',
);

```

Basically your callback can call the default `system_batch_page()` page callback (wrap it). From there you can adjust what happens when someone hits an inactive or stale batch.

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


# Question
Title: How can I see what visitors are searching for?
Are visitor search terms stored somewhere in Drupal 6? I see a **search\_total** table that might hold that info but the data in there looks kinda weird.

I'm using search module in core.

# Answer
Unfortunately it's pretty limited.

View top search phrases (in Drupal 6.x): yoursite.com/admin/reports/search

The data originates from the *watchdog* table, which means that how much data is provided depends on how far back your watchdog data goes (usually not far).

The Search Log module will provide more robust results. Or use Google Analytics, as the commenter above suggested.
> 0 votes

# Answer
We use Piwik Analytics for this. piwik.org
> 0 votes

---
Tags: 6, search
---


title: Display all menu levels

text:
# Question
Title: Display all menu levels
I'm trying to output a menu with all of its submenus into a template file, currently I'm using the code below. The problem is that it only displays the top level links. If I pass the second $level parameter into menu\_navigation\_links it'll then only display that one level, not any of the others above or below.

How can I display all the different menu levels & still have the ability to add classes to the as below? The title isn't really that important as I can 'hard code' that tag into the template file.

```
print theme('links__menu_top_page_navigation', array('links' => menu_navigation_links('menu-top-page-navigation'), 'attributes' => array('id' => 'main-menu', 'class' => array('main-menu', 'list-menu')), 'heading' => array('text' => t('Main menu'),'level' => 'h2','class' => array('main-menu-title'))));

```

The closest thing I've found so far is to use menu\_tree\_all\_data() & menu\_tree\_all\_output() but I cannot see how to edit the class using that.

# Answer
I've managed to find an answer in a Stack Overflow answer https://stackoverflow.com/a/30570027/1094862

For completeness I've copied the relevant code below:

```
$main_menu_tree = menu_tree_all_data('menu-name', null, 3);
render_menu_tree($main_menu_tree);

function render_menu_tree($menu_tree) {
  print '<ul>';
  foreach ($menu_tree as $link) {
    print '<li>';
    $link_path = '#';
    $link_title = $link['link']['link_title'];
    if($link['link']['link_path']) {
        $link_path = drupal_get_path_alias($link['link']['link_path']);
    }
    print '<a href="' . $link_path . '">' . $link_title . '</a>';
    if(count($link['below']) > 0) {
      render_menu_tree($link['below']);
    }
    print '</li>';
  }
  print '</ul>';
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Add JavaScript to a page without access to core files?
I apologize in advance if this is a really simple question, but I'm pretty new to Drupal and still figuring out my way around things. So I was wondering if it is possible to add JS to a certain node or page of Drupal if I don't have access to the core library of files? I've searched around before and a lot of people have talked about somehow inserting a file into the directory, but I'm only granted access to the Drupal pages and the Appearance settings where I can add to/edit the CSS of a page.

Thanks!!

# Answer
> 0 votes
If the developer has granted your user role access to the appropriate input formats and and has it configured to allow JS then yes, you can.

You may see a select box under one or more of the fields that allows you to select a filter such as "filtered HTML", "Full HTML" etc..

This is however normally locked down to prevent content editors from breaking a site, so I would be surprised if your limited role had access to unfiltered HTML/JS input.

A quick way to test if it works would be to add `<script>alert('test');</script>` in the box and save/refresh the page.

---
Tags: nodes, javascript, 7
---


# Question
Title: Import data into Select List using using Feeds and the Feeds XML Parser from xml file
I have to import some data from a xml document.

I'm usuing the https://www.drupal.org/project/feeds and the https://www.drupal.org/project/feeds\_xpathparser modules.

I have other fields which get the data with no problem at all. But I can't get a **Select list** to get the data from the xml.

**XML LOOKS LIKE**

```
<properties>
  <property>
    <type>House</type>
  </property>

  <property>
    <type>Flat</type>
  </property>

  <property>
    <type>Parking</type>
  </property>
</properties>

```

**INFO OF THE field "Type" WHICH GET THE DATA:**

**Type:**

```
List (text)

```

**Control:**

```
Selection List

```

**Allowed values list:**

```
House|House
Flat|Flat
Parking|Parking

```

**THEN, IN THE FEED IMPORT SETTINGS:**

```
-MAPPING: add the xpathparser selecting the field "Type"
-XPHATH XML PARSER - Settings: set the XPath for the field to "Type"

```

As far as I see everything is all right, but it doesn't work.

I have other fields in the same importer which get the data with no problem at all.

# Answer
If you're on Drupal 7.x, you probably want to be using this module:

https://www.drupal.org/project/feeds\_ex

This is the new home for no-longer actively maintained one (https://www.drupal.org/project/feeds\_xpathparser)

I've been using feeds\_ex and haven't had this problem.

Also, and I'm not sure about this, but I think the machine names for the list values should all be lowercase - but I could be wrong about this.
> 0 votes

---
Tags: feeds
---


# Question
Title: Where is documentation for $entity->data property? I.e. $commerce_order->data
I've searched google and the Drupal API, but I can't seem to find documentation for the data array that serializes/unserializes automatically that is attached to entities and stored in the data column on some entities, particularly commerce\_order. Searching for the world "data" is like searching for the word "the." Where/how is the data array serialized and unserialized?

# Answer
> 2 votes
The data attribute is part of the Commerce Entity definitions, and I think this might be part of the larger de facto Entity API setup for contrib entities (don't quote me on that ;).)

If you want to find the documentation on properties and how they are handled you need to review the EntityController class, which each Commerce module has in its includes folder.

commerce\_order.controller.inc#n135

```
/**
 * Unserializes the data property of loaded orders.
 */
public function attachLoad(&$queried_orders, $revision_id = FALSE) {
  foreach ($queried_orders as $order_id => &$order) {
    $order->data = unserialize($order->data);
}

```

The database layer automatically serializes, if I recall correctly. However controllers need to unserialize.

Hopefully this *this* question and other entity related items (also make sure to review hook\_entity\_info() implementation.)

---
Tags: entities, commerce
---


title: how to calculate a value by rules

text:
# Question
Title: how to calculate a value by rules
I have three fields in a content type and want to calulate sum of them in another field. First, I use Computed Field but it does not work at all. Then I tried to use conditional field but it is not made for this purpose at all. So I am trying rules module and make an event: After saving new content(or before) - The condition is: Content is of type \[something\] - The action: Execute custom PHP code.

And the code is:

```
$field_a = field_get_items($entity_type, $entity, 'field_absence');
$field_b = field_get_items($entity_type, $entity, 'field_delay');
$field_c = field_get_items($entity_type, $entity, 'field_vacation');
[node:field-sum] = $field_a[0]['value']+$field_b[0]['value']+$field_c[0]['value'];

```

But it does not do anything at all. I used the same code in computed field but it has no result. I'm not an expert Drupal programmer. So I need your helps in it. Thanks in advance.

# Answer
The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field that does not require the use of PHP Filter.

**Note**: the above info is an excerpt from its project page.
> 2 votes

---
Tags: rules, entities
---


title: Add Html code to Menu Title in Bartik

text:
# Question
Title: Add Html code to Menu Title in Bartik
I am trying to add my own image menu names (I prepared png files) instead of menu titles (Navigate, Category, Home etc.). How can I do this? Which files should I need to check? I know Html Menu module but it does not work on menu titles.

Thank you.

# Answer
> 0 votes
Firstly I'd say menu titles should be text, for accessibility, maintainability and SEO reasons.

If you must, you could consider using CSS background images by checking the classes or IDs on those menu elements and adding CSS rules target them.

# Answer
> 0 votes
Try to use MenuImage module. Hope you will got result as you want. I have not try this module.

> When editing a menu link, this module provides a file field to upload an image to associate with a menu item. In the array returned by menu\_link\_load, the fid of the image file is contained in \[options\]\[content\]\[image\]. This may may be passed as a parameter to file\_load to obtain its public:// uri, and further used with either file\_build\_uri or image\_style\_url to populate the src= attribute of an .

**OR**

Use Menu Icons module.

> This module allows you to upload an image in the menu-item's configuration form.
>
> After uploading the image, the icon data will be added to the menu link's options array.

---
Tags: routes
---


# Question
Title: "You are not authorized to access this page." immediately after logging in with any user
I'm getting the seemingly famous `You are not authorized to access this page.` message whenever I log in to my local development environment from `/user` or from `/user/login`. I'm on Drupal 7.26, PHP 5.6.3, running under XAMPP 3.2.1.

I've tried clearing all browser history, truncating flood and session tables, making sure I'm not defining $cookie\_domain. I'm sure I've tried other things, but nothing seems to work. What should I try next?

This is one of those "this worked yesterday" things that became one of those "I was sure I fixed this but I have no idea how" things.

**edit:** So I ran the following to disable most of the modules and then logging in worked again:

```
drush @alias pm-list --type=Module --no-core --status=enabled | sed 's/.*(//' | sed 's/).*//' | sed '/^ *$/d' | sed '/^.*views.*$/d' | sed '/^.*entity.*$/d' | sed '/^.*ctool.*$/d' | sed '/^.*ctool.*$/d' | sed '/^.*date.*$/d' | sed '/^field_collection$/d' | sed '/^link$/d' | sed '/^youtube$/d' | sed '/^block.*$/d' | tail -n+2 > modules.txt; cat modules.txt
drush @alias dis `cat modules.txt`
drush @alias cache-clear all

```

I did have some issues such as Fatal error: Call to undefined function entityreference\_get\_behavior\_handlers() in entityreference\_schema(), which is why that command is so ugly. (I'm sure there's a neater sed command.) Now I'm turning on the modules one at a time.

**edit:** Disabling all modules and then re-enabling all modules except for the libraries module and modules that depend on allows us to log in again. However, enabling that module breaks logging in. This problem is only in our local development environments, not our hosted environments.

# Answer
Backup the database and rebuilt the permission of the user under "/admin/reports/status/rebuild"..
> 1 votes

# Answer
This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing ?q=user or ?q=admin. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

```
RewriteRule . index.php [L]

```

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that brower you are able to login, then it's probably a cookie problem (in your original browser).

**Update**: as per the extra comment you added (with that 'Warning' you mentioned), you may want to look at Warning: "Headers already sent" or "Cannot modify header information", which contains 3 typical reason that cause these errors, and how to resolve them. Here is a summary of that link:

* it means that somewhere in the code, something was printed to the browser before Drupal had finished preparing the page. This is most often caused by custom or modified code contributed from sources outside Drupal, so inspect your uniquely added code (including themes) first ...
* **Cause 1**: If this error is not the first error message on the page, then it is most likely a 'avalanche effect' of previous errors and you may ignore it. Instead, focus on fixing the errors before it. When you fix the first error message(s), the "Headers already sent" error(s) will most likely disappear.
* **Cause 2**: Text editors sometimes insert a UTF-8 byte order mark at the top of a file. In this case, the error message will usually say that "output started" at line 1 of some file. To fix this, configure your text editor to save the file without a byte order mark.
* **Cause 3**: If you get an error "Headers already sent" as the first error and it tells you the error is near the end of a file (check which file "output started at" points to), that probably means that there are extra spaces or lines after a closing `?>` php tag. In Drupal coding standards, it is strongly recommended (for this very reason) that PHP files should not have any closing `?>` tags. to fix this, just delete them, and everything should work fine.

Notes:

1. Extra whitespace being added probably is caused by a bad unpacking program and / or a non-compliant editor (Windows Notepad or Wordpad, Mac TextEdit) adding it.
2. The question about Warning: Cannot modify header information - headers already sent contains some more details / hints that might help to understand what's happening, or to further debug it.
> 0 votes

---
Tags: users
---


# Question
Title: Correct way to add language switcher to a menu
I'm trying to add a language switcher to one of my menus using the `hook_preprocess_page()`:

```
function <MODULE>_preprocess_page(&$variables) {
  // append language switcher to top_menu
  if(drupal_multilingual()) {
    global $language;
    include_once DRUPAL_ROOT . '/includes/language.inc';
    $info = language_types_info();

    $lang_types = language_types_configurable(FALSE);

    $path = drupal_is_front_page() ? '' : $_GET['q'];

    foreach($lang_types as $type) {
       $languages = language_negotiation_get_switch_links($type, $path);
       if(isset($languages->links)) {
         foreach($languages->links as $lang => $link) {
           if ($lang != $language->language) {
             $alias = drupal_get_path_alias($link['href']);
             $info = path_load(array('alias' => $alias));
             if(drupal_is_front_page()) {
                $alias = '';
             }
             $variables['page']['top_menu']['menu_block_2']['#content'][] = array(
                '#theme' => array('menu_link'),
                '#title' => $link['title'],
                '#href' => $alias,
                '#attributes' => array(),
                '#query' => array('language' => 'sv'),
                '#localized_options' => array('query' => $link['query']),
                '#below' => array(),
                '#original_link' => array(),
                '#bid' => array('module' => 'menu_block', 'delta' => 2)
             );
          }
        }
      }
    }
  }
}

```

I display the normal top menu in my `page.tpl.php` like this:

```
    <div class="normal-menu">
      <?php if(isset($page['top_menu'])): ?>
      <div class="top-menu">
        <?php print render($page['top_menu']); ?>
      </div>
    </div>

```

The above code works fine for my normal menu, but I also have a mobil menu which content I store in the following two variables:

```
function <THEME>_preprocess_page(&$variables) {
  $main_menu_tree = menu_tree_all_data('main-menu');
  $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);
  $top_menu_tree = menu_tree_all_data('menu-top-menu');
  $variables['top_menu_expanded'] = menu_tree_output($top_menu_tree);
}

```

Then in my `page.tpl.php` file I output the contents for my mobil menu like this:

```
<div id="mobile-menu">
  <?php print render($main_menu_expanded); ?>
  <?php print render($top_menu_expanded); ?>
</div>

```

The strange thing is that the language switcher isn't added to the mobile menu, while it turns up without any problems in the normal menu.

# Answer
It's not strange it's a question of order.
You use `theme_preprocess_page` and `module_preprocess_page`.
`theme_preprocess_page` runs first, this mean you save your menu before you change it.
Easy option would be, to add your `theme_preprocess_page` part to your `module_preprocess_page`.
(Set it outside of the `if(drupal_multilingual()) {}` and it run even if the if return false)
Better option would be to create a module for your mobile menu, and set it's weight so it run after your other module.

**EDIT:** Ignore the Part about the order this https://www.drupal.org/node/223430 confussed me so i thought about template\_preprocess\_hook not the theme\_preprocess\_hook.
The Problem is your call, you think you add the switcher to the menu. But you just add temp items. On your call for mobile you get the original Menu (so no lang switch).
You could fix it by adding the lang fix to the menu and not temp.
You could extend your module so you would get the new Menu for your vars.
> 1 votes

# Answer
If you check this page https://www.drupal.org/node/223430 you will see that template preprocess hooks run before module preprocess hooks. This means that language is switched after you have rendered your mobile menu.
> 1 votes

# Answer
Try out this module Language Switcher . I hope this may help as you expected
> 1 votes

# Answer
I managed to achieve my desired result by using `theme_menu_link()`:

```
function <THEME>_menu_link(array $variables) {
  $element = $variables ['element'];
  $sub_menu = '';

  if($element ['#below']) {
    $sub_menu = drupal_render($element ['#below']);
  }

  // check so this is the top menu and this link is the last one
  $add_language = (($element['#theme'] == 'menu_link__menu_top_menu' ||
                    $element['#theme'][0] == 'menu_link__menu_block__2') &&
                    in_array('last', $element['#attributes']['class']) ? 1 : '');
  if($add_language != '') {
    // append language switcher to top_menu
    if(drupal_multilingual()) {
      global $language;
      include_once DRUPAL_ROOT . '/includes/language.inc';
      $info = language_types_info();
      $lang_types = language_types_configurable(FALSE);

      $path = drupal_is_front_page() ? '' : $_GET['q'];

      foreach($lang_types as $type) {
        $languages = language_negotiation_get_switch_links($type, $path);
        if (isset($languages->links)) {
          foreach($languages->links as $lang => $link) {
            if ($lang != $language->language) {
              $alias = drupal_get_path_alias($link['href'], $lang);
              $info = path_load(array('alias' => $alias));
              if(drupal_is_front_page()) {
                $alias = '';
              }
              $item = array(
                '#theme' => array('menu_link'),
                '#title' => $link['title'],
                '#href' => $alias,
                '#attributes' => array(),
                '#query' => array('language' => 'sv'),
                '#localized_options' => array('query' => $link['query']),
                '#below' => array(),
                '#original_link' => array(),
                '#bid' => array('module' => 'menu_block', 'delta' => 2)
              );
            }
          }
        }
      }
    }
    $add_language = l($item['#title'], $item['#href'], $item['#localized_options']);
    $add_language = '<li>'.$add_language.'</li>';
  }

  $output = l($element ['#title'], $element ['#href'], $element ['#localized_options']);
  return '<li' . drupal_attributes($element ['#attributes']) . '>' . $output . $sub_menu . "</li>\n".$add_language;
}

```
> 1 votes

---
Tags: 7, routes, i18n-l10n
---


title: what can replace hook

text:
# Question
Title: what can replace hook
I am a newbie into Drupal.

what else other than module name can replace 'hook' from any hook function in Drupal?
For ex. "myModule" replaces hook in hook\_form\_alter and defined as 'myModule\_form\_alter'

# Answer
> 0 votes
If you are particularly looking at theme hooks following from https://www.packtpub.com/books/content/drupal-7-module-development-drupals-theme-layer can be useful.

> All preprocess functions run before all process functions template\_ prefixed functions run frst. \[module\]\_ prefixed functions run next. \[theme\]\_ prefixed functions run last Multi-hook functions run before hook-specific functions This results in the following order of execution for a particular theme hook:
>
> template\_preprocess()
>
> template\_preprocesss\_HOOK()
>
> MODULE\_preprocess()
>
> THEME\_preprocess()
>
> THEME\_preprocess\_HOOK()
>
> template\_process()
>
> template\_processs\_HOOK()
>
> MODULE\_process()
>
> MODULE\_process\_HOOK()
>
> THEME\_process()
>
> THEME\_process\_HOOK()

# Answer
> 1 votes
Any **alter hook** and **preprocess hooks** that is defined inside a module can also be defined inside the theme as well. So if you are using *Bartik* theme you can open the *Bartik*'s template.php file and use

```
function bartik_form_alter(){}

```

---

**UPDATE**

Checking the Is it possible to define hook functions in template.php instead of the module? can also be helpful.

---
Tags: hooks
---


# Question
Title: Adding ASCII characters to HTML links in Drupal
I've written the decimal HTML entry of the "Logical or" ASCII note in a menu-link and yet I don't see the character. What I do see is the decimal HTML entry... Why is that? Is this problem solvable without any modules? Thanks,

# Answer
> 1 votes
You can use the Menu HTML module for that.

It uses a bunch of alter hooks, which means you could theoretically reproduce the same functionality in a theme if you really want to. So yes, it's possible to solve without using a module per se.

Modules are the proper way to add such functionality, though, hacking this into a theme is bad application design in my opinion. Drupal is, intentionally, a modular system; don't be scared of installing modules to add functionality, *that's what you're supposed to do* :)

---
Tags: theming
---


# Question
Title: Views module core patching inside a sub-site
I have a multi-site setup like below:

abc-parent/sites/all/modules/views abc-parent/sites/pqr-child/modules/views (consisting core patching done in views)

When i do the above i get errors like cannot redeclare function

I wanted to do a core patching for views inside just 'pqr-child' site so that customization remains only to pqr-child and not for all the sites inside 'abc-parent'

Can anyone please help me achieve the above.

Thanks.

# Answer
> 1 votes
Modules that are placed inside `sites/all/modules` directory are accessible to all sites setup inside sites directory. Thats why it is showing you the error.

So basically you are trying to apply a patch for `pqr-child` site only. So you can do :

1. If it is a general patch, you can apply it to `sites/all/modules/views` directory. So there is no need of adding views directory for pqr-child site.
2. If it is a **hack**, then my suggestion is not to hack the module, instead you can write a custom module to fulfil your requirements.
3. But if it still necessary to hack the module, you need to copy the `sites/all/modules/views` to all the `sites/subsites/modules` directory and delete it from `sites/all/modules`.

---
Tags: views, 7, multi-sites
---


# Question
Title: How to show specific views for certain combinations of taxonomy terms?
I have searched and not been able to find anything related to this specific situation.

I would like to show specific views for certain combinations of taxonomy terms in Drupal 7.

I have three different taxonomies each with different terms (I have changed the terms here to make them easier to understand):

```
Fruit
  - Apples
  - Oranges
  - Bananas

Numbers
  - 1
  - 2
  - 3

Letters
  - a
  - b
  - c

```

Using these terms I already have a view that shows all items tagged with specific terms based on url such as:

```
/fruit/apples/1/a
/fruit/apples/2/c
/fruit/bananas/3/b

```

I achieved this with a view which uses a url in the form of `/fruit/%/%/%` and multiple contextual filters of type 'Has taxonomy term ID'.

So far so good.

What I would like to do is have **different view displays that show for specific urls/combinations of terms**:

```
/fruit/apples/1/a  - display 1
/fruit/apples/1/b  - display 2
/fruit/bananas     - display 3
/fruit/oranges/1/a - display 1
/fruit/oranges/1/b - display 2

```

Does anyone know how I can achieve this or have any alternate solutions/ideas?

# Answer
In a custom module you could implement the hook hook\_views\_pre\_view()

e.g.

```
function my_module_views_pre_view(&$view, &$display_id, &$args) {

    if ($view->name == 'the_view') {
        // if url matches certain pattern
        $view->set_display('your display');
    }

}

```
> 7 votes

# Answer
There is also another solution. You can use context module.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

After installing module and adding new context use **Path** as a condition and **Template suggestions** as a reaction.

In the **Path** you can define wildcards (\*) so for every path pattern you can define special **Template suggestions**. As an example:
> 3 votes

# Answer
What about just use different views template to customise the output?

In your theme template.php, add:

```
function my_theme_preprocess_views_view(&$vars){
  if($vars['view']->name == 'my_view_name'){
    if($vars['view']->args[1]==1&&$vars['view']->args[2]=='a'){
      $vars['theme_hook_suggestions'][] = 'views_view__my_view_name_display_1__page';
    }elseif($vars['view']->args[1]==1&&$vars['view']->args[2]=='b'){
      $vars['theme_hook_suggestions'][] = 'views_view__my_view_name_display_2__page';
    }elseif(!isset($vars['view']->args[1])){
      $vars['theme_hook_suggestions'][] = 'views_view__my_view_name_display_3__page';
    }
  }
}

```

Then add those template file, like 'views-view--my\_view\_name\_display\_1--page.tpl.php' to customise the different output.
> 1 votes

# Answer
Another option if you want to use the UI would be to use Page Manager. You can create the /fruit/%/%/%/ path and use the arguments to choose which variant of the page to display (using selection criteria).

Each variant could simply show a different view display, or could be wildly different including layout if you so desire.

You needn't use the 'panel pane' display in views but that can make it easier to pass the arguments (once you've learned how to use it).
> 0 votes

# Answer
You can try `hook_views_query_alter`

> Alter the query before executing the query.
>
> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.
> 0 votes

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


# Question
Title: Submit button to filter data from table select by selecting on list select
i'm new on drupal, i've create a module that shows a form (with tableselect, list select and a submit button) the tableselect shows data from the database, but i want to filter what i want to see on the table by selecting what i want from the list select and submit. i've create the submit function (it contains the query with condition) and when i use dsm($form\['tableselect'\] everything works (filter works), but how can i show the result's select on the tableselect ? because it doesn't change

here's my form :

```
$form['options_state'] = array(
    '#type' => 'value',
    '#value' => array (
        'all'=>t('All'),
        'Valid'=>t('Valid'),
        'published'=>t('published'),
        'not published'=>t('not published')

        )

    );

$form['state_book'] = array(
    '#type' => 'select',
    '#title' => t('state :'),
    '#options' => $form['options_state']['#value'],
);

// filter submit button

$form['filter'] = array(
    '#type' => 'submit',
    '#value' => t('filter')
    );

```

and this is my table select (the first one shows all records) ;

```
$header  = array(
    'book_title' => t('title'),
    'book_state' => t('state'),
);

    $sql = db_select('field_data_field_title','ta');
    $sql->join('field_data_field_state','st','st.entity_id = ta.entity_id');

    $sql
        ->fields('ta', array('field_titre_en_arabe_value','entity_id'))
        ->fields('st',array('field_state_value'));
        $result = $sql->execute();

    $rows = array();

foreach ($result as $res){

$rows [] = array(
        'book_title' => l($res->field_title_value, 'node/'.$res->entity_id),
        'book_state' => $res->field_state_value
      );

}

$form['table1'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty !'),

);

return $form;

```

}

table1 works, but it shows all records (book published and not published) now here's my submit function :

```
function book_form_submit($form, &$form_state){

$cond = $form_state['values']['state_book'];

$header  = array(
    'book_title' => t('title'),
    'book_state' => t('state'),
);

$sql = db_select('field_data_field_title','ta');
$sql->join('field_data_field_state','st','st.entity_id = ta.entity_id');

$sql
    ->fields('ta', array('field_title_value'))
    ->fields('st',array('field_state_value'));

    $sql->condition('st.field_state_value', $cond, '=');

$quer = $sql->execute();

$rows2 = array();

foreach ($quer as $q){

    array_push($rows, array(
        'book_title' => $q->field_title_value,
        'book_state' => $q->field_state_value,

    ));

}
$form['table2'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty!')
);
}

```

Now how can i put result of submit on table1 to show what the query returns ??

Thanks

# Answer
Digging in, and trying to run some pseudo code it looks like there may be a problem with AJAX callbacks and tableselect fields regarding Drupal Core.

https://www.drupal.org/node/1458824 (7x and 8x)

I would consider using the Views module with exposed filters.

You could fairly easily create a view that displays 2 articles, which exposes a state drop down list. You could use a page or block view for the front end.

If you update your question with what you are ultimately trying to accomplish I can try to put together a more appropriate Views setup.
> 1 votes

# Answer
i finally set a `$form_state['storage']['state_book']` and i set the `$form_state['rebuild']` on the submit function after doing :`$form_state['storage']['state_book'] = $form_state['values']['state_book'];` Do not forget to set default\_value on $form\[''\] like this :

```
$form['state_book'] = array(
    '#type' => 'select',
    '#title' => t('state of book :'),
    '#options' => $form['options_state']['#value'],
    '#default_value' => isset($form_state['storage']['state_book']) ? $form_state['storage']['state_book'] : '',

);

```

I've even do :

```
if (isset($form_state['storage']['state_book'])){
            $resultat->condition('st.field_state_book_value', $form_state['values']['state_book']); }

```

Thanx all
> 0 votes

---
Tags: forms
---


# Question
Title: How do I alter the submission button class?
```
 <input type="submit" class="form-submit" value="" name="op" id="edit-submit">

```

I want to alter the class from "form-submit" to "form-submitone".

How can do I do it? Where does the class "form-submit" come from?

# Answer
> 24 votes
If I were you, I would not change the class name but rather add your own class to the form element. You can do this by implementing hook\_form\_alter in a custom module or (in case of Drupal 7) in your theme. The code would look something like this:

```
<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'my_form') {
    $form['actions']['submit']['#attributes']['class'][] = 'form-submitone';
  }
}
?>

```

By the way, the submit button element is not necessarily `$form['actions']['submit']`. You will have to figure out which element is the submit button in your specific situation. You can do that by outputting the $form variable; I recommend installing the Devel module and adding `dsm($form);` to the function above.

# Answer
> 0 votes
this code basically user dor add your custom class on form submit button.

```
function subscriber_form(){
    $form['submit'] = array(
    '#type'  => 'submit',
    '#attributes'=>array('class'=> array('mybtn')),
    '#ajax' => array(
      'callback' => 'subscriber_ajax_callback',
    ),
    '#value' =>'Submit', // @FIXME doesn't render quotes properly
  );

}

```

---
Tags: theming
---


# Question
Title: How to enable bootstrap tooltip and popover (on a bootstrap based theme)?
I'm using a theme based on Bootstrap 3.

I want to use **Tooltip** and **Popover** features that come with Bootstrap but I couldn't.

It's said on the Bootstrap Javascript page that:

> Opt-in functionality
>
> For performance reasons, the Tooltip and Popover data-apis are opt-in, meaning you must initialize them yourself.
>
> One way to initialize all tooltips on a page would be to select them by their data-toggle attribute:
>
> ```
> $(function () {
>   $('[data-toggle="tooltip"]').tooltip()
> })
>
> ```

I tried to add the code above to my node.tpl.php (inside of tags) but it didn't work. I also tried to save that code as script.js and added it to my theme info file but it didn't work.

**How can I enable these features? Where to use the above code?**

# Answer
I could enable the tooltip and popover by adding the code below to my `node--mytype.tpl.php`:

```
<script>
(function($) {
$(document).ready(function() {
$('[data-toggle=tooltip]').tooltip();
});
})(jQuery);
</script>

```

I added this JavaScript to my custom `node--mytype.tpl.php` because I wanted to use tooltip **only** on that content type.

If you want to use the tooltip anywhere on the website (eg on the blocks), you should add the code above to your theme's **`html.tpl.php`** file, just before the closing body tag.
> 1 votes

# Answer
The best way to enable tooltips/popovers — using `selector` option (see this and this):

```
$(document).tooltip({ selector: '[data-toggle="tooltip"]' });
$(document).popover({ selector: '[data-toggle="popover"]' });

```

In this way it will work with dynamically generated tooltips/popovers too.

The complete code is:

```
<script>
  (function($) {
    $(function() {
      $(document).tooltip({ selector: '[data-toggle="tooltip"]' });
      $(document).popover({ selector: '[data-toggle="popover"]' });
    });
  })(jQuery);
</script>

```

You can place it either in:

1. Your theme's `.js` file (don't forget to remove `<script>` tag).
2. `page.tpl.php` template.
3. Custom block (in this case you can easily control on which pages to enable them).
> 1 votes

---
Tags: 7, theming, javascript
---


# Question
Title: Block value in a view row design template
I have a block value which I need to access in a views row design template. I need to check the value of the block content in this template.

Does anyone know how?

# Answer
You can use the following code.

```
$block = block_custom_block_get($block_id);
$content = $block['body'];

```

But be advised that it would generally contain html which would be difficult to parse.

If you are looking to store a value and then use it to check in the theme layer I would suggest creating an admin page for that and storing the value in the variables table, which you can later access by

```
variable_get('my_setting', 3);

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Add a "with +10 minutes" condition using db_select()
I'm trying to add a condition "within 10 minutes" using `db_select()`. This is my code.

```
$query = db_select('table1', 'c');
$query->innerJoin('table2', 'i', 'i.nid = c.nid');
$query->fields('c', array('cid', 'nid', 'container', 'users_list', 'api_key', 'regions', 'abbreviative'));
$query->fields('i', array('id', 'nid', 'image_path', 'image_style', 'final_image_name_path', 'retry'));
$query->condition('i.status', array('Pending', 'Failed'), 'IN');
// HAVING(Convert(DateTime, DateAdd(MONTH, tb_files.file_retentiondate, MAX(tb_records.rec_record_date))) <= getdate())
$query->condition(db_and()->condition('i.status', array('InProgress'), 'IN')->condition('i.last_updated', /* This is where I'm confused*/, '=')));
$query->condition('i.retry', 10, '<');
$query->orderBy('i.id', 'ASC');
$query->orderBy('i.retry', 'ASC');
$query->range(0, 10);
$entries = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

```

# Answer
> 0 votes
You can use this instead

```
->condition('i.last_updated', date("d-m-Y H:i:s"), ">")));

```

# Answer
> 1 votes
Try using the following in your condition:

```
->condition('i.last_updated', REQUEST_TIME - 10 * 60, '>=')));

```

Drupal uses most of the time UNIX timestamps, meaning you can easily calculate the difference by subtracting the number of seconds. In your case, it will be 10 minutes times 60 seconds per minute = 600 seconds.

`REQUEST_TIME` is provided by Drupal and gives you the current timestamp.

Hope this helps.

---
Tags: 7, database
---


# Question
Title: Drupal 7. Replacing core links with their aliases in theme templates
I want to check all templates before rendering and replace links
**node/1 node/3** ect to their aliases

For example, i have main landing page template
**page--front.tpl.php**
and there are some links in this template:
`<a href="node/1">Contact</a`\>
I want drupal to dynamically change such links to their aliases:
`<a href="contact">Contact</a>`
So, if i change alias for specific page, all urls will remain correct

Is it possible?

# Answer
> 2 votes
Not sure if this is what you're after, but in your tpl.php file you can change

```
<a href="node/1">Contact</a>

```

to

```
<a href="<?php print url('node/1');?>">Contact</a>

```

# Answer
> -1 votes
It sounds as though you have links hard coded into the template, which is probably a mistake. Can you replace the links with a menu or a block so they are easier to maintain?

However, to answer the question, you can use drupal\_get\_path\_alias('node/1') to obtain the alias. Be sure to prefix with a / as '/contact' may be different from 'contact' in different locations on the site.

You could also use the l() function to make the links: l('Contact', 'node/1').

I would really recommend trying to turn these links into a menu if you can and then putting that into the right template region using 'Blocks'. Your future self will thank you.

---
Tags: uri, 7
---


# Question
Title: Bootstrap theme overrides "theme_list_item" function and removes div's "item-list" class
How can I stop Bootstrap theme from overriding the them\_item\_list and replacing the div's class from item-list to panel-body?

I have the following form and it does not render the items

```
$stages = array(
1 => array('data' => '1. Step 1'),
2 => array('data' => '2. Step 2'),
3 => array('data' => '3. Step 3'),
);

$stages[$current_step]['class'] = array('active');

$stages_list = theme('item_list', array('items' => $stages));

$form['header'] = array(
    '#type' => 'fieldset',
    '#title' => '',
    '#value' => $stages_list,
);

```

the Above renders a navigation steps menu just fine with Bartik and other themes however, when it comes to Bootstrap it is empty rather having list of items.

I did some googling and found out this issue that might be somewhat relevant but, the solution does not seem to work for me. I tried to override the mytheme\_item\_list($variables) in template.php with following but, still no sign of the naviagtion.

```
function bootstrap_subtheme_item_list($variables) {
   $items = $variables['items'];
   $title = $variables['title'];
   $type = $variables['type'];
   $attributes = $variables['attributes'];

   $output = '<div class="item-list">';
   $output .= "<$type" . drupal_attributes($attributes) . '>';

   $count = 1;
   $num_items = count($items);

   foreach ($items as $item) {
      $attributes = array();
      $children = array();
      $data = '';
      $count++;

      if (is_array($item)) {
        foreach ($item as $key => $value) {
          if ($key == 'data') {
            $data = $value;
          }
          elseif ($key == 'children') {
            $children = $value;
          }
          else {
            $attributes[$key] = $value;
          }
        }
      }
      else {
        $data = $item;
      }

      if (count($children) > 0) {
        // Render nested list.
        $data .= theme_item_list(array('items' => $children, 'title' => NULL, 'type' => $type, 'attributes' => $attributes));
      }

      if ($count == 1) {
        $attributes['class'][] = 'first';
      }
      if ($count == $num_items) {
        $attributes['class'][] = 'last';
      }
      $output .= '<li' . drupal_attributes($attributes) . '>' . $data . "</li>\n";
   }
   $output .= "</$type></div>";

   dpm($output);

   return $output;
 }

```

The dpm above prints the exact thing piece of html that I want, the following but, the same is not rendered in the page.

```
<div class="item-list"><ul><li class="active">1. Step 1</li>
<li class="last">2. Step 2</li>
<li>3. Step 3</li>
</ul></div>

```

Not sure what I am doing wrong. Any solution that do not break other theme's would be very much appreciated.

# Answer
**1) Default markup.** To return default item list markup just do this:

```
function bootstrap_subtheme_item_list($variables) {
  return theme_item_list($variables);
}

```

**2) But.** Your issue is not caused by Bootstrap markup. Try this:

```
$form['header'] = array(
  '#markup' => $stages_list,
);

```

You are using `fieldset` incorrectly, learn Form API Reference.
> 1 votes

---
Tags: theming
---


# Question
Title: Custom theme function and template suggestion
I'm trying to create a theme function, with a template:

```
/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
    ),
  );
}

```

The my-template.tpl.php file is in the module directory and it works, I have added this to my page.tpl.php:

```
<?php print theme('custom_function', array()); ?>

```

I've tried to copy that template on my theme, but it doesn't work, Drupal always reads the module template, not the theme.

Have I forgotten something?

# Answer
```
/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
      'path' => path_to_theme(),
    ),
  );
}

OR for the my-template.tpl.php file is in the module directory

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
      'path' => drupal_get_path('module', 'mycustomtheme'),
    ),
  );
}

```
> 0 votes

# Answer
I think if you want the theme to pick up the template you need to put it in the theme folder not a module folder. I doubt very much that the theme system goes looking elsewhere for template files.
> -1 votes

---
Tags: theming
---


title: How do i search within views results?

text:
# Question
Title: How do i search within views results?
Consider i have a view which filter some Content Type according to a specific field.

I want to place a search box in the view page so the results of the view can be search able.

Is there a module? Or can i somehow do it with search api any tutorial for this?

# Answer
> 1 votes
Its not called search, it will be called filtering.

Goto your view and add a filter.

And then select the expose option in the filter.

---
Tags: views, search
---


# Question
Title: Alter a form based on where it is called from
I am using something on the lines of

```
  $view = views_get_current_view();
  $build = drupal_get_form("comment_node_contenttype_form",
  (object) array('nid' => $view-> args[0]));
  print render($build);

```

to print a comment form in my views.

My challenge is I am using the same code in two different displays. I need to make a few fields in the comment form required only when it is getting called from a particular display.

# Answer
> 0 votes
The following worked for me.

```
  if ($form_id == 'comment_node_CONTENT_TYPE_form') {
    $view = views_get_current_view();
    if ($view->current_display == 'block_1') {
      //Alter my form
    }
  }

```

I checked views\_get\_current\_view function. Since it is using caching there is no harm in calling it again.

---
Tags: views, forms
---


# Question
Title: Domain Access force node redirect to proper domain
Using Domain Access with Drupal 6, I am encountering an issue in the following scenario:

I set up a node published to a sub site, say:

```
subsite.com/node-x

```

If I browse to:

```
mainsite.com/node-x

```

I would like it to redirect to:

```
subsite.com/node-x

```

However, it just renders the content on the main site domain (which the search engines would pick up as duplicate content).

Any idea how I can configure the sites to redirect to the site on which the node is published? I attempted to use Global Redirect to redirect from the main site to the full url on the sub site but Drupal told me that I was redirecting something to itself. Are web server redirects my only option?

# Answer
> 2 votes
There is a special module for that: https://www.drupal.org/project/domain\_path\_rewrite.

The idea is to check the request path before the page load and to make a redirect to the proper domain if needed. Something like:

```
/**
 * Implements hook_init().
 */
function domain_path_rewrite_init() {
  if ($domain_path = _domain_path_rewrite_domain_path(current_path())) {
    global $_domain;

    if (!($_domain['domain_id'] == $domain_path['domain_id'] && request_path() == $domain_path['path'])) {
      drupal_goto($domain_path['url'], array(), 301);
    }
  }
}

```

# Answer
> 0 votes
Yep, I'm looking for D6, too.

Looks like D7 can be found here: https://drupal.org/node/1566058

This seems to work for D6: https://drupal.org/node/704568

# Answer
> -3 votes
I believe Domain 301 Redirect mixed with domain source will do what you are after.

> The Domain 301 Redirect module allows sites to 301 redirect to a domain that is marked as the main domain. This means you can have all subdomains and other domains pointing to the site 301 redirect to a domain that you choose as the main domain. This provides great SEO benefit.

---
Tags: redirection, domain-access
---


title: Entity Reference View format

text:
# Question
Title: Entity Reference View format
Is there a way to change the Entity Reference view to a different format than an entity reference list?

I'm trying to list taxonomy terms and other custom taxonomy fields to the user when they use the edit form of the node. Ideally, I would list the taxonomy reference as a table with multiple columns. I haven't found a way to convert this list to a table. Does anyone have any idea?

# Answer
You can use Entity Reference Views module

> This module provides an advanced Entity Reference widget that uses a view embedded in a modal dialog for selecting items. The view can be paginated and have exposed filters.

You can also use tables in your views for referencing now.
> 0 votes

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


# Question
Title: How to redirect links to a single domain in a multi-domain setup?
I am working on a project that uses Domain Access. The site has two domains one public(`example.com`) & one for members(`example.com/members`).

Some contents are common to both domains and some are domain specific.

Any link rendered on webpages has a relative path to that domain.

eg. A page that is displayed on both sites has the link (`/some/link`). Clicking it would take you to `example.com/some/link` if you click it on `example.com` AND to `example.com/members/some/link` if you click it on `example.com/members`

There are a few links that I want to appear on both domains but they should redirect to the members domain only.

eg. for the case described above the link should redirect to `example.com/members/some/link` even if it is clicked form the `example.com` domain.

Is there a way to do it?

UPDATE:

These are subdomains `example.com` & `members.example.com`. There is some server-side settings for url rewrite that makes them appear as `example.com` & `example.com/members` in URL.

# Answer
There is a special module for that: https://www.drupal.org/project/domain\_path\_rewrite.

The idea is to automatically rewrite the relative links to the absolute ones so they always point to the proper domain. Something like:

```
/**
 * Implements hook_url_outbound_alter().
 */
function domain_path_rewrite_url_outbound_alter(&$path, &$options, $original_path) {
  if ($domain_path = _domain_path_rewrite_domain_path($original_path)) {
    $path = $domain_path['url'];
    $options['external'] = strpos($path, '//') !== FALSE;
  }
}

```

Of course, is's only possible if you're printing the links programmatically. Otherwise nobody knows to which domain the links belong to and most likely you need custom rewrite rule.
> 1 votes

---
Tags: 7, navigation, redirection, domain-access
---


title: Entity Reference & View

text:
# Question
Title: Entity Reference & View
I am in the process of setting up a listing and review type scenario. I have set up the separate entity types, one for the listing, and three for the types of reviews. I kind of get how (from here and other sites) to set up these relationships using entity reference.

What I don't understand, is when I have a published listing, and I want the user to navigate to one of the three reviews, how do I make this happen? ie what do I do to set up this link and in what module? Is there a 'link' field to the review type, and the 'entity reference prepopulate' will take care of it?

So when it comes time to publish, I will have the listing and three columns for the different types of reviews.

Any help is much appreciated, new to drupal, having trouble connecting all the dots...

# Answer
> 0 votes
Check out Entity Connect Module

> Entity Connect now expands both Entity reference and References (node\_reference and user\_reference) fields by adding "add new content" and "edit current content" buttons.

Exactly what you need.

---
Tags: views, entities
---


# Question
Title: Invalid URL Aliases in Drupal Nested Sites/Subsites - Main 404
I'm sure my title made no sense! But I'm really struggling with something and could use some assistance.

I inherited a Drupal-based website a few months ago, and it was my first exposure to Drupal.

The way this website is set up is that it actually has three separate Drupal installs. Clean URLs is enabled with aliases set up. I'm sure this was the complete wrong way to set up multi-site, but unfortunately it is this way for now and I'm not confident I could correct it without breaking many things.

www.website.com (1st Drupal Install)

www.website.com/success (2nd Drupal Install)

www.website.com/spa (3rd Drupal Install)

For awhile, everything was working fine. But at some point the URL www.website.com/success/thank\_you, started to display a 404 error - but NOT /Success's 404 page - it would be the 404 display page of the base Drupal install! But still show www.website.com/success/thank\_you in the URL

Other Aliases on /Success continued to work, etc www.website.com/success/online, www.website.com/success/privacy.

If I typed in a garbage URL, say, www.website.com/success/abcdefg, i would get the 404 page of /Success install like it should, not the base Drupal.

I managed to "fix" this issue by changing the URL Alias of /success/thank\_you to /thankyou.

Now last week, it started happening with the other Aliases.

If I go to /success/thankyou it still works properly. If I do /success/online, or /success/privacy, I get the main Drupal's 404 page.

If I remove the Alias, I can do /success/node/20 and see the page. If I change the Alias to say, /success/online2 I can see the page. But if I change it back to /success/online, it does not work.

So, my current thinking has been that this is an issue with the base Drupal install, not the /success Drupal. That the base Drupal is grabbing that URL I am entering for some reason and seeing it's not an alias in that Drupal and failing. But why is it only happening to specific aliases? And why doesn't the base Drupal grab the URL if I type in a garbage one? (/success/abcdefg for example).

Any pointers in the right direction would be greatly appreciated.

# Answer
> 0 votes
# Option 1 - base\_url

Maybe you want to do some experiments to see if setting the `$base_url` in your settings.php somehow helps.

# Option 2 - RewriteRule

It might be worth trying to further enhance your .htaccess file, by adding a line after the line containing RewriteBase, which looks like so:

```
RewriteRule . index.php [L]

```

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

#

---
Tags: multi-sites, uri, debugging
---


# Question
Title: How to create a redirect for specific domain?
I'm using Domain Access and Redirect modules. Both work well.

But Redirect module only allows me to create redirects from relative path which affects as follows all my domains.

So how to create domain-specific redirect?

# Answer
> 2 votes
You can do this by using Domain Redirect module.

> This module allows the creation of an internal Drupal path that will direct the user to a unique path based on the domain that the user is in. The link is based at the path "/domain-redirect/12345" where "12345" is the redirect ID that is stored in the database.

**OR**

Try to use Domain Default Redirection module.

> This small module provides a redirection feature instead of providing the default domain contents in the Domain Access suite.

# Answer
> 2 votes
You can perform multisite redirect by using Multisite Redirect module.

> Multisite Redirect is a system designed to allow users to create and manage URL redirects across domains in a sort of multisite configuration. The primary use case for this module is one where a client might have multiple domains that are being consolidated into a single site.

---
Tags: redirection, domain-access
---


title: Use hook twice in a single module

text:
# Question
Title: Use hook twice in a single module
I have created a custom module with some inc files for different functionalities, these inc files adds config pages for admin but i had to define all urls in `.module` file.

is it possible to use hook\_menu in inc files as well, i already used it once in .module file. what i need is menu should be added from inc file itself.

# Answer
> 6 votes
You couldn't implement a single hook in the module twice.

Instead you can define a custom helper function like `_MODULE_include_menu()` in the `.inc` file and then use it in the main `.module` like:

```
function MODULE_menu() {
  $items = array();
  $items += _MODULE_include_menu();
  return $items;
}

```

---
Tags: 7, routes
---


# Question
Title: Make a "Taxonomy Term" Appear in search field
What my requirement is to display taxonomy terms in search results when someone searches for anything related/similar to it. For example: I have a taxonomy ABC, and articles 1,2,3,4 related to it. So when somebody searches ABC, along with article 1,2,3,4, ABC should also be visible there. I suppose i would have to edit the .tpl.php file of 'search display' and also add the required fields in the taxonomy fields(like image and description) which are required by the articles when searched.Where and how can i add fields in taxonomy terms.

# Answer
If you have Views installed, use the Views to create a new searchable page. Views has the "**Expose**", which allow user to change them. All you have to do in View, is to add the "**Taxonomy term: Name**" on "**Sort Criteria**" and check the "**Expose this sort to visitor, to allow them to change it**". See below screenshot for details.
> 0 votes

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


# Question
Title: How to set up multiple hierarchy taxonomy?
I am struggling to find the solution for the following situation: I am building a tourism site with POIs as nodes (Drupal 7). The POIs are categorized/tagged in a State-County-City hierarchical vocabulary. I want to add two another cathegories - Historical region and Tourism region. Each City belongs to exactly one historical region and one tourism region and these regions do not cover the same area (meaning that e.g. two cities belong to the same county, but to different historical and tourism regions). While creating new node/POI the user/editor selects the State-County-City via Simple Hierarchical Select module (this structure is generally well-known) and I want to automatically assign the corresponding Historical and Tourism region to the node, based on the City selected (as the division into Historical and Tourism regions is not obvious for the general userbase, but I have the corresponding database available).

How to generate the relationship between the terms for Cities in the State-County-City vocabulary with the corresponding Historical and Tourism regions, while maintaining the possibility to list all nodes/POIs in a State/County/City/Historical region/Tourism region?

I have thought about having two additional vocabularies but failed to find a way to connect them with the City terms in the first. I also thought about having multiple parent terms in one vocabulary for the Cities - but this messes up the vocabulary (and Simple Hierarchical Select) completely and is therefore inapplicable. Any help appreciated.

# Answer
> 1 votes
It's quite simple:

1. State-County-City hierarchy you have figured out
2. Create separate taxonomy for regions
3. Go to `/admin/structure/taxonomy/*/fields` and add a taxonomy field to terms in first tree. That way you will be able to assign cities, counties and states to regions

Later, you will have to switch to Views for display, as regular taxonomy pages will not be enough to display nodes by historical region - but that's for another question.

---
Tags: 7, forms, taxonomy-terms
---