# Question
Title: Programmatically find out what fieldset a field belongs to, if any
There doesn't seem to be a way to join the fieldset table in the database to a fields table, nor any function that can be used to get fieldset info by field name. Is there a way to get fieldset info starting from a single field's information (as well as bundle and such)?

# Answer
> 1 votes
If you call `field_group_info_groups` with the entity type and bundle, it will return all the field groups on the bundle, the fields should be in the children array under `['form'][YOUR_FIELDGROUP]` e.g.

```
     $fieldgroups = field_group_info_groups('node', "YOUR_NODETYPE");
     $field_names = $fieldgroups['form']['YOUR_FIELDGROUP']->children;

```

`$fieldnames` should now contain a list of all the fields that pertain to `YOUR_FIELDGROUP`. Which you can now parse through using a foreach loop.

```
     $node = node_load(2);
     foreach ($field_names as $key => $field_name) {
      $field_items = field_get_items('node', $node, $field_name);
      // Do something cool here.
     }

```

---
Tags: entities
---


title: Required autocomplete field

text:
# Question
Title: Required autocomplete field
I have an 'Entity Reference' autocomplete field populated by a view that returns all authenticated user email addresses. I have set the field to 'Required' but when I enter an email address not in the list and save the node, it doesn't trigger an error. It just makes the field blank. Is there anything I can do to force the node not to save if a valid email address has not been entered?

# Answer
You should try changing the no results message in the view, maybe have return an invalid address like a@a@a.c or something.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Purpose of the Tag field on Add View page?
Under the Tag field on the Add View Page is such note:

> Enter an optional tag for this view; it is used only to help sort views on the administrative page.

But I also noticed that when I fill this field out another template becomes available with tagname in it's name. I should say that that might be quite handy in my case, when I kinda need to narrow the hit to specific views only. Can I perhaps use this feature to granulate templates for the views?

Any other usage case for the Tag field?

# Answer
> 2 votes
To me, the tag field is handy for sites that have a lot of views.Different views have different purposes; for instance admin/editor tasks, front end pages and blocks, or as source for node reference fields. If you tag your views consistently, it's easier to find a view when you need to edit it.

# Answer
> 1 votes
Except for obvious sorting and organization purposes, Tag field is also used in views Theme Information as suggestion template. For example Views tagged with "MYTAG" will use this template - views-view-unformatted--MYTAG.tpl.php. This is very usefull when u have multiple different but similar views that u want would use same template file.

See Comments at: http://greenash.net.au/thoughts/2014/04/sharing-templates-between-multiple-drupal-views

---
Tags: views, blocks, theming
---


# Question
Title: Setup for Taxonomy throwing 404 constantly
I'm running a fresh, vanilla install of Drupal 7.27. There are absolutely no non-default modules installed with it. I was playing with the taxonomy settings to familiarize myself with the system. I have no trouble creating vocabularies, terms and hierarchies, or associating content, but editing any of my existing terms takes me out of the overlay mode, and saving the edits throws a 404 Object not Found. Further, setting urls for any of my taxonomy terms breaks the landing page for the term, giving me, for example:

```
Page not found
The requested page "/drupal-7.27/?q=/nonfiction/cookbooks" could not be found.

```

in the content area of the page.

Any ideas where I can look for the source of this error? The error log in admin reports simply tells me what I already know.

I'm new to Drupal, just hoping to get my company to migrate away from Magento, so this is all very exciting, but confusing. Thanks in advance.

# Answer
> 0 votes
Unexpected non-reachable pages you know that exist are 99% of the time a problem in the server-config.

mod\_rewrite for apache needs to be enabled and you need to make sure AllowOverride All is enabled in your virtual host for your drupaldirectory. more here: http://drupal.org/node/54832

After you have this setup right you can also enable clean-urls and lose the ?q= in your url. Set it up @ admin/config/search/clean-urls.

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


# Question
Title: How do I theme repeating dates output field?
I currently have a calendar of events and each event has multiple repeating dates. Now when i display them it shows all those repeating dates in a long list. How would i theme this to show only if there are more than 3 dates to display":

**Has multiple dates in the coming month**

I was thinking of doing this via tpl's, but what should i name my tpl as to override this output?

# Answer
You need a new custom Formatter for this. Some proposed solutions are listed below (with an order of importance):

...

You can use Devel to inspect your field structure.
> 0 votes

# Answer
Using template\_preprocess\_field seems to do the trick. You can either put this in your themes template.php or in a custom module.

```
function YOUR_THEME_preprocess_field(&$variables) {

    $most_repeating_dates_to_show = 5; // set limit of how many repeating dates is acceptable to show

    if($variables['element']['#field_name'] == 'field_date') { // Put your actual field name where it says "field_date"

        $num_repeats = count($variables['items']); // get count of how many repeating dates there are

        if($num_repeats > $most_repeating_dates_to_show) {

            $nid = $variables['element']['#object']->nid; // get the nid of the parent node

            // set the title of the link to show how many repeating dates there are
            $link_options = array(
                'attributes' => array(
                    'title' => t('See all :num repeating dates', array(':num' => $num_repeats))
                )
            );

            $link = l('Has multiple dates', 'node/'.$nid.'/repeats', $link_options);

            $variables['items'] = array(0 => array('#markup' => $link)); // here we overwrite the whole array of items so only our link will show

        }

    }

}

```

I've added a bit of extra functionality turning your text "Has multiple dates" into a link that links to the full list of repeating dates.
> 0 votes

# Answer
What i did was modify hook\_date\_display\_single() as seen below. I had it detect todays date then compare it to the repeating dates and if they are past todays date grey it out and do a strikethrough. I also had it remove the YEAR using preg\_replace(). I did that so it wouldn't show up for that specific date format. Its a quick and dirty fix, but obviously it can be polished up.

```
/**
 * Returns HTML for a date element formatted as a single date.
 */
function THEMENAME_date_display_single($variables) {
  $date = $variables['date'];
  $noyr_date = preg_replace('/\.[0-9][0-9][0-9][0-9]/', '', $variables['date']);
  $timezone = $variables['timezone'];
  $attributes = $variables['attributes'];

if(((time()-(60*60*24)) > strtotime($date)) && (strtotime($date) != 0)) {
  // Wrap the result with the attributes.
  return '<span class="date-display-single"' . drupal_attributes($attributes) . '><del>' . $noyr_date . $timezone . '</del></span>';
} else {
  return '<span class="date-display-single"' . drupal_attributes($attributes) . '>' . $noyr_date . $timezone . '</span>';
}
}

```

The output of that looks like this as compared to the original on the original question:
> 0 votes

---
Tags: 7, theming, datetime
---


# Question
Title: How to change the user profile edit page?
What is the best way to change the user profile edit page? I need to add a new field alongside the password.

# Answer
You can add new fields to the users profile page at admin/config/people/accounts/fields

You can also manipulate the form by implementing `hook_form_user_profile_form_alter(&$form, &$form_state, $form_id)` and `hook_form_user_register_form_alter(&$form, &$form_state, $form_id)`

To add new profile pages you can use the Profile 2 module.

You can also edit the user edit template by implementing hook\_theme().
> 3 votes

# Answer
In drupal 7 /admin/config/people/accounts/fields Here you can add and change certain fields for the user profile. You may want to check out the module profile2 as well: https://drupal.org/project/profile2
> 0 votes

---
Tags: users
---


title: set referenced entity programmatically

text:
# Question
Title: set referenced entity programmatically
I have a view that displays a content type "offers" for a specific "task" (content type), the "task" content type has an entity reference field that reference an "offer". The view shows the title of the "offers" and in front of each title a button "Select this offer for your task"

I want that when I click the button "Select this offer for your task" set the value of the entity reference field I have in the "task" node, for reference the offer I have selected from the view

Is this possible? Thanks for your help.

# Answer
Because you are already using Views, consider using the Rules with Rules Link module. This kind of setup could be done quite easily and even stored in a Feature so that the changes could be maintained in a git repository.
> 1 votes

---
Tags: 7, entities
---


title: How to theme a view with Zen?

text:
# Question
Title: How to theme a view with Zen?
I have a view called 'Profile' that shows some user fields on my users' profile pages. I'm using the Zen theme and I'd like to change the way these fields are displayed.

As a total newbie in theming, I don't have a clue where to start. I read a lot about template files on the internet, but I don't know if that's what I'm looking for. I'm not asking for help with the CSS code, but for the place where I should put it.

Which files should I adapt?

# Answer
> 0 votes
When you go to the view, open the advanced section - near the bottom is a link called theme: information.

This lists all the potential files you COULD adjust to tweak the output of the view. Some are very generic, and some specific to the view you are looking at - in general if you only want to theme the one view, choose a file name with your specific view name in it. Exactly which file(s) need to adjusted depends on the kind of tweaking you want to accomplish. These files (i.e. views-view-profile--page.tpl.php ) would then be placed in the theme directory (i.e. /sites/all/themes/zen) unless the theme uses a sub-directory for template files - a simple look through should tell you where they are found for each theme.

---
Tags: 7, views, theming
---


title: Migrate : Update not working

text:
# Question
Title: Migrate : Update not working
Im using the migrate module to import data from a json feed. Mostly work fine however, i require that each time the feed is imported , updated records in the source are updated in the destination if they exist.

Im struggling to find much information on this or more over explicitly how to implement this kind of functionality.

I have list my code to date and would really appreciate any input someone has on this. An example might be the same feed being imported but the aboutOurClient field updated in the source

cheers

Steve

```
class JSONMigration extends Migration {
  /**
   * A constructor
   */
  public function __construct() {

    parent::__construct(MigrateGroup::getInstance('json_migration'));

    $http_options = array();

    // define source definitions.... wont work with out this so hey ho
    $this->map = new MigrateSQLMap(
      $this->machineName,
      array(
        'jobref' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
        ),
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $fields = array(
      'jobref'                   => 'Job reference',
      'jobTitle'                 => 'Job title',
      'aboutOurClient'           => 'About the job',

    );

    $json_folder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'json_migration') . '/';
    $items_url = $json_folder . 'PEsamplejson.json';

    $this->source = new MigrateSourceList(new ExampleListJSON($items_url),
      new ExampleItemJSON($items_url, array()), $fields);

    $options = array();

    $options = array('track_changes' => 1);
    $this->destination = new MigrateDestinationNode('jsontest', $options);
    //$this->systemOfRecord = Migration::DESTINATION;

    $this->addFieldMapping('field_jobref', 'jobref');
    $this->addFieldMapping('title'       , 'jobTitle');
    $this->addFieldMapping('body'        , 'aboutOurClient');

  }

  public function prepareRow($row) {
     // i can remap/manipulate here if needs be ie date
  }

}

```

# Answer
> 0 votes
If you are using the Migrate UI, at the bottom of the page there is an Options slideout with the Update checkbox. If you are kicking off your migration programmatically then call prepareUpdate() before calling processImport().

```
migrate_static_registration(array($machine_name));
$migration = Migration::getInstance($machine_name);
$migration->prepareUpdate();
$result = $migration->processImport();

```

---
Tags: 7, migrations
---


# Question
Title: Update Webform Submission from subsequent form on confirmation page
I am trying to update a webform submission from a form on the confirmation page. My callback function is as follows, but it's not updating the submission. What is the correct syntax to accomplish this? I'm getting the webform node and the submission are loaded correctly but the webform\_submission\_update is not updating the record. What am I doing wrong?

```
$nid = 3389;
$webform = node_load(3389);
$sid = $form['sid']['#default_value'];
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submission = webform_get_submissions($nid, $sid);
$email = check_plain($form['your-email']['#value']);
$submission->data[14]['value'][0] = $email;
webform_submission_update($webform, $submission);

```

# Answer
Looks like you are you using the wrong function, rather then retrieving a single webform submission you are retrieving multiple entries.

```
$nid = 3389;
$webform = node_load(3389);
$sid = $form['sid']['#default_value'];
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submission = webform_get_submission($nid, $sid); // note function name
$email = check_plain($form['your-email']['#value']);
$submission->data[14]['value'][0] = $email;
webform_submission_update($webform, $submission);

```
> 1 votes

---
Tags: webforms
---


# Question
Title: How to change the date on which a user was created?
I'm creating users on my new website that were active on my previous website and I'd like to point this out on there profile pages by displaying the correct date in the "Active since" field.

Is there a possibility to change the user-creation date?

# Answer
You can change user creation date programmaticly with following statement:

```
$user= user_load($uid);
$user->created = '1390469581';  // Timestamp of user creation date
user_save($user);

```
> 0 votes

# Answer
Here's a link to expose the creation date for drupal 6 - someone more knowledgeable with the conversion might be able to help you change it over to 7. Otherwise, if there are not too many users, you could do it manually via database manipulation.

https://drupal.org/node/857846
> 0 votes

---
Tags: 7, users
---


title: How to create a script file

text:
# Question
Title: How to create a script file
I want to create a script file that I can call using a form on submit. For example I can use:

```
action="action.php?uid=1&method=deleteuser"

```

This would trigger the script to result in the function deleteuser in file action.php deleting uid 1. However, when I tried to create this file and put it in the home scripts folder it couldn't call basic drupal commands such as db\_query. Where and how can I generate such a script file so that I can access drupals core functions?

# Answer
> 0 votes
You can make your script file with following statements:

```
<?php
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']); // Define the DRUPAL_ROOT constant which is used in many places.
$base_url = 'http://'.$_SERVER['HTTP_HOST']; // Again, this is used in many places.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; // Include the boostrap file.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); // Start things up to whatever level you need.
//drupal_set_message('custom script');
print db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => 1))->fetchColumn();
?>

```

But it is not a good practice to handle form submit or whatever.

---
Tags: forms, external-scripts
---


# Question
Title: How to keep your Drupal 8 site synced with 8.x branch
Is it practical to both A) develop/maintain a Drupal 8 alpha site and B) keep it up to date with the latest daily/hourly commits from the 8.x branch ?

If so, what would be your strategy to keep your site up to date, while maintaining the integrity/stability of the site itself? How would you handle commits that affect the database?

My big concern is pulling in commits that affect the database structure. If the database is affected in a particular commit, I'm assuming the site could easily break.

# Answer
> 1 votes
All those comments are correct. While running Drupal 8 for a simple blog, brochureware or similar site is a good idea to test it, doing anything more is most definitely not. Upgrading any code on a production site without testing it first is a bad idea, upgrading it with code which is openly declared to be possibly broken is a spectacularly bad one.

So: build you site, upgrade locally occassionally, be ready to export your content (somehow) and reimport it into the new one (somehow). Neither of these are supported. Writing migrate sources for D8 and a CSV source and target pair would be appreciated and quite possibly would work well for this scenario. You can find me in `#drupal-migrate` on freenode IRC should you want to work on this.

---
Tags: 8, version-control
---


# Question
Title: Why 'excluded from display' fields in views are not available in template files?
There is a slide show in my website and I implemented it using `views_slideshow` module. its content type has 2 fields: 1. an address 2. and image. when user clicks on the image it must be redirected to the address.

this is views-view-fields--VIEWNAME.tpl.php

```
<?php
global $base_url;
$address = strip_tags($fields['field_site_link']->content);
$address = str_replace($base_url,'',$address);
print $address;
?>
<div>
<a href="<?php print $address;?>"><?php print     $fields['field_site_image']->content; ?></a>
</div>

```

I excluded the `field_site_link` from display but it is not available in this function. I also tested `<?php kpr($fields); ?>` and it was still unavailable. How do I can get its content?

# Answer
If you exclude any field that means you don't want to display that fields. So obviously that fiels is not avilable to any template for exclude's default behaviour. That field only available as token in views.
> 1 votes

# Answer
If you enable the field in your view you can access it through the template and control it's output using php.
> 0 votes

---
Tags: nodes, views
---


# Question
Title: Pass the value in a field into a colorbox popup
Is it possible to dynamically change a link on a colorbox popup a specific field value?

I have a view displaying a list of external links that have been added using a custom content type. And what I would like to do is be able to have a colorbox popup when you click on one of those links that explains that you are about to go to an external site.

I have the colorbox popup working with a button to go to that link, but I need the link of the colorbox button to change depending on which node they click on in the view.

My field is "field\_conf\_presentation\_link"

Can I pass that value in anyway to the link that the popup would have?

Here is my view displaying the link they would click on:

Here is the code I have on my page template file that creates the content for the popup:

```
<div style="display:none;">
<div id="gate">
  <?php print '<p>' . t('You are now being redirected to view this live session.') . '</p>'; ?>
  <?php print l('Watch Now ›', '**LINK HERE**', array('attributes' => array('class' => array('btn-small')) ) ); ?>
</div>

```

I've been looking around and see that there is a module called Colorbox Node that might be able to give me what I want, but I am hoping I can get around that for something like this.

# Answer
> 0 votes
With the help of @Citricguy I was able to find a solution to this. Turns out the feature needed is not the **load**, but the **inline** feature.

It's not the cleanest solution but using views I was able to create a custom text field that created a DIV using tokens. I then passed that DIV into the **colorbox-inline**. With that I was able to generate the dynamic link in my colorbox that I needed.

# Answer
> 0 votes
Using the Drupal Colorbox module you should be able to accomplish this.

You just need to add the class **colorbox-load** to your link and then to modify the colorbox settings per link append something like `?width=500&height=500` to the end of the path.

Colorbox Documentation

> Check the "Enable Colorbox load" option in Colorbox settings.
>
> This enables custom links that can open content in a Colorbox. Add the class "colorbox-load" to the link and build the url like this "\[path\]?width=500&height=500&iframe=true" or "\[path\]?width=500&height=500" if you don't want an iframe.
>
> If you want to pass the width and height of the Colorbox as a percentage (useful for responsive designs), you can format the link like this "\[path\]?width=90%25&height=90%25&iframe=true" or "\[path\]?width=90%25&height=90%25", where the "%25" is the HTML entity for "%".
>
> Other modules may activate this for easy Colorbox integration.
>
> Load inline content in a Colorbox
>
> Check the "Enable Colorbox inline" option in Colorbox settings.
>
> This enables custom links that can open inline content in a Colorbox. Inline in this context means some part/tag of the current page, e.g. a div. Replace "id-of-content" with the id of the tag you want to open.
>
> Add the class "colorbox-inline" to the link and build the url like this "?width=500&height=500&inline=true#id-of-content".
>
> It could e.g. look like this.
>
> Link to click What ever content you want to display in a Colorbox. Alternatively instead of style="display: none;" you could use class="element-hidden".
>
> Other modules may activate this for easy Colorbox integration.

---
Tags: 7, views, javascript
---


# Question
Title: How to access existing data in the row during Migrate?
I'm using the Migrate module to import data but I want to compare existing data in my Drupal content for one specific field before I overwrite it during an update migration.

`PrepareRow()` doesn't seem to have access to the destination data. I was hoping that `Prepare()` would as the inputs to `prepare($entity, stdclass $row)` suggest it has the entity in hand, however it appears that this entity is the fully constructed row it is about to import rather than the data from the destination object.

Is there any way I can get access to the unaltered destination row to do a comparison with my source row before the import happens?

# Answer
Answer lies in PrepareRow() method you will implement... You always have access to source where reference to destination is given.. For example if you are importing a node you will have nodeid reference.. From node id you can get destination details using node\_load api function..

Similarly for any other entity if you are updating you will have a reference in source using which you can load destination details...
> 0 votes

---
Tags: migrations
---


# Question
Title: Is it possible to define a field as disabled on creation in field_create_instance?
I have a content type that has a mix of user-editable fields and auto-populated fields (from an external source). I would like to mark those fields as disabled right when I create them so the user cannot overwrite them. I know there are readonly modules and ways to do this in hook\_form\_alter but I'm curious if I can short circuit having to do this on the fly and just have it disabled by default. Thanks.

# Answer
No, fields don't have a 'disabled' setting by default.

You could however use `hook_field_access` to restrict access to editing them

```
/**
 * Implements hook_field_access
 */
function MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  // Define read only fields
  $readonly = array('field_my_field_1', 'field_my_field_2');
  if ($op == 'edit' && in_array($field['field_name'], $readonly)) {
    // Disable edit.
    return FALSE;
  }
  return TRUE;
}

```
> 0 votes

# Answer
If you want a non-code way, would https://drupal.org/project/field\_permissions not help? It would remove them from the edit screen and then only display them in the display field.

The only issue is whether fiel permissions will let you complete the value using an external source. But if that works okay then it would save some coding.
> 0 votes

# Answer
I believe you can able to do it while defining them using field\_create\_instance .. If you see the documentation..

> settings: each omitted setting is given the default value specified in hook\_field\_info().

You can define settings saying disabled =\> TRUE

```
'settings' => array('disabled' => TRUE),

```
> 0 votes

---
Tags: entities
---


# Question
Title: Unknown directories /pipermail /poll accessible in Drupal 7
My Drupal 7 install, has the Simplenews and Polls modules enabled, but Simplenews is set to subscribe registered members only, and Polls are only open to authenticated users. Yet, the mysite.com/pipermail and mysite.com/poll directories are accessible to anonymous view.

The mysite.com/poll directory returns a page with the Drupal theme only, and the word "Polls" in the page title, and no other data. The mysite.com/pipermail directory returns a blank page, absolutely no data.

These directories are not seen anywhere in the directory tree when I checked using File Manager in cPanel. This is a CentOS 5.10, php 5.4 install. How does one check Drupal's internal directory tree, especially to verify whether the permissions are correctly set on these unknown directories?

How do I remove these problematic directories? Also, is it possible that this flaw can be maliciously attacked, say by ftp upload means, etc.?

# Answer
> 0 votes
Drupal is a Dynamic Content Management system unlike old style files and directories where you find path specific directory.. Various features are available from modules in Drupal... Modules implements menu paths using hook\_menu...

For your case, module exposes permissions settings which you can set in "admin/people/permissions" for different roles... Login as admin and access above page to set access permissions..

---
Tags: polls, files
---


# Question
Title: How to compute fields from different content types and then show the result in Views table
Is there a way to compute fields from different content types then display the result in Views table?

I will use those fields in a given formula.

# Answer
> 0 votes
Ya definitely,

Include those fields in views, Take another field **Global: Custom text** OR **Global: Math expression** and that's field setting text or expression, use previous field value as a token as per your formula. Make sure this field will be below the all other field that you will use in formula. You may exclude the fields that you use in formula if not want to display.

---
Tags: views
---


# Question
Title: Is it possible to create a List field without requiring Allowed Values?
It there any way to create a List field that doesn't require an Allowed Values list? I'm looking for a free form list, which users can typing values in or I can programmatically add values without the requirement of them having to be in an Allowed Values list.

I'm looking for something a bit more sophisticated than a delimited textarea field so that suggestion doesn't apply here. I want the functionality of a List field but not the requirement of the Allowed Values validation.

# Answer
You can use Select (or other) module for this.

Project pays says:

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

You may also try CCK Select Other
> 0 votes

---
Tags: entities
---


title: First order ID different from 1

text:
# Question
Title: First order ID different from 1
I am using Commerce Kickstart, and I want to use as order ID any desire number, where by default the first order ID is 1.

How can I achieve this?

# Answer
> 0 votes
I saw a similar post.

Just a quick behind-the-scenes tidbit here: Drupal Commerce separates out its internal Order ID from what you see on the front end as the Order number. The Order ID is a serial numeric value that increments with each order created (including orders that are still shopping carts). The Order number can be any alphanumeric string, but it initialises to be the same as the Order ID. (Some sites then update orders upon creation to use a special alphanumeric order number format instead of the regular integer format.)

What you want to change is the AUTO\_INCREMENT value on the commerce\_order table. This will make it so the next created Order ID will start with the increased AUTO\_INCREMENT value. By default when you create a new site, this will be set to 1, but feel free to set it as high as you need it to go. This is especially important if you're migrating an old site but using the same payment gateway, as they sometimes don't support the same order number being used twice.

The query to update this is:

```
ALTER TABLE  `commerce_order` AUTO_INCREMENT = 1000;

```

Where 1000 is replaced by whatever number you need the next created order to start at. This won't affect any existing order, just the next order to be saved to the database.

---
Tags: commerce
---


# Question
Title: User List of user roles in List field af a content type
I would like to add a new field type in my content type. The field is of the type List(Text) and the possible values should be the list of user roles in the system. Is there a way to do it without creating a custom field type?

# Answer
> 1 votes
You can try using Role Field module..

Project page says

> Role Field provides a field for selecting roles that exist in your site.
>
> Please note that there is no out-of-the-box permissions shenanigans going on. It just lets you pick from a list of roles. Although, combined with Rules the possibilities are pretty interesting.

---
Tags: nodes, entities
---


# Question
Title: How to I call a preprocess function for a view from a custom module?
Lets say I have a view called `widgets`.

On a given page, `/widgets/manage/` I want to add use a function that calls `drupal_add_js` and `drupal_add_css` to change the behaviour and appearance.

If I wanted to make a change to the widget view in a theme, I'd change this file:

```
views-view--widgets--page.tpl.php

```

But, I want to change this in a module, so I can easily switch a feature on when I enable a module.

I don't need to add any other template files, I just want to call a few functions in PHP.

What is the best way to do this, and what would be the relevant hook to use here?

# Answer
> 1 votes
A template preprocess hook would be the best place. The naming convention for those functions is standard so you should be able to use

```
function MYMODULE_preprocess_views_view__widgets__page(&$vars) {
  drupal_add_js('...');
  drupal_add_css('...');
}

```

# Answer
> 0 votes
In order to make a Views preprocess hook to work in a custom module, you should first kind of register it using mymodule\_preprocess\_views\_view().

In mymodule.module file, add the following:

```
//Register your hook here
function mymodule_preprocess_views_view(&$vars)
{
    if (isset($vars['view']->name))
    {
      $function = 'mymodule_preprocess_views_view__'.$vars['view']->name;
      if (function_exists($function))
      {
        $function($vars);
      }
    }
}

//Preprocess hook for widgets-page view
function mymodule_preprocess_views_view__widgets__page(&$variables)
{
  $view = $variables['view'];
 //do your stuff here
}

```

---
Tags: views, theming
---


title: Change structure of block content

text:
# Question
Title: Change structure of block content
I have a block like this:

```
<section id="block-locale-language" class="block block-locale clearfix" data-thmr="thmr_23">
  <h2 class="block-title">Languages</h2>
  <ul class="language-switcher-locale-url" data-thmr="thmr_8"><li class="nl first"><a href="/nl/user/1" class="language-link" lang="nl" data-thmr="thmr_9">Nederlands</a></li>
      <li class="en active"><a href="/user/1" class="language-link active" lang="en" data-thmr="thmr_10">English</a></li>
      <li class="fr last"><a href="/fr/user/1" class="language-link" lang="fr" data-thmr="thmr_11">Français</a></li>
  </ul>
</section>

```

But what I want is this:

```
<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Action <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li class="divider"></li>
    <li><a href="#">Separated link</a></li>
  </ul>
</div>

```

I've overwritten the locale block like this: (block--locale.tpl.php)

```
<div class="btn-group languageswitch">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        LANGUAGE <span class="caret"></span>
    </button>
    <?php print $content; ?>
</div>

```

But I need to change the structure in the $content variable, how can I do this?

UPDATE:

In my locale module (in /modules) I've found this:

```
function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

```

As you can see they add a class `language-switcher-{$links->provider}`. Now I would like to add some more classes to that.

How can I do this now in my subtheme template.php? It's like my function `locale_block_view_alter` isn't called for some reason. I already tried with a var\_dump but no result in my browser ...

# Answer
If you are not in control of the initial building of the content then `hook_block_view_alter()` can alter the content of any block before it is rendered.

**From the API page:**

*Perform alterations to the content of a block.*

*This hook allows you to modify any data returned by `hook_block_view().`*

---

**To target a specific block...**

In `hook_block_info()`, each block your module provides is given a unique identifier referred to as "delta" (the array key in the return value). Delta values only need to be unique within your module.

The variable $block is passed into `hook_block_view_alter()`. This variable is defined as:

**$block:** The block object, as loaded from the database, having the main properties:

* **module**: The name of the module that defined the block.
* **delta**: The unique identifier for the block within that module, as defined in hook\_block\_info().

So you can check what the module and delta of the block to target specific blocks.
> 1 votes

# Answer
You might want to look at targetting the THEME\_item\_list instead of the locale module. I had the exact problem but since my issue was targetting a menu I could use hook\_menu\_tree to add the classes.
> 0 votes

---
Tags: blocks, nodes, theming
---


# Question
Title: Drupal 7 Migration - redirect old dynamic urls to new domain name
I just cloned a drupal 7 site to another domain name. Now i want to only redirect some of the URLS from the old site to the new site. Problem is that I have many (300+) dynamically generated URLs via views. Most likely I will have to do this via .htaccess modrewrites doing a 301 redirect. Basically I want to do is this:

**Site #1:**

abc.com/products/shoe

abc.com/products/shoe/blue

abc.com/products/shirt/neon

**Site #2:**

xyz.com/products/shoe

xyz.com/products/shoe/blue

xyz.com/products/shirt/neon

-- Where would I create this modrewrite in the .htaccess file? on the bottom or do I have to edit anything else? also would it affect anything else?

# Answer
There are three ways to tackle this.

1. You can make the mod\_rewrite rules in you Apache configuration. The benefit of this is that you can keep your Drupal .htaccess stock, so you don't need to worry about losing changes when you update core. How/where this goes depends on you have Apache configured. On my servers, I use virtual hosts, so I add a `<IfModule mod_rewrite.c>` inside the `<Directory>` section.
2. You can edit the stock .htaccess that comes with Drupal. You need to add them above the main rewrite that punts to index.php, which starts on line 112 in Drupal 7.x HEAD. When you do this, you need to make sure you back up and restore this file when you update core (or track in RCS and merge changes).
3. You can use a combination of the Pathologic and Redirect modules. Pathologic will set up rules that rewrite URLs in your content when they get rendered out. Redirect can set up 301/302 redirects for inbound requests.

Of the three choices, I try to avoid #2. I manage a lot of sites, and I don't want to keep track of which have custom .htaccess files.

Between #3 and #1, I tend to prefer #3 because I can have someone else manage this process via the UI. However, if I have a lot of URLs with common patterns, or for simple domain redirections, I will use #1. Typically, I end up using a combination of #1 and #3.
> 1 votes

---
Tags: 7, migrations, .htaccess
---


title: Merging view displays into same view

text:
# Question
Title: Merging view displays into same view
I've got a view with 5 complex view displays (4 pages and 1 feed).

I've also got another view with 7 even more complex view displays which where automatically generated from the `calendar` module.

Is it possible to merge those 2 view displays into the same view? Or alternativelly execute `Add view from template` within an existing view. So the 7 `calendar` view displays ends up appended in the view which already contains my 5 custom view displays.

What I've tried so far:

* `Add view from template` in a new view and replicate/recreate by hand my custom 5 displays
* export the 2 views with `features` and try to merge the code so I can "features revert" to a single view

Is there a better way?

# Answer
> 1 votes
Your 2nd approach may be more trouble than it's worth, unless this is a learning exercise. As far as other options go, can't think of any, you may have to just recreate your displays.

# Answer
> 0 votes
This seems to work:

Simply cut/paste the display code from the views export of the first view and past it in to the 2nd view.

Make sure to change the display machine name if it overlaps with any of the display machine names in the 2nd view (example page\_1).

Import this new, combined view.

---
Tags: 7, views
---


title: db_add_field not working

text:
# Question
Title: db_add_field not working
I want to add a new field to `node` table using db\_add\_field when intalling a new module, but it seems there is something wrong or missing:

here is the code used:

```
/**
* Implements hook_schema_alter()
*/
function smart_delete_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['node']['fields']['show_in_inbox'] = array(
    'type' => 'int',
    'length' => '4',
    'default' => '1',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by Smart_delete module',
  );
}

/**
* Implements hook_install()
*/
function smart_delete_install(){
    if (!db_field_exists('node', 'show_in_inbox')) {
        $schema = drupal_get_schema('node');
        db_add_field('node', 'show_in_inbox', $schema['fields']['show_in_inbox']);
    }
}

```

**ADD :**

I made an db\_query in `hook_init()` inside .module file :

```
$result = db_query("ALTER TABLE `node` ADD `show_in_inbox` TINYINT NOT NULL DEFAULT '1';");

```

this is working, but the same db\_query in .install file is not working when disable/enable the module again!

(I cleared the cache, also add the file in .info file)

# Answer
I don't think `length` is valid for integers. `size` is though:

```
$schema['node']['fields']['show_in_inbox'] = array(
  'type' => 'int',
  'size' => 'tiny',
  'default' => '1',
  'not null' => TRUE,
  'unsigned' => TRUE,
  'description' => 'Field added by Smart_delete module',
);

```

Data Types
> 1 votes

---
Tags: 7, database
---


# Question
Title: Disable sticky table headers for field collection?
I'm using a field collection on my node form and sticky table headers comes baked in with no way to disable it (that I can find, anyway). How do I disable sticky table headers? Preferably with Javascript or CSS... sadly, I'm using an instance of Drupal 7 that has a lot of the internals hidden from me.

# Answer
One line of CSS will do it:

```
table.sticky-header { display: none !important; }

```

Answer found here.
> 2 votes

# Answer
Just chiming in here since I came across this page while searching for a solution and wanted to demonstrate the alternative to a CSS override.

If you want to remove this at the theme level — where arguably it should be — you'll want to look at `theme_field_multiple_value_form`.

That function calls `theme('table'... w/out sending the 'sticky' => FALSE value)` see `theme_table`.

If you override that function and set `'sticky' => FALSE`, then the code that initialized the sticky header will be ignored.

If you want to only override this for a certain field, just reference the `$variables['element']['#field_name']` value.
> 1 votes

---
Tags: entities, theming
---


# Question
Title: How do I make my homepage slideshow to fit the page width?
I have my website built in Drupal 6, and I have used the Views slideshow module for the home page banner which is 960 pixel wide. I need a banner with 100% width to fit the page. Can anybody help me in making it to 100% or kindly suggest any full width banner slideshow module which is compatible with Drupal 6?

# Answer
Is your website wider than 960px ? ... I have you looked at online CSS tutorials such as Full Screen Background Image Pure CSS Code, or CSS3 cover property for background-images as mentioned here. I think the CSS Only Technique #1 is more what your looking for in your slideshow's inline images.

Anyways, Google will help you alot here. Views Slideshow ships with basic *useable* CSS, but it's not themed for everyones needs. It's up to you to tweak its CSS as you need. As an example I've previously given here -- taking a Views slideshow and using only css + jquery and changing it to meet client needs.

Sorry I dont know of a module that just does all the themeing for you, views slideshow does do 99% of the work for you by providing a workable slideshow for your site.
> 1 votes

# Answer
Set the container's width to 100%, remove the maximum width, then set the width of `.views-field-field-slideshow-image img` to 100%.
> 1 votes

---
Tags: theming, 6, media
---


# Question
Title: Best way to inform users after file upload
I'm searching for a good solution to inform users after a file was uploaded (with standard upload URL: `...file/add`).

I would solve this with rules, but I can't find the right events for this.
Has anybody a good idea.

# Answer
Have you checked out the Entity Rules module? I believe this is exactly what that module is for.

I did a brief check and you can create a reaction rule on a Create Entity action and then check the type of that entity.
> 0 votes

---
Tags: notifications
---


# Question
Title: Difference between hook_node_view() and template_preprocess_node() with seeing messages
When I add a form to a node's render tree using `hook_node_view()`, eg

```
<?php

/**
* Implements hook_node_view().
*/
function MODULE_node_view($node, $view_mode, $langcode){
  if ($node->nid == 9 && module_exists('contact')) {
    module_load_include('inc', 'contact', 'contact.pages');
    $cForm = drupal_get_form('contact_site_form');
    //$cForm['#action'] .= '?destination=' .    request_path();
    $node->content['contact_form'] = array(
    '#markup' => drupal_render($cForm),
    '#weight' => 20,
    );
  }
}

```

then I get my messages displayed right after the submission.

I do the same thing with `template_preprocess_node()`, the messages are displayed one request after the submission.

I suspect this is related to the execution order. Can someone shed some light on the difference here?

# Answer
> 1 votes
It is indeed related to execution order and how messages are handled by the theme layer.

The `$messages` variable (which contains system messages) is processed and output at the page level (page.tpl.php) which occurs before node (node.tpl.php). So by the time you invoke `drupal_get_form()` from your node preprocessor, `$messages` has already been set up.

So, although `$_SESSION['messages']` has been populated with the validation errors via `drupal_get_form()`, these won't appear until a page refresh.

`hook_node_view()`, on the other hand, is outside the theme layer and is invoked even before page processing begins, which is why it works. But if you want to make the change at the theme level, a workaround is to set up the messages manually after you call `drupal_get_form()` in `template_preprocess_node()`:

```
$contact_form = drupal_get_form('contact_site_form');
$contact_form['#prefix'] = theme('set_messages');

```

Thanks to rémy for originally pointing out the problem on our site.

# Answer
> 2 votes
It is the execution order. `hook_node_view()` acts on the node object as it is being assembled. When `template_preprocess_node()` is called, the node is ready to be rendered. For instance you may use `template_preprocess_node()` to change the date format.

---
Tags: 7, forms, status-messages
---


# Question
Title: Drupal 7 site crashed after enabling module - No DB backup. What do?
I enabled the blog module on a website, after that the site crashed. The error is the same on everypage:

> Catchable fatal error: Argument 2 passed to entity\_views\_field\_definition() must be an array, null given, called in /homez.653/xxxxxxxxx/www/sites/all/modules/entity/views/entity.views.inc on line 152 and defined in /homez.653/xxxxxxxxx/www/sites/all/modules/entity/views/entity.views.inc on line 175

Problem is that I don't have any backyp of the DB......

Any any idea on what should I do?

Thanks you per advance.

# Answer
> 1 votes
The mention of "I do not have a backup of the DB" in the question/title makes it clear that you want to roll-back the change as opposed to debugging and making the modules work where it is - for that, you do not need a backup, but access to the code and logs.

Another way to bypass the blog module, an alternative to what @Jimajamma said is to remove the module from the filesystem. Remember to clear the cache and ideally rebuilt the module registry after these steps.

```
drush cc all --yes;
drush rr;

```

---
Tags: 7, database, debugging
---


title: drush partially working

text:
# Question
Title: drush partially working
I have been running drush successfully for more than a year. Now running some drush commands such as "drush pml" or "drush up" I suddenly get the well known error:

> Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
>
> The drush command 'pml' could not be executed. Drush was not able to start (bootstrap) the Drupal database.

Usually one gets this error when running drush command in a directory higher than to site's root directory. But in my case I am indeed inside de site's root directory and I still get the error. Besides I also have an .aliases.drushrc.php file which has been working all along and that drush actually takes into account drush st gives:

```
  Drupal version    : 7.23
  Site URI          : http://default
  Database driver   : mysql
  Database hostname : localhost
  Database username : mydatabase_dru1
  Database name     : mydatabase_dru1
  Default theme     : garland
  Administration theme: garland
  PHP configuration : /Users/me/.drush/php.ini /Users/me/.drush/php.ini
  Drush version     : 5.8
  Drush configuration:
  Drush alias files : /Users/me/.drush/mysite.aliases.drushrc.php
  Drupal root       : /Applications/XAMPP/xamppfiles/htdocs/kl-local
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

```

The problem is also not due to running in a jailed shell because invoking mysql in a shell returns:

> Welcome to the MySQL monitor. Commands end with ; or \g.
>
> Your MySQL connection id is 736
>
> Server version: 5.1.44 Source distribution

Also invoking drush sql-cli in a shell returns:

> Welcome to the MySQL monitor. Commands end with ; or \g.
>
> Your MySQL connection id is 735
>
> Server version: 5.1.44 Source distribution

Also drush rsync and drush sql-sync do work! I can get my remote site synced to my local one.

One error I have noticed is that locally drush st returns the *wrong* theme names. it returns:

> Default theme : garland
> Administration theme : garland

instead of

> Default theme : bootstrap\_subtheme
> Administration theme : seven

Also when I ssh to my remote rsynced sql-synced site then the version of drush installed on that remote site works normally.

Even odder, when I run my local drush version on both my local site and my remote (synced) site, drush works on the remote but not locally. for instance from my local machine:

drush @mysite.local up returns:

> bash-3.2$ drush @mysite.local up drush @mysite.local up Command pm-update needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run this command. \[error\] Command pm-update needs the following modules installed/enabled to run: update. \[error\] The drush command 'up' could not be executed. \[error\] Drush was not able to start (bootstrap) the Drupal database. \[error\] Hint: This error often occurs when Drush is trying to bootstrap a site that has not been installed or does not have a configured database.

```
 Drush was attempting to connect to :   Drupal version    : 7.23   Site
 URI               : http://default   Database driver   : mysql   Database
 hostname          : localhost
 Database username : mydatabase_dru1
 Database name     : mydatabase_dru1
 Default theme     : garland
 Administration theme: garland
  PHP configuration : /Users/me/.drush/php.ini /Users/me/.drush/php.ini
 Drush  version     : 5.3
 Drush configuration:
 Drush alias files : /Users/me/.drush/mysite.aliases.drushrc.php
 Drupal root       : /Applications/XAMPP/xamppfiles/htdocs/mysite-local
 Site path         : sites/default
 Modules path      : sites/all/modules
 Themes path       : sites/all/themes
 File directory path: sites/default/files   %paths

 You can select another site with a working database setup by specifying the URI to use with
 the --uri parameter on the command line or $options['uri'] in your drushrc.php file.

```

But drush @mysite.remote up (for my remote synced site) actually starts the update process.

I get the same behaviors whether I run drush 5.3 or drush 5.8 on os x10.8.5

One thing I am wondering is if the line:

> PHP configuration : /Users/me/.drush/php.ini /Users/me/.drush/php.ini

does not indicate a problem somehow.

Also I have php 5.3.27 (cli) installed on my local system and XAMMP (which is serving my site) is using its own version 5.3.1 could that introduce some conflicts?

My remote server runs php 5.2.21

Any idea where the problem could be originated from?

# Answer
> 2 votes
The problem was due to a PHP conflict. Drush was using the OS X installed PHP instead of the XAMPP one. Adding the following line in my .profile fixed the problem.

```
export DRUSH_PHP='/Applications/XAMPP/xamppfiles/bin/php'

```

# Answer
> 0 votes
Ran into the same problem here. I use MAMP on Mac OS X Mavericks. I used this path in my .profile file

```
export DRUSH_PHP='/Applications/MAMP/bin/php/php5.5.10/bin/php'

```

For those who don't know where the .profile is located, it's at /Users/yourname/ (run ls -a to see hidden files).

---
Tags: drush
---


# Question
Title: Display submitted data using a select field option - webform module
I'm new to Drupal. I have a form that I created using Webform Module, is there a way to pull data submitted by Webform and group it by a column. To display result in a view

# Answer
Hi this topic should help you out. https://drupal.org/node/1658784 I used it when i needed to achieve the same thing.
> 0 votes

---
Tags: webforms, forms
---


title: URL alias error

text:
# Question
Title: URL alias error
I want to configure the URL alias patterns on my site. When I try visiting the `http://localhost/mysite/admin/config/search/path/patterns,` I get an error saying "The website encountered an unexpected error. Please try again later." All other paths work fine with the exception of the above. Any ideas on what could possibly be the course?

# Answer
Usually this is due to the php memory being set too low.

Instead of increasing for the entire site, you could target the specific page by adding this to the settings.php file in your sites folder.

if (isset($\_GET\['q'\]) && strpos($\_GET\['q'\], 'admin/config/search/path/patterns') === 0) { ini\_set('memory\_limit', '512M'); }
> 1 votes

---
Tags: path-aliases
---


title: Taxonomy term View Customization

text:
# Question
Title: Taxonomy term View Customization
on a website I'm working this period i have this problem with Taxonomy term View: My scenario is like this : I've created a vocabulary with terms and sub-terms for my products categories. So for example there is a structure like this:

First Category: Computing--\>Laptops (Apple, Acer, Dell)--\> Desktops (CPU, RAM, Hard Drives, VGA)--\> Servers (HP, Dell, Cisco, IBM)

Second Category:Peripherals--\> Monitors (Samsung, LG,Dell, Asus)--\>Keyboards (Logitech, Microsoft)--\> Printers (Epson, HP, Samsung)

I'm using taxonomy term view to make the taxonomy term page to show the products in a grid using fields. Everything works fine, when i click for example on Dell i see XPS14, XPS14Z, XPS15 etc in a grid format with a thumbnail picture and the title below it. (I' created a field for thumbnail for every product).

What i want to do is when i click on Computing for example, to show only Laptops, Desktops and Servers with a thumbnail for each one and not all the products for Computing term ( Apple,Acer,Dell,CPU,RAM,Hard Drives...etc) as it happens now. I've tried to put some contextual filters from the view but i didn't figured out how to accomplish it yet.

# Answer
So I finally find the solution.

Step 1, I added an image field for thumbnails to my taxonomy vocabulary and uploaded thumbnail image to each term.

Step 2, I created a new view showing taxonomy terms with these settings: Title: %1, Path : taxonomy/term/%, Format:Grid, Show :Fields (Taxonomy thumbnail image, Taxonomy Name), Contextual Filters: Taxonomy term: Parent term (When the filter value is NOT in the URL--\> Provide default value --\>Taxonomy term ID from URL and checked "Load default filter from term page ").

Step 3 I enable default taxonomy term view i made these changes : Title: %1, Path : taxonomy/term/%, Format: Grid, Show: Fields (Title, Thumbnail), Contextual Filters: Content: Has taxonomy term ID (with depth)(Depth: -1), No results behavior: Global: View area(View to insert : The view created in Step 1)).

And that's it.

(Felix thanks for the inspiration)
> 0 votes

# Answer
I'm assuming you are using the "Taxonomy term" view that comes with drupal.

Edit that view and:

1. Edit the contextual filter for "Content: Has taxonomy term ID (with depth)"
2. Set the depth option as high as you need to cover the number of levels in your vocabulary.
> 2 votes

# Answer
I think the solution here is going to be to use the pre-made taxonomy term pages to list the products, but use custom views to list categories.

If you make a new view that shows taxonomy terms from the computing vocabulary, and then add a filter so that parent term = 0 then it will list Laptops, Desktops, Servers. When these titles are clicked then they will link to the normal taxonomy term listing page.
> 0 votes

---
Tags: taxonomy-terms
---


title: Customising user profile tabs

text:
# Question
Title: Customising user profile tabs
I've customised the user profile tabs to look like a dashboard by using the generated classes and styling them using just CSS. Just to be clear, I haven't used any hooks or preprocesses to render the tabs, these are the default tabs that appear on the user profile.

I'm really pleased with the result! It all works fine and there's no bugs whatsoever as i've done it all through **CSS:**.

```
.logged-in.page-user {
  .dashboard-navigation {
    @include at-breakpoint($medium) {
      width: 20%;
      float: left;
    }
    section {
      padding: 0;
      margin: 0;
      max-width: 100%;
    }
    ul {
      padding: 0;
      margin: 0;
      border: 0;
      li {
        a {
          background: $lightgray;
          color: $darkgray;
          margin: 0;
          border: 0;
          text-transform: capitalize;
          display: inline;
          width: 50%;
          float: left;
          padding: .5em;
          color: $drupal;
          &.active {
            border-left: 3px solid $drupal;
            background: $white;
            &:after {
              content: "›";
              font-size: 2em;
              line-height: 0;
              float: right;
              margin-top: .25em;
            }
          }
          &:hover {
            background: $drupal;
            color: $white;
            &:after {
              content: "›";
              font-size: 2em;
              line-height: 0;
              float: right;
              margin-top: .25em;
            }
          }
        }
        @include at-breakpoint($medium) {
          display: block;
          overflow: hidden;
          a {
            padding: 1em 1em;
            text-align: left;
            display: inline-block;
            width: 100%;
            float: none;
            background: $lightgray;
            color: $darkgray;
            &:hover {
              background: lighten($gray, 10%);
            }
            &.active {
              background: $orange;
              color: $white;
              border: 0;
            }
          }
        }
      }
    }
    .secondary {
      clear: both;
      overflow: hidden;
      li {
        padding: 0;
        border: 0;
        a {
          background: $drupal;
          color: $white;
          &:hover {
            background: lighten($drupal, 10%);
          }
          &.active {
            color: $drupal;
            @include at-breakpoint($medium) {
              color: $white;
            }
          }
          &:after {
            margin-top: .3em;
          }
        }
      }
    }
  }

  .main-content {
    @include at-breakpoint($medium) {
      width: 80%;
      float: left;
    }
  }
}

```

Here's what i've come up with:

I'd like to take it a step further and add icons to each tab if possible like this:

I wasn't able to target the tabs using CSS as they all have general classes or non at all + obviously the tabs that appear depend on the role so I can't target them using pseudo nth-of-type selectors.

Maybe the solution is to add more specific classes but i'm open to ideas and some help on how I should go about it.

# Answer
> 0 votes
Too long for a comment...

Ok - add this to your themes template.php (or create one if it doesn't exist) - it is a modification of the core function.

```
function theme_menu_local_task($variables)   /* change 'theme' as appropriate to your theme name */
{
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
   if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
   $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  /* this is where the conditional addition of new classes starts. in this case, it is looking for both user and relationships
  *  in the href (i.e.  user/42/relationships ) - make sure this is unique enough not to be triggered elsewhere. You can use
  *  as many checks as you want or alter this appropriately, depending on the directory structure you have set up.
  *  the double == are not a typo
  *  it adds a class 'relationships' to the end of the classes of the <a> tag if both strings are found
  *  You can cycle through other permutations for different links.
  *  don't forget to setup the classes in the css file afterwards.
  */
  if( strpos($link['href'], 'user') !== false && strpos($link['href'], 'relationships') !== false)
  {
    $link['localized_options']['attributes']['class'][] = 'relationships';
  }
 //  else if(strpos($link...)
 //  {
//  }

return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
}

```

# Answer
> 0 votes
If the final addresses are known to be static, you could use destination specific information to identify each link

http://css-tricks.com/snippets/css/style-links-depending-on-destination/

If they include nodes of random values though, this might not work unless you can force the paths for the nodes to be predictable.

---
Tags: theming, routes
---


title: URL and GUID values from Feed import

text:
# Question
Title: URL and GUID values from Feed import
When you import RSS items via Feeds, where are the URL and GUID target values stored in the node? How do you get these out? I am not seeing anything close to these when I dump the `$node`.

This shows the **Mappings** screen with the values that I am talking about:

# Answer
> 6 votes
They are stored in the feeds\_item table in the database. They are used by the feeds module to control updates of imported items.

# Answer
> 2 votes
Use `feeds_item_info_load()` to get the feed item object, eg:

```
$fii = feeds_item_info_load('node', $node->nid);

```

# Answer
> 0 votes
I had the same problem .. I use a db\_query to retrieve the source

if you need to load information from feed\_items then use feeds\_item\_info\_load. However I need to load the source URL, and so far I havent found anything to do that. With the dbase query below you can retrieve the source feed.

```
$key = 'www.somefeed.com';
$result = db_query('SELECT feed_nid from feeds_source where source = :source', array(':source'=>$key ));

foreach ($result as $record) {
    $feed_nid[] = $record;
    }

```

---
Tags: 7, feeds
---


# Question
Title: Create an Action on 'node_insert' or 'node_presave'
I created a new action on a new node being created, it shows up in my triggers and the action gets triggered. Works so far. Problem is trying to add additional functionality using some submitted field values. As of now, all its doing is logging in Watchdog. My goal is to be able to set a flag on the node based on certain values.

## ------------------------------------------------------------------

```
/**
 *  Implementation of hook_action_info().
 */

function my_custom_action_info() {
  return array(
    'my_custom_action' => array(
  'type' => 'node',
  'bundles' => array('article'),
  'label' => t('Check article for stuff'),
  'configurable' => FALSE,
  'triggers' => array('node_insert'),
    ),
  );
}

function my_custom_action($node) {
    $myvar = $node->nid;
    my_custom($myvar);
}

function my_custom($myvar) {
    watchdog('Test', 'My Custom Variable: ' . $myvar);
}

```

## --------------------------------------------------------------------------

If I set the variable to an integer or text, it works. But how to get any value from the submitted node? Eventually I'd like to get a value from a specific field, but for now just testing with the Node ID and can't seem to get it.

The error I'm getting is : "Notice: Trying to get property of non-object in my\_custom\_action() ... "

This part: $myvar = $node-\>nid;

# Answer
yeah,

for some reason, my variable needed to be initiated first.

```
$myvar = 0;
$myvar = $node->nid;

```

that's it. works now. Problem/solution applies for Drupal 6 or 7.
> 0 votes

---
Tags: 7, nodes, actions
---


# Question
Title: Need to hide a field for the node author
For a particular content type education i need a field to be hidden for the node author. It works in the template file but not with preprocess. This is my code

```
 function aapka_preprocess_node(&$variables){
     $node = $variables['node'];
     if ($node->type == 'education'){
     if ($node->uid == $user->uid && $user->uid != 1) {
 unset($variables['content']['field_college']);}
  }

```

What am i doing wrong??

# Answer
> 0 votes
You are referencing $user without bringing it into scope.

e.g using your current approach you could do this:

```
function aapka_preprocess_node(&$variables){
  // Bring global user object into scope
  global $user;
  // Assign by reference
  $node =& $variables['node'];
  if ($node->type == 'education'){
    if ($node->uid == $user->uid && $user->uid != 1) {
      unset($variables['content']['field_college']);
    }
  }
}

```

Keep in mind that won't work if the node is cached and the cache doesn't vary between the author and other regular registered users.

---
Tags: nodes, theming
---


# Question
Title: How to set Exposed filters in fieldset for specific Views?
I found an article that can collapse exposed filters into fieldset. But this will change all Views. How can I set below code for specific Views only? For example, I wanna use this on ViewsA only.

```
<?php
/**
 * hook_preprocess_views_view
 */
function YOUR_MODULE_NAME_preprocess_views_view(&$vars) {
  // Wrap exposed filters in a fieldset.
  if ($vars['exposed']) {
    drupal_add_js('misc/form.js');
    drupal_add_js('misc/collapse.js');
    // Default collapsed
    $collapsed = TRUE;
    $class = array('collapsible', 'collapsed');
    if (count($_GET) > 1){
      // assume other get vars are exposed filters, so expand fieldset
      // to show applied filters
      $collapsed = FALSE;
      $class = array('collapsible');
    }
    $fieldset['element'] = array(
      '#title' => t('Filter'),
      '#collapsible' => TRUE,
      '#collapsed' => $collapsed,
      '#attributes' => array('class' => $class),
      '#children' => $vars['exposed'],
    );
    $vars['exposed'] = theme('fieldset', $fieldset);
  }
}
?>

```

# Answer
> 0 votes
This code will work for specific view. Example for "ViewsA"(reaplce ViewsA for your Views name and "my\_module" for your module name).

```
<?php
    /**
     * Implements hook_preprocess_views_view().
     */
    function my_module_preprocess_views_view(&$vars) {
     // Assign to your specific view.
      if ($vars['view']->name === 'ViewsA') {
        // Wrap exposed filters in a fieldset.
        if ($vars['exposed']) {
          drupal_add_js('misc/form.js');
          drupal_add_js('misc/collapse.js');
          // Default collapsed
          $collapsed = TRUE;
          $class = array('collapsible', 'collapsed');
          if (count($_GET) > 1){
            // assume other get vars are exposed filters, so expand fieldset
            // to show applied filters
            $collapsed = FALSE;
            $class = array('collapsible');
          }
          $fieldset['element'] = array(
            '#title' => t('Filter'),
            '#collapsible' => TRUE,
            '#collapsed' => $collapsed,
            '#attributes' => array('class' => $class),
            '#children' => $vars['exposed'],
          );
          $vars['exposed'] = theme('fieldset', $fieldset);
        }
      }
    }
?>

```

---
Tags: views, forms
---


title: Embedding images in a block from url

text:
# Question
Title: Embedding images in a block from url
How do I embed a URL in a block which is displayed as the linked image on the site?

# Answer
For any source or path of any thing in drupal site use src like this. It will work everywhere.

```
<?php $src = base_path() .'sites/files/logo.png'; ?>

```

This src use like

```
<img alt="logo" src=" <?php echo $src ; ?>">

```

Enable PHP filter module that come with core module.

and in Block Body Choose Text format as PHP CODE.

I assuming block is created using Block module(Block UI)
> 0 votes

# Answer
I found the answer - rather easy really.... the module Image Block solves the whole problem for those of you who might see this post asking yourself the same question!

EDIT The module simply creates an image block as said - it adds a "Add image block" to the block admin page. On the page you can choose to upload a picture - so you simply have to download the image from the URL and upload it in the block. Hence it does not exactly solve the problem but this is a workaround.
> -2 votes

---
Tags: media, uri, nodes
---


# Question
Title: Drupal Commerce Paypal: Order information at Paypal
I am using drupal commerce paypal. When a client is directed to the paypal site, then by default this information is shown: Order at .

How can I configure the information shown here?

thanks for any help

# Answer
The only way to change that is through an alter hook documented in the module commece\_paypal\_wps.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to turn on block or panel from old site to the new one
I'm fairly new to Drupal. I have an old version of site with a "block" or "panel" or whatever it's called, that displays on a page, and the new version doesn't have it, and I for god's love can't figure out how to turn it on. It would require looking at it directly, because it's just something I can't see in that beautiful user friendly admin dashboard of Drupal.

EDIT: Upon closer examination, it looks like a view with "content" data that is on the old site, but the "content" is missing on new one. Anyone knowing how to deal with that, I would appriciate that a lot.

# Answer
> 0 votes
Views out of the box support export / import functionality . You can export any view from any instance to any instance using below steps.. Make sure both the instances are in same Major Drupal version..

* Login as administrator
* Go to the view you want to export "admin/structure/views"
* Edit View
* Click on export link in the drop down

* Copy content
* Go to new site and navigate to "admin/structure/views/import"
* Paste copied content and click on Import

---
Tags: views, nodes
---


# Question
Title: Fatal error: Cannot redeclare MYTHEME_preprocess_user_picture()
If I add the following:

```
      function MYTHEME_preprocess_user_picture(&$variables) {
      $variables['user_picture'] = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
}

```

to my **comment.tpl.php** (the purpose of which is to use an image style on the comment author's picture,) I get a WSOD with the following message:

**Fatal error: Cannot redeclare MYTHEME\_preprocess\_user\_picture() (previously declared in /home3/zc1/public\_html/sites/all/themes/mytheme/comment.tpl.php:8) in /home3/zc1/public\_html/sites/all/themes/mytheme/comment.tpl.php on line 12**

Now, I know this error normally indicates a duplicate of the function. But in this case it seems to indicate that the duplication is in the same comment.tpl.php file. And I can't see it.

Here is the file, with the added code included:

```
<?php ?>
<div class="<?php print $classes . ' ' . $zebra; ?>"<?php print $attributes; ?>>

<?php
  function MYTHEME_preprocess_user_picture(&$variables) {
$variables['user_picture'] = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
} ?>
<?php print $picture ?>
<span class="submitted"><?php print $submitted ?></span>
   <span class="signature">
  <?php print $signature ?>
</span>
<div class="content"<?php print $content_attributes; ?>>
<?php if ($new): ?>
  <span class="new"><?php print drupal_ucfirst($new) ?></span>
<?php endif; ?>
    <?php hide($content['links']); print render($content); ?>
<?php if ($signature): ?>
<?php endif; ?>
  </div>

<?php print render($content['links']) ?>
</div>

```

Any idea what's going on?

This is Drupal 7 and I use Bartik.

Any and all help is greatly appreciated. Thank you. :)

# Answer
First of all you cannot write preprocess functions inside tpl.php.. It should go into your active theme template.php file.. Please see using preprocess functions in D.O.

Fatal error clearly says you have redclared same function twice."Cannot redeclare MYTHEME\_preprocess\_user\_picture()" . Search for "MYTHEME\_preprocess\_user\_picture" in your entire Drupal codebase and make sure you remove both of them since you need to rename "MYTHEME" to your active theme name. In your case it should be "bartik". So your function should be..

```
function bartik_preprocess_user_picture(&$variables) {
      $variables['user_picture'] = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
}

```

Above code should go into the theme template.php file.. To see the changes you need to clear cache by navigating to "admin/config/development/performance" or using drush command

```
drush cc

```
> 1 votes

# Answer
Change function signature with `'function bartik_preprocess_user_picture(&$variables)'` and put this function in template.php. Don't forget to clear the cache.
> 1 votes

---
Tags: theming
---


title: Second level in the menu

text:
# Question
Title: Second level in the menu
I have created a menu with items and one item has second level. So I created child links.

The problem is that the item which has second level links to some page and I would like to make it to link nowhere. It would be only collaps/expand link that shows or hides the child links.

I have found only possibility to set the link as `<front>` but this does not make what I want. Is this possible in Drupal 7?

OK, I found some modules the could help, Menu block and Nice menus but it seems that my problem could have some easier solution. How would you solve it? With some javascript?

thank you

# Answer
There are actually 2 links that can help you with your problem:

Menu items that are not links (Notice that the discussion starts from drupal 5, so you will have to skip to the drupal-7-specific comments: hit ctrl+f and search for Drupal 7)

Javascript to Disable Drupal Parent Menu Links (This solution is based on jQuery and CSS, so you won't have to modify the template.php file or install any extra modules)
> 0 votes

# Answer
There are two modules I know of specifically for allowing menu items that are not 'proper' links. There's Special menu items (which doesn't have a D7 release, but there's a patch) and Menu Firstchild (they're not identical in features, but both do what you want I believe).

You might also be interested in DHTML Menu which has a beta1 release for D7.
> 3 votes

# Answer
One thing you could do is to make the first level link manually, and make it identical to the 'primary' or most important second level link.

So you'd have something like this:

* About (about/who-we-are/)
    + Who We Are (about/who-we-are/)
    + Contact Us (about/contact-us/)
    + etc.

Then, using Nice Menus (or something else), you can make the second level menu appear as someone hovers over the primary menu items. Some users might click on this primary link, but this sends them to your desired second-level page.
> 2 votes

# Answer
You can use menu attributes to create an id for the menu item. With jquery you can then target that menu item and add an onclick event to show and hide your children to override the default on click.

```
if($('#your-id').get(0)) {
  $('#your-id').click(function(){
    $('ul', this).toggle();
    return false;
  });
}

```
> 2 votes

# Answer
https://drupal.org/project/special\_menu\_items does exactly what you want...

> **Special menu items** is a Drupal module that provides placeholder and separator menu items.
>
> A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.
>
> A separator menu item is something like "`-------`" which is not linking anywhere but merely a mean to structure menus and "separate" menu items visually.
>
> **Menu item container** provides similar functionality.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Add value to field using hook_webform_submission_presave()
I am at my wits end trying to use the hook\_webform\_submission\_presave function on a webform that I have created for a Drupal 7 site. Ideally I would like to capture a list of nodes that a user has flagged and transfer that data into a field before the user submits their form. But the function is just not adding the data.

First I get the flags:

```
$flags = flag_get_user_flags($node->type);

```

Then I want to transfer that variable into a field with a component ID of 32.

```
// Update some component's value before it is saved.
  $component_id = 32;
  $submission->data[$component_id]['value'][0] = $flags;

```

Here is the full function:

```
function get_flags_webform_submission_presave($node, &$submission) {
$nodes_list = array();
$title = '';
  // Get the flags.
  $flags = flag_get_user_flags($node->type);

  // Get the nodes.
  if (!empty($flags)) {
foreach ($flags as $flag) {
    $nid = $flad->entity_id;
    // Get node data. Delete to not get node titles.
    $node = node_load($nid);
    $title = $node->title;
    // Combine data.
    $nodes_list[] .= 'node/' . $nid . ' ' . $title . ",\n";
    }
  }

  // Update some component's value before it is saved.
  $component_id = 32;
  $submission->data[$component_id]['value'][0] = $nodes_list;
}

```

What am I doing wrong? I'd love some help!

# Answer
Dan, you should not have created another question out of this. This is a probably a duplicte of the original question now. The function that I initially gave you, handles flags correctly. Please see:

```
function leadflag_webform_submission_presave($node, &$submission) {
  $nodes_list = '';
  $title = '';
  // Get the flags.
  $flags = flag_get_user_flags('node');
  // Get the nodes.
  if (!empty($flags)) {
    $flags = $flags['flag_name'];
    foreach ($flags as $flag) {
        $nid = $flag->entity_id;
      // Get node data. Delete to not get node titles.
      $node = node_load($nid);
      $title = $node->title;
      // Combine data.
      $nodes_list .= 'node/' . $nid . ' ' . $title . ",\n";
    }
  }

  // Update some component's value before it is saved.
  $component_id = 4;
  $submission->data[$component_id][0] = $nodes_list;
}

```

**1. The foreach part should not be removed.** Flags is an array of objects, and you can't assign it to a field value, which expects a string. You can only remove the two lines I indicated in a comment if you want to.

**2. This should g in a module, not in a theme.** You should substitute the 'MYMODULE' in this code with a name of the module, where it is placed. How to create a simple module is among the other links I indicated back at your original question/answer.

You need to follow the steps I outlined in the original question. Here is with more detail:

1. Create the module. Replace the function name part 'leadflag' with the name of your module.
2. Clear the website (Drupal) cache.
3. Replace the component\_id with the correct one (see how in the original answer).
4. Replace the fid of the flag with your actual fid.
> 0 votes

# Answer
`flag_get_user_flags` will return an array. so you have to handle it as an array not like a value.
> 0 votes

---
Tags: 7, theming, webforms
---


# Question
Title: Creating menus links for displaying articles with specific tags
How would you go about creating a categorization system which categorizes after tags and then displays a link to the page with only the specific tags linked/posted?

Aka 1 page per category. On each page there is series of blog-posts/content which has the same tag (I believe this is called the taxonomy term?)

and then of course add the links to the pages to the menu (got this one as long as there is an URL)

Thanks!

# Answer
You need the taxonomy menu module. Here is a quote about it (from the module's project page):

> Transforms your taxonomy vocabularies into menus with ease!
>
> Features:
>
> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules
> 0 votes

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


# Question
Title: Creating a page only to be accessed by registered users
at my site tobynews I have users that would be registered as an "author." What I'd like to do is create a page such as an "Author's Resources" page that would only be accessible by someone who is registered as an author through the site. I'm not exactly sure how to approach this, other than trying to connect to the database's user table with a form. Any help is greatly appreciated.

# Answer
You could do that using Drupal's role based access control system.

For example, assign the role of "author" to the author users. You can then restrict access to the "Author Resources" page by user role. e.g

1. Create a page using the Views module and adding an access restriction.
2. Create a page using hook\_menu and restrict access to that role in the "access callback"
> 0 votes

# Answer
Or (following on from David Thomas' answer) if you are using Panels you can restrict access by roles.
> 0 votes

---
Tags: 7, users
---


title: Menu <front> href not working

text:
# Question
Title: Menu <front> href not working
I've never seen this problem in Drupal 7, but my home link contains the string `<front>` within its href. It's not working.

Any idea what could be happening?

# Answer
> 1 votes
In Drupal `<front>` is used to make a link which points to home page.. If you are in home page even if you click on that link you will come back to same page..

You can find the documentation about it in URL API function where it says..

> The special string `<front>` generates a link to the site's base URL.

URL function converts href from `<front`\> to ''. So you should get baseurl in href. I see you are using spanish language, may be special characters in `<front>` is causing issue.. Can you make sure front word is utf-8 english supported letters..

After carefully watching your screenshot i see you are using Void Menu module which is the root cause of your problem.. For solution see this issue in module Project Page..

---
Tags: 7, navigation
---


# Question
Title: Is it possible to have three levels of subdomains in Drupal 7?
I know how to create a sub domains for Drupal website (I create a sub domain and add its folder in `/sites` folder). Out websites are multilingual so for every language I create a subdomain and in the end the sites are going to be like this :

1. fr.example.com
2. en.example.com
3. ar.example.com

and so on. we have also a few sites that are subset of our main website and we want to display them like this

fr.subset1.example.com

en.subset1.example.com

ar.subset1.example.com

fr.subset2.example.com

en.subset2.example.com

is it possible to implement such thing in Drupal 7?

# Answer
> 1 votes
The answer is "yes". A Drupal multisite can use whatever structure it likes, including the one you propose.

To do this for subdomain `http://fr.subset1.example.com/` just create the following subdrectory `sites/fr.subset1.example.com/`. Make sure it contains the file `default.setttings.php` and a copy this to `settings.php`. Then create subdirectories `files` (and optionally, `modules` and `themes`), and make sure they're all writable by the web-server user.

Then:

1. Set up DNS for this subdomain (fr.subset1.example.com) to point to the same IP as the default domain.
2. Create a serveralias (details below) (or vhost entry) for that directory that has the same web root as the default domain.
3. Point your browser to the base URL of your website (`http://fr.subset1.example.com/`) to complete the web based part of the installation of a Drupal site.

To create a multi-site instance, you also need to make sure the DNS for that instance points to the same web root as the default domain. If you've set up a sub-domain, the simplest way to do this is to add it as a *ServerAlias*. This means putting something like this in the Apache vhost configuration:

```
<VirtualHost *>
  ServerName example.com
  ServerAlias fr.example.com
  ServerAlias fr.subset1.example.com
  …
  DocumentRoot /var/www/example.com/htdocs/
  …
</VirtualHost *>

```

Alternatively, you may create a separate vhost for the multi-site. This requires a separate entry, but allow you to tailor the web server settings for this particular multi-site instance.

Repeat this procedure for any other subdomains you want.

---
Tags: installation, subsites
---


# Question
Title: How to create heirarchical taxonomy menu/list using VIEWS
How can I create a view of taxonomy terms for a content type (Story and Page) and display it to a block with parent and child relationship?

What I want is to take a "Taxonomy Term" based on "Content Types".

Example:

```
Fruits (5)
  - Apple (3)
  - Banana (2)
Vegetables (4)
  - Beans (1)
  - Eggplant (2)
  - Onions (1)

```

Demo: http://worldstogethertravel.com

Menu on right sidebar: (Of Cultural Interest)

This menu is created using taxonomy\_menu module not VIEWS.

# Answer
> 0 votes
You can try using Views Tree module..

Project page says

> Views Tree module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
>
> It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.

For node count, you can implement same using views.. Check this post Views and node count for taxonomy terms..

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


# Question
Title: Node access depending on boolean field in user profile
I would like to control access to specific articles or categories of articles depending on a boolean variable in a user's profile.

For example, this would be on a site where a user gets access to all kinds of data about their product after they purchase it. I would like to manually enable or "tick" a boolean field on their profile which then allows them to see the corresponding information when they browse the website.

I hope you understand what I'm trying to say.

I have already set up a few fields on the user profiles and I'm trying to make it work using the Rules and Content Access modules but I'm not sure if I'm heading in the right direction. I have thought about just setting this up with a "View" but I think the content would still be accessible to everyone by default if they have a link or through Google?

If someone could point me in the right direction, that would be great. Thanks in advance!

# Answer
> 1 votes
I got it working, for the sake of anyone ever needing this functionality and stumbling upon this thread:

You'll need the Access Control and ACL modules. The combination of these allows you to set "per user" access for each individual node. For the checkboxes on a profile or page, you'll need to use the Entity Reference module and create a field on the profiles for that type of content. You can then set that field up as checkboxes.

For the final part, you'll need the Rules module and set up two rules: one to "Grant Access per user" and grant view access when a specific value of the checkboxes is true and one to "Revoke Access per user" when values have changed. You'll need to play around with the rule's conditions to make it suit your needs.

# Answer
> 0 votes
Content Access is a roles-based access control module. So, you must have created a role for your "controlled access" content. And setup the Content Access settings on your content types. From here, you could use standard, Drupal user admin to add remove users to/from this role. Done.

But if you want to assign this role dynamically, Rules is a place you can do it.

Create a rule that triggers on the "Before saving a user account" event. Add a "Data comparison" condition to test your boolean field's value. Select "account" then "" in the Data Selector field. For the Value field, select the value you want to trigger from (most likely the 'on' value for your boolean). Now, add the "Add user role" action, and select your "controlled access" role. Save. And test.

You'll also want create an inverse rule to remove the role.

Good luck!

---
Tags: entities, rules, users
---


# Question
Title: hook_block_view For an Array of Paragraphs
Is there a way to use the theme() function to process an array of paragraphs, in a fashion to how theme('item\_list', $theme\_args) works?

If there is not a way using the theme function, what then is the "preferred" way to create a render array for an array of paragraphs?

# Answer
There isn't a 'preferred' way, or built in function, to render an array of paragraphs. You could do it like this:

```
$build = array(
  'p1' => array(
    '#markup' => 'Something',
    '#prefix' => '<p>',
    '#suffix' => '</p>',
  ),
  'p2' => array(
    '#markup' => 'Something else',
    '#prefix' => '<p>',
    '#suffix' => '</p>',
  ),
);

```

Or this:

```
$build = array(
  'p1' => array(
    '#markup' => '<p>Something</p>',
  ),
  'p2' => array(
    '#markup' => '<p>Something else</p>',
  ),
);

```

Or you could build a theme function which takes an array of paragraphs and builds up an HTML string. Or you could use some variation of `implode()`, or a simple loop, and so on.

It really depends on how you want to approach it, there are several equally valid ways to solve that problem.
> 1 votes

---
Tags: hooks
---


title: How to add custom slider for textfield

text:
# Question
Title: How to add custom slider for textfield
I read:

I'm using jQuery Update module. Tried different versions of jQuery.

I have theme tao\_test (that is subtheme of Tao). In tao\_test.info I added:

```
scripts[] = scripts/ranger.js

```

And inside of this js file is this code:

```
(function($){

    Drupal.behaviors.tao_test = {
      attach: function(context, settings) {

          $("input#edit-field-range-test").before("<div class='range-slider'></div>");

          $(".range-slider").slider({
              range: "min",
              value: 1,
              step: 1000,
              min: 0,
              max: 5000000,
              slide: function( event, ui ) {
                  $( "input#edit-field-range-test" ).val( ui.value );
              }
          });

      }
    };
}(jQuery));

```

Now problems:

1. When logged in as admin, slider kinda works, but looks strange:

There is no knob and overall it looks graphically broken. Also it only works if I set "CDN jQuery and jQuery UI" in jquery\_update settings to some value.

2. When watching as anonymous user, I'm getting in firebugs console:

> TypeError: $(...).slider is not a function

What I'm doing wrong?

**Added:** Oh, I realized that this slider is supposed to be unusable without theming. However the problem with anonymous user is still current.

# Answer
It appears that:

```
function THEME_preprocess_html(&$variables) {
    drupal_add_library('system', 'ui.slider');
}

```

is needed for query\_ui to be available for anonymous users on every page.
> 1 votes

---
Tags: javascript
---


# Question
Title: How can I filter a View by the value (or data) of field?
This seams like quite a basic thing but I cannot work out how to do this in Views, since the Views filter criteria has no option to use the data/value from a specific field or token. There is only an option to add a constant value or to expose the field, neither of which are useful in my case.

I have a list of entities which I would like to filter based on the value of a node field; and this value is auto assigned through a default token set in the content type. The field is a plain text field with a date in it, which I would like to use to filter my list of entities to only show the entities created on that particular date.

# Answer
> 1 votes
I have worked out how to do this finally. You need to install the token filter module and then when entering a value for a filter inside Views, you can make the operator "equal to" a token. Meaning, you can filter by the value of a particular field or anything else exposed as a token.

---
Tags: entities, views
---


# Question
Title: "Questions that may already have your answer" Stackexhange Module For Drupal
is there a module for drupal when you write a title to a question it suggest the answer i.e

"Questions that may already have your answer" on Stackexhange

Many thanks for your help

# Answer
> 4 votes
If a 'Question' is a node, you could use the Similar Entries module as a starting point:

> Similar Entries provides lists of links to site content related to the current node being viewed. Links can be displayed in standard blocks or as part of custom views. Similar content is located and rated using MySQL's FULLTEXT indexing for MyISAM tables. FULLTEXT is a special query that helps find relevant content in other nodes using a natural language search that interprets the search string as a phrase in natural human language.

It will require some customisation to get a similar workflow to the one Stack Exchange uses (you'll need to make the blocks appear on the node add/edit pages somehow, and implement an AJAX solution for suggestions while writing the title).

I'd be surprised if there's a module which replicates the functionality here straight out of the box.

---
Tags: 7
---


# Question
Title: Add custom files/file-fields to panels pages
I would like to add content from a set of file fields to particular pages (via panels/panels everywhere/panelizer) with the ability to change the files by panels IPE editor or backend form.

Ideally, I would like to just add a custom content pane, or minipanel (or whatever it needs to be) to specific panels pages, and have that widget be able to upload files that print to the page, and that page only. It would also be nice to reuse the widget for other panels pages for different sets of files. I'm trying not to involve a whole other set of node/content types just to do this.

Could anyone point me in the right direction? Thanks.

Detail: The purpose is to upload files and add file paths to an element on some pages which is the image/video source for a fullscreen image/video background script.

# Answer
What you are looking for is a customized fieldable panel panes. You can also check Panopoly Widgets for a similar example. It contains a lot of custom widgets which can be embed in panel panes and customized. Fieldable panels panes makes your widget data as fieldable entities instead of node/content types(which is what you want).

If you want dynamic background images on a specific page context, you could check the dynamic background module.
> 0 votes

---
Tags: entities, panels, files
---


# Question
Title: How to create an Enquiry form with ability to submit a collection of enquiries
I am building a new site which has a large selection of different products/services on offer, the information for each is shown in it's own node.

If the user has interest in a number of these services then I would like to give them the ability to 'add' the item to their enquiry along with a message. When they have added all of the items they are interested in they can then submit the enquiry.

Overall, the process shares similarities with an e-commerce workflow

1. View product
2. Add product to enquiry form builder with comment (choose options and add to cart)
3. Browse other products and repeat steps 1&2.
4. Once happy, review enquiry (checkout)
5. If all is ok, submit enquiry (process order)

Using Drupal 7, how would you suggest I tackle this?

I only compared the process to e-commerce as it helped me think things through, the site isn't actually going to be selling the products. Strictly a tool to submit a detailed enquiry.

# Answer
Switch to Entityform. This uses the core field APIs. Add an entity reference field on your products and services types. Details from the project page:

> The Entityform module enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields. This means that out of the box, you can use any standard Drupal node field! As of the time this article was written, there were over three hundred "field" modules. And since Entityforms are "Drupal entities", you will automatically be able to use future "field" modules!
>
> The forms can be used to create custom surveys, petition, and personalized contact forms, and other customized form. (For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.)
>
> As with everything in Drupal, there are Pros and Cons to using Entityform. All though Entityform is a powerful tool, it is not always the best solution. The article When to Use Entityform discusses the advantages and disadvantages that Entityform may have over other methods of creating user "submittable" forms. Do not use Entityform for forms that will contain 150+ form elements

Entity form works well with other modules like Rules so you can get really custom with your behaviours.
> 0 votes

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