# Question
Title: How do you perform a rules action by the quantity of a specific commerce product?
I'm working on a module which is going to be used alongside Drupal Commerce so people can buy a set number of digital products. I've written a custom rules action, which will be run once for each purchase of a specific commerce product. How can I add this to a loop, so that the action gets run n times (n being the quantity purchased for this product, as you could purchase more than one).

So far I've added this action to a loop for `commerce-order:commerce-line-items` but even if I purchase more than one, the action is only run once. How can I make the action run 'quantity of this product purchased' number of times?

Many thanks

# Answer
The quickest way to do this is with another custom action. Since you already wrote your own module, this shouldn't be a problem.

In your my\_module.rules.inc file, do something like:

```
function my_module_rules_action_info() {
 return array(
  'my_module_loop_based_on_qty' => array(
    'label' => t('Execute a loop based on a quantity'),
    'parameter' => array(
      'quantity' => array(
        'type' => 'integer',
        'label' => t('Quantity added to cart'),
      ),
    ),
    'group' => t('My Module'),
  );
}

function my_module_loop_based_on_qty($qty) {
  // Loop based on the $qty variable
}

```

Provide whatever other parameters you need for the function as well. You can then pass it the quantity when you create the rule. That other rules action you already wrote can just be wrapped in a helper function that is then called by this new action.
> 0 votes

---
Tags: commerce, rules, actions
---


title: Get view and process content

text:
# Question
Title: Get view and process content
I'm trying to build an infinite scroll with views using a custom ajax callback function, every view has only 1 node displayed. What I would like to do is use the offset to load the correct view. To be clear, I already tried views infinite scroll and infinite scroll modules and for various reasons I cannot use them.

What I got so far is this:

```
$view = views_get_view('frontpage');
$view->set_items_per_page(1);
$view->set_offset($offset);

$view->execute_display();

```

This gives me back the right markup with the right node.

My question is, what if I want to process the node loaded in the view before getting back the markup? Is this possible? I've looked through the view API multiple time without finding something suitable.

# Answer
> 0 votes
You can display anything using Views: Nodes, users, comments, fields. Drawback is - Views object does not particularly care about the type of data. As long as handlers can process it, it works. But that means it cannot really expose methods related to the kind of data displayed. It might be possible to hack around it, but it's not the way it was designed to work.

---
Tags: 7, views, nodes, ajax
---


# Question
Title: Difference between Minimum cache lifetime and Expiration of cached pages
On Drupal Performance Page, under the fieldset Cache you have two options. One is Minimum Cache Lifetime and the other is Expiration of cached pages.

What is the difference between these two.

# Answer
> 41 votes
I have made following observations after spending a few hours. If there are any gaps or mistakes, do let me know. I will be happy to make editions.

First observer that none of the Options under the **CACHING** are interdependent. If they were you would have seen them under different field sets(or as dependent fields). Make a note of this observation and we will revisit that later.

Let us begin with the first option **Cache Pages for anonymous users**.

When you check this option you are basically telling Drupal

Hey Beast listen, when an anonymous user visits my site,

1. Store the generated HTML in the cache table
2. So that I can display the same result to all users as my pages remain same for all anonymous users.
3. And don't clear the page caches until I say clear all caches.

Also even when you don't enable the `Cache Pages for anonymous users` the page can still be cached by external cache systems. Eg : Boost

Now lets move to the next options which you would end up using generally.

**Expiration of cached pages**

1. Note that this setting has nothing to do with the Drupal Database or cache tables.
2. Read the description `The maximum time an external cache can use an
old version of a page.` As Molot pointed out the keyword is external.
3. So what this option basically does is it sets the header Cache Control to `public` and the max-age value in the header to the specified value(1 day in this case).
4. This header tells the `external` Caching systems not to make a call to the server for this page until the max age, as they can show this page from their own cache. After the max-age the Caching system should check back with the Drupal server to see if the content has changed.
5. If its a Varnish server, it doesn't make a call to Apache and returns the page from its cache. So assume that Varnish has cached a page and thousand different users made a request to that page. So it means that 1000 requests have been processed without hitting the Apache Server even once.

**Minimum Cache Life Time**

If your site doesn't have a huge traffic or if you are not sure what this value is, it better to leave this value as none.

1. This value applies not just for the pages. But all the cache objects.
2. What this value tells is "Its ok to serve cache objects which are stale"
3. In our case the value is set to 5 mins.
4. If you have a page that lists the five latest blogs on your home page. What the above values means is that, if a new blog is created its ok for the blog not to appear on the listing for the five minutes.
5. When this value is set, for the cache to be updated/recreated minimum this much time must have passed and a cache clearing action must be run\[A cache clearing function should be run\].

# Answer
> 19 votes
This article has a good rundown of the caching terminology of Drupal: http://www.phase2technology.com/blog/caching-in-drupal/

Summary of the relevant points:

**Minimum cache lifetime** is often misinterpreted as meaning "pages will be regenerated after this much time has passed". What it actually means is that pages will not be regenerated until at least this much time has passed and a cache clearing event has happened.

**Expiration of cached pages** is also sometimes misinterpreted. This value controls what is sent as a max-age value in a Cache-Control header and thus advises proxy servers how long they may serve the page without asking your Drupal install for a new copy. This does not mean that the page will be regenerated after this much time, it just means that the proxy server must check back with Drupal to see if a new version of the page exists after this much time. Drupal will only regenerate a page after a cache clearing event occurs.

---
Tags: 7, caching
---


# Question
Title: Problem with image styles : access denied
I'm getting a problem with image styles being created. The files are there but the styles are not getting created. I have tried changing permissions recursively on the folder (udo chmod -R 777 /Applications/MAMP/htdocs/geoslate/sites/default/files/)but this isn't solving it. I've tried deleting the styles folder but it doesn't get recreated. There is an error in the log:

```
access denied
Date    Wednesday, May 1, 2013 - 11:03
User    admin
Location    http://localhost:8888/geoslate/sites/default/files/styles/thumbnail/public/image-file-name-325x250.jpg?itok=zPXsGtyX
Referrer    http://localhost:8888/geoslate/node/1
Message sites/default/files/styles/thumbnail/publicimage-file-name-325x250.jpg
Severity    warning

```

# Answer
It is either you update your Drupal core to the latest version or you You can add the following line to your settings.php to get the images in the site working:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```
> 6 votes

# Answer
Take care with this configuration:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

The main purpose of the 7.20 release is to prevent a denial of service security issue. With this setting turned on, you site is still vulnerable.

If you want to keep this configuration I strongly recommend you to upgrade, at least, 7.21. The purpose of this release is to allow sites using this variable to have a partial protection.

I'm not sure if this should be a answer, but I don't have enough reputation to post a comment yet.
> 5 votes

---
Tags: media, users
---


# Question
Title: Use swatches and not the color picker widget
The Color core modules allows for a user to perform css color overrides via the theme settings page. This is handy for exposing the means for users to update color specifications without touching a line of CSS code. I've successfully integrated the Color module with an Omega 3.x subtheme. However, we have a range of branded color swatches that I'd like to make available to our users, rather than the too-broad color picker that the color module uses.

So; I'd like to swap (it can be additive, i.e., use one or the other) the Drupal color picker with a pane of swatches that I can configure.

How to do so?

# Answer
> 3 votes
Interesting question - You should try the color field module \-

> Color Field is simple field that use a hexadecimal notation (HEX) for the combination of Red, Green, and Blue color values (RGB).

This uses the jquery simple color widget

and you can add your colors directly in as hexadecimal codes when you setup the field:

---
Tags: 7
---


title: Drupal cache expire value of -1?

text:
# Question
Title: Drupal cache expire value of -1?
What does a value of -1 mean when it's present in the expire field of a cache entry in the database? I've honestly looked around and could not find an answer.

# Answer
It is coming from includes/bootstrap.inc:

```
/**
 * Indicates that the item should be removed at the next general cache wipe.
 */
define('CACHE_TEMPORARY', -1);

```

Which is also defined in the docblock for `cache_set($cid, $data, $bin, $expire)`:

> `$expire`: One of the following values:
> \- `CACHE_PERMANENT`: Indicates that the item should never be removed unless explicitly told to using cache\_clear\_all() with a cache ID.
> \- `CACHE_TEMPORARY`: Indicates that the item should be removed at the next general cache wipe.
> \- A Unix timestamp: Indicates that the item should be kept at least until the given time, after which it behaves like `CACHE_TEMPORARY`.
> 3 votes

---
Tags: 7, caching
---


title: Customise Views PDF export

text:
# Question
Title: Customise Views PDF export
I am using Views PDF to export some of my pages as PDF files. So far I can get it to export the files . I am however getting challenges in trying to adjust the styling. I have looked at the module for any tpl files and they are not there. Anybody with a headstart on this?

# Answer
In the pdf view under "PDF SETTINGS" you can add a css file for styling. Note that it only supports basic css.
> 1 votes

---
Tags: views, files
---


# Question
Title: how to assign different Text formats for each Long Text fields?
In my node creating form i have two `Long Text` fields, they are:

1. Article
2. Lists

And i have created two `Text Formats` they are:

1. Article
2. Lists

Now, is there any Drupal way to assign:

* `Article (field_article)` field with `Article` Text Format
* `Lists (field_lists)` field with `Lists` Text Format

If not, then how i can do it Programmatically in node `node--article.tpl.php`? or any other idea?
\- Thanks

# Answer
> 3 votes
Use the better formats module. The module allows you set text formats per field.

> Better formats is a module to add more flexibility to Drupal's core input format system.

---
Tags: 7, nodes, input-formats
---


# Question
Title: create drupal 7 webform programmatically?
I have already created a webform and I need to fill it programatically.

how can I create webform ? Can i create it like node creation:

```
$node = new stdClass()
$node->type = 'webform'
$node->webform['components'][1]['value'] =  'sss'

```

# Answer
See code below:

```
function _add_webform_components($node) {
  $components = array(
    0 => array(
      'name' => 'First name',
      'form_key' => 'first_name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 1,
      'pid' => 0
    ),
    1 => array(
      'name' => 'Name',
      'form_key' => 'name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 2,
      'pid' => 0
    ),
    ... and so on

  );

  webform_ensure_record($node);
  foreach($components as $component) {
    $component['nid'] = $node->nid;
    $component['extra']['title_display'] = 'inline';
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }
  $email = array(
    'nid' => $node->nid,
    'email' => 'name@example.ch',
    'subject' => 'default',
    'from_name' => 'default',
    'from_address' => 'default',
    'template' => 'default',
    'excluded_components' => array(),
  );
  webform_email_insert($email);
}

```
> 7 votes

# Answer
Maybe it is easier to understand with this example:

```
function hook_node_insert($node) {
  if ($node->type == 'your_content_type') {
    webform_ensure_record($node);
    $components = _my_function_webform_components();
    foreach($components as $component) {
      $component['nid'] = $node->nid;
      $component['extra']['title_display'] = 'inline';
      $node->webform['components'][] = $component;
      webform_component_insert($component);
    }
    $email = array(
      'nid' => $node->nid,
      'email' => 'name@example.ch',
      'subject' => 'default',
      'from_name' => 'default',
      'from_address' => 'default',
      'template' => 'default',
      'excluded_components' => array(),
    );
    webform_email_insert($email);
  }
}

function _my_function_webform_components() {
  $components = array(
    0 => array(
      'name' => 'Name',
      'form_key' => 'name',
      'type' => 'textfield',
      'mandatory' => 1,
      'width' => '40',
      'maxlength' => '75',
      'weight' => 1,
      'pid' => 0
    ),
    1 => array(
      'name' => 'Age',
      'form_key' => 'age',
      'type' => 'number',
      'mandatory' => 1,
      'max' => '99',
      'excludezero' => 1,
      'weight' => 2,
      'pid' => 0
    ),
    ...
  );

  return $components;

}

```
> 0 votes

# Answer
You can make use of `drupal_form_submit` I didn't tried it.

Anyway this may can help you.

> This function allows you to supply values for form elements and submit a form for processing.

The idea is to find the `form_id` check for the form fields and

```
// register a new user
$form_state = array();
$form_state['values']['xxx'] = 'yyyyy';
drupal_form_submit('xxx', $form_state);

```

Give a try and please paste the code here if you succeed.
> -3 votes

---
Tags: 7, webforms
---


title: Strange Views Relationship Error

text:
# Question
Title: Strange Views Relationship Error
I've done quite a bit of googling and can't seem to find any information on this error, so I'm going to assume it's not a common one.

The error is:

> Notice: Undefined property: views\_handler\_relationship\_broken:: $alias in EntityFieldHandlerHelper::query() (line 84 of /MYPATH/sites/all/modules/entity/views/handlers/entity\_views\_field\_handler\_helper.inc).

A bit of information about my set up, I've been using Views to show a list of my Drupal Commerce Product displays, set up similarly to Commerce Kickstart where you have the Product Display that references the Commerce Products via the SKU. This error arose shortly after removing some fields relating to a relationship the view was using, as these fields no longer exist they cannot be re-added.

I've cleared the views cache, the site cache, to no avail. Is there any kind of database entry that may be referencing this particular relationship still?

Regards, Daniel.

# Answer
By enabling views debugging in views advanced settings I was able to narrow down the actual view with the error and it wasn't the one I had first suspected, oops! Note for anyone coming into similar problems, views debugging is amazingly helpful alongside Devel.
> 1 votes

# Answer
Generally you shouldn't remove fields that are used by other mechanisms, like Views. Now when it's done, the best way I know is to export view, manually remove fields that was deleted from it, and re-import. And don't forget your backups.
> 2 votes

---
Tags: views
---


# Question
Title: drupal_goto(request_uri()) replaces my '?', '=' and '&' in url
I need to redirect user from a page with example.com/node/add/dispo?arg1=1&arg2=2 to the same type of URL. But when I simply do a `drupal_goto(request_uri());`, it redirects my user to example.com/node/add/dispo%25F%3C etc....

I tried a str\_replace but it didnt work.

Would you have any workaround ?

# Answer
> 33 votes
`drupal_goto()` accepts an `$options` parameter to be passed on to the `url()` function. You can pass a query string like this:

```
$options = array('query' => array('foo' => 'bar'));
drupal_goto('path', $options);

```

That example will forward on to /path?foo=bar

# Answer
> 13 votes
This is same as Clive's answer. It's correct IMO but I just wanted to add the answer that suits your use case 1:1.

```
$options = array('query' => drupal_get_query_parameters());
drupal_goto(current_path(), $options);

```

You wanted to call `drupal_goto()` to the same location as the current one.

```
mysite.com/node/add/dispo?arg1=1&arg2=2

```

current\_path() returns node/add/dispo; drupal\_get\_query\_parameters() returns all `$_GET` parameters except `$_GET['q']` which is the internal path node/add/dispo.

When you call `drupal_goto()`, Drupal can rebuild the same URI to send the user to.

# Answer
> 0 votes
You can also use `drupal_goto($GLOBALS['base_root'] . request_uri());`

Note that it is not same as `drupal_goto(request_uri());` where the passed parameter is urlencoded as if it is an internal drupal path, which is actually the source of your issue.

# Answer
> -1 votes
Actually I made it work by using `header("location: " . $base_path . request_uri());`

---
Tags: 7, uri, views
---


# Question
Title: How do you create a colorbox popup on the frontpage of D7?
I'm using Colorbox and Drupal 7. I'm trying to create a Colorbox of an Image on the front page in a POP-UP. The problem is I can't figure out how to get it to show up on page load. How can I achieve this without adding an additional elements showing on the frontpage?

# Answer
The module: Splashify did the job.
> 1 votes

# Answer
You could use Views:

* create a view with a block display
* add the field with the image and set the output to colorbox
* add this block to the homepage with Context or block management
> 0 votes

# Answer
This module is an option: Popup On Load

> The module allows to display a popup after a certain delay on a page load. This fills a gap in popup modules family (Popups, Popup), which are designed to show popups only after a click on an HTML element, or to implement a complex behavior like modal dialog forms.
> 0 votes

---
Tags: javascript
---


title: Limiting users to edit other users

text:
# Question
Title: Limiting users to edit other users
I have a hierarchical user structure, so every user has a entity reference field that points to another user - his/her supervisor.

The thing is that I need to give every user the permission to modify/delete the users that are under him/her in the hierarchy but to no one else.

It is a bit more complicated due to the fact that the hierarchy can be quite high, so a user has to be able to modify even users that points to someone (as to their supervisor) who points to him.

I've Googled for quite a few minutes but didn't find any solution whatsoever. I also need to implement it with my module so programmatic approach would be proffered to another module.

# Answer
You need to define your own access call back for the menu items. For example: implement hook\_menu\_alter and changes the access callback for `item['user/%user/edit']` and `item['user/%user/cancel']` to your own custom access callback. I have not tried this myself yet, but it is something along these lines:

```
/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function MYMODULE_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'MYMODULE_access_callback';
}
/**
 * Callback to disallow access for the anonymous user.
 */
function MYMODULE_access_callback(){
  global $user;
  // if the global user (current user) satisfy the criteria
  // then return true else false.
  // you might not have to load the user from the menu item
  // as it may be already loaded and passed to the page and access callback
  // see hook_menu
}

```

It might be a better idea though to define your own menu items and handle the operations on your own instead of altering the user menu items.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How can I change the value of a field in Entity B based on the value of a field in Entity A?
I need a bit of help with Rules. I'm trying to create a rule that if a check box is checked on one entity, change the value of another checkbox on another entity. I have the conditions "Entity has field - Checkbox A" + "Data Comparison Checkbox A, value = Checked". But for the Action, I don't know how to set the value of Checkbox B on the other entity.

More detail: it's for a hotel booking site. I have an entity for the booking and an entity for the room itself. I want it so that when the "Checked-out" box is selected in the booking entity, the "Needs Cleaning" box in the room entity is checked. The two entities are linked by the room\_ID number.

# Answer
You may need to write a quick custom action for this given your use case but its fairly easy to do. First create a custom module and add this hook to declare that you are creating a new action to be taken when 'someone checks out'.

```
/**
 * Implements hook_action_info().
 */

function YOURMODULE_action_info() {
  return array(
    'YOURMODULE_room_checkout_action' => array(
      'label' => t('Action to take after someone checks out'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
}

```

Presumably, you want to attach this action to the trigger you already have, perhaps 'when booking content type is updated'.

Next, all you need to do is write your payload function that gets triggered for the action. The name for this is the same as what we defined in the array above. After that, you just need to set the two values which is a bit more involved but the pseudo code here should get your started.

```
/**
 * Action function for 'check out of room' action.
 *
 * @see action_example_action_info()
 */
function YOURMODULE_room_checkout_action(&$entity, $context = array()) {

  // find entity id for your room entity and load entity as $room
  // set $room->needs_cleaning field to 1 (or same value as $booking->checked_out
  // note that the $entity passed here is the one from your trigger (ex. the booking node)

}

```
> 1 votes

---
Tags: rules
---


# Question
Title: Services Views not exposing thumbnail image url
I am trying to create a view which will be exposed as a service via Services Views module. I have only defined Default display for this view and added the following field to the list of Fields -

* Node: Nid Nid
* Node: Type Type
* Node: Title Title
* Profile: Author Info: Full Name Author Name
* Node: Post date Post date
* Node: Teaser Teaser
* Node: Promoted to front page Promoted to front page
* Node: Last edited by Last edited by
* Node: Updated date Updated date
* Content: Thumbnail URL to file

All the fields are appearing nicely when I request it (using this url: http://localhost/app/rest/views/articlelist?args\[0\]=1), but the last field, which is the url to thumbnail file isn't appearing there.

A sample response from the above url is as follows -

```
<item>
<nid>22</nid>
<type>Article</type>
<title>UK soldier killed in Afghanistan</title>
<author_name>Demo Journalist</author_name>
<post_date>Jul 1 2012 - 4:08pm</post_date>
<teaser>
<p> ret rre tre tretre trtretre tre t re t ret rre tre tretre trtretre tre t re t ret rre tre tretre trtretre tre t re t ret rre tre tretre trtretre tre t re t ret rre tre tretre trtretre tre t re t ret rre tre tretre trtretre tre t re t</p>
</teaser>
<promoted_to_front_page>Yes</promoted_to_front_page>
<last_edited_by>admin</last_edited_by>
<updated_date>Jan 2 2013 - 3:56pm</updated_date>
</item>

```

What do I need to do to display the related thumbnail url?

**Edit**

Here is the query that is being executed (obtained from preview) -

```
SELECT node.nid AS nid, node.language AS node_language, node.type AS node_type,
       node.title AS node_title,
       profile_values_profile_full_name.value AS profile_values_profile_full_name_value,
       profile_values_profile_full_name.uid AS profile_values_profile_full_name_uid,
       node.created AS node_created, node.promote AS node_promote,
       node.changed AS node_changed,
       files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_fid AS files_node_data_field_thumbnail_image_node_data_field_thumbnail_image_field_thumbnail_image_fid,
       files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_list AS files_node_data_field_thumbnail_image_node_data_field_thumbnail_image_field_thumbnail_image_list,
       files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_data AS files_node_data_field_thumbnail_image_node_data_field_thumbnail_image_field_thumbnail_image_data,
       node_data_field_analysis_box.field_analysis_box_value AS node_data_field_analysis_box_field_analysis_box_value,
       node.vid AS node_vid
FROM node node  LEFT JOIN content_type_article node_data_field_thumbnail_image
ON node.vid = node_data_field_thumbnail_image.vid
LEFT JOIN files files_node_data_field_thumbnail_image
ON node_data_field_thumbnail_image.field_thumbnail_image_fid = files_node_data_field_thumbnail_image.fid
INNER JOIN term_node term_node
ON node.vid = term_node.vid
INNER JOIN users users
ON node.uid = users.uid
LEFT JOIN profile_values profile_values_profile_full_name
ON users.uid = profile_values_profile_full_name.uid AND
    profile_values_profile_full_name.fid = '1'
LEFT JOIN content_type_article files_node_data_field_thumbnail_image_node_data_field_thumbnail_image
ON files_node_data_field_thumbnail_image.fid = files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_fid
LEFT JOIN content_type_article node_data_field_analysis_box
ON node.vid = node_data_field_analysis_box.vid
WHERE (node.status <> 0) AND (term_node.tid IN (1, 2))
ORDER BY node_changed DESC, node_created DESC

```

# Answer
It's a bit unclear what you have in your view, but here are some suggestions:

* Make sure you have Formatter set to "Image URL", and the "Image Style" set to the specific style (ie thumbnail)
* Ensure that you actually have some data for your filter. "No Results Behavior" may have "Hide if empty", which would omit this field in your response if it's not set.
* Enable showing the query and results for the view to at least check that the return data contains the value that you expect (admin/structure/views/settings -\> \[\] show performance statistics)
* Check that your contextual filter is not obfuscating something - remove the args\[0\]=1
* Ensure that the normal Page response for the view displays a value for the thumbnail field, by going to the "path" that you've defined for the view.
> 1 votes

# Answer
On the View edit page, try:

* Edit the image url field settings
* Expand "Rewrite results"
* Check "Output this field as a link" then
* Check "Use absolute path" under link rewrite options.
> 1 votes

# Answer
I have unsolved case to display field image (uri) before, I can solve it by using viewsphp module to load field image value.

Have you seen the video demo on this page? http://drupal.org/project/services\_views
> 0 votes

---
Tags: views, 6, services
---


# Question
Title: Problem ignoring in a view the images inside the .views field body and the minimum number of characters?
I need to remove the images appears in the view in the field body. I have tried the following code.

```
.view-mydisplay .views-field-body {
    display:none;
}

```

However, I cannot see the image but the "maximum length of characters" of my field-body are not showing completely. If I remove the image manually in the body, then the characteres are complete in the view. Seems how if the image were counted like character.

For example if I have 300 max. characters in my view and I put an image only are showed 100 characters, after remove the images with css. If I don't put the image in my body, the view shows the 300 characters configured in the view.

# Answer
> 2 votes
The Smart trim module might be helpful. You'll be able to trim units by words or characters on stripped HTML.

> After installing and enabling Smart Trim, you should see a "Smart trimmed" option in the format dropdown for your text fields. With smart trim, you have control over:
>
> 1. The trim length
> 2. Whether the trim length is measured in characters or words
> 3. Appending an optional suffix at the trim point
> 4. Displaying an optional "More" link immediately after the trimmed text
> 5. Stripping out HTML tags from the field

---
Tags: 7, views
---


# Question
Title: Possible reasons why status report page is blank
I'm using Drupal 7.23 on my test site and since a couple of days the status report page is completely blank (no theme, no menu, nothing). No info shown at all. Other (report) pages are shown without noticeable issues.

Does anybody have an idea what could cause this? I have a almost similar 7.23 life site that shows this /admin/reports/status report perfectly.

Any log-file to check?

# Answer
> 0 votes
I didn't manage to get the php logging, but I do know now why this report page was blank. I had installed a not complete functioning module named Backup and Migrate Opencloud that needed Libraries 7.x-2.0 or higher. I was still on 7.x-1.0. After I updated to the latest libraries version the status report page showed up again.

---
Tags: log-messages
---


# Question
Title: Drupal admin themeing and customizations
I am looking into how I might customize the backend, but re-themed is not the ultimate agenda. Say for instance, 'admin/content', where I have filter options for various content types. Below that I have a table of content sections.

I want to completely replace the table and render the list in the left region of my template and use the content area for a WYSIWYG editor -- this is a common UI for basic CMS and I figured would be a good advanced learning experience.

I started poking through the code and quickly discovered I have no idea what content/form/blocks are in which regions in the admin section.

I found the module that implements the menu for 'admin/content' but that wasn't very helpful.

My question is: In the admin portion of a drupal setup how would I position custom block module content in the right region of a template when using block admin seems only to affect the front-end of the site?

# Answer
> 1 votes
1. Use https://drupal.org/project/admin\_views
2. Go edit a view and add a new display: block.
3. Register a new path in system:

a) using hook\_menu in your custom module OR

b) using https://drupal.org/project/empty\_page
4. Place that new created block in a region (edit also the paths where block should be displayed)
5. I'm not sure what you mean by WYSIWYG editor in content area - do you want to edit node or what?

a) If you used hook\_menu, point its page callback into a function which returns WYSIWYG editor OR

b) If you used a empty\_page you must create another block with editoror inside, and place it into content region

---
Tags: theming
---


# Question
Title: Contextual link in Product Display type to allow me to edit the referenced Product?
I have a Product Display node and it has the following contextual links: **Edit**, **Delete** and **Manage Display**.

The **Edit** link allows to edit the Product Display node. I need to add another contextual link to allow me to edit the product referenced by the product display.

Please take a look a this image:

# Answer
> 0 votes
This is a year old question, but worth answering I think.

You can use this hook (hook\_menu\_contextual\_links\_alter). The sample does exactly what you want. (I mean altering node's contextual links)

Here's an actual code I did. And it works for multiple products too.

```
    // Add a link to all contextual links for nodes of type product_display.
    if ($root_path == 'node/%' && $router_item['page_arguments'][0]->type == 'product_display') {

      // Loop through all products
      foreach ($router_item['page_arguments'][0]->field_product[LANGUAGE_NONE] as $element) {
        $product = commerce_product_load($element['product_id']);

        // Add your contextual link
        $links['edit_prod_'.$element['product_id']] = array(
          'title' => t('Edit @sku', array('@sku' => $product->sku)),
          'href' => 'admin/commerce/products/'.$element['product_id'].'/edit',
          'localized_options' => array(
            'query' => array(
            'destination' => current_path(),
          ),
        ),
      );
    }
  }

```

This will add contextual links like 'Edit HMWPB' or 'Edit POHPB'

---
Tags: commerce, navigation
---


# Question
Title: Access denied when I try to delete the user menu
How can I delete a user menu in Drupal 7? It throws me an access denied error, though I am logged in as user #1. What's wrong with it?

# Answer
You cannot delete any of the following menus; they come with the core. You can delete any menu you created yourself.

To disable them from displaying go to admin/structure/block.
> 0 votes

# Answer
maybe swithing for another source for secondary links at admin/structure/menu/settings is enough ?

OR

depending on theme you are using: go to theme's .info file and delete secondary links feature // change theme settings
> 0 votes

---
Tags: users
---


title: Site wide information data

text:
# Question
Title: Site wide information data
I'm using many information data on my site. I have some blocks with the main informations like address and phone numbers, but also I have some blocks with Quick Response code, geolocations (latitude, longitude) etc. There is about 15 this kind of details.

I wrote a simple module which allows me to define them in one place and save all of them as a one variable (array), so if I need any contact detail in any block template file, I just call e.g: $contact\_details\['qr\_code'\] to get it.

It's working and it is very useful, but I'm just wondering what do you think about that? Maybe I spent couple hours unnecessarily, because this kind of module already exists, or maybe I did not need any module at all, because for example: I should create a page with as many fields as I need, and then create my blocks with views?

I think many people would be intersted where to store all their contact informations and use them to build any content they need, for example blocks.

there is a small cutting of my module output:

# Answer
AFAIK, there is no module that does this for you.

I think this is a sensible approach. I am doing the same thing myself, storing the array with site-wide persistant data using the built-in `function variable_set()` to save, and then I use `function variable_get()` to retrieve the data.

I don't think saving site wide information in fields is a good idea.
> 1 votes

# Answer
The is no a bad solutions, when they actually work for you.

My approach would be:

1.Create a node type with all types of fields needed.

2.Create one node of that type and fill out with data.

3.Create custom module, with several blocks returning field\_view\_value() of fields that node has.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Is there a way to find out how many registered users logged in a given time period?
I am working on KPIs for my site and there are a few numbers I want to track. One of them is how many registered users actually logged in every month. Is there a way to get this number?

# Answer
You could count all User table rows in the database where the fields for "Last Access" and or "Last Login" are newer than one month old . You'd need to compare those timestamps to a timestamp for the start of the current month. You can find that with something like this or maybe it's as simple as:

```
$this_month_start = strtotime("-1 month");

```
> 1 votes

# Answer
I think this module is what your looking for User Stats. Cheers.
> 0 votes

---
Tags: 6, users, nodes
---


# Question
Title: Clickable preview of a youtube video in a Lightbox?
So I have been trying for a month now to get a nice gallery view working. It's a view displaying items of a custom "Gallery element" content type, that can contain either an image or a youtube video.

I want to have my gallery displayed as a 4x3 grid of thumbnails, that you can click on and get a lightbox output of the media file, wether it is an image or a video.

I managed to get the images working using the Lightbox2 module, but somehow the youtube videos need a little bit more working... So far I haven't managed to even see these videos in a lightbox. Either only an unclickable thumbnail appears in the gallery, or the full sized video if I remove the "Youtube Preview Image" display from the **manage file display** panel of **File types** in the configuration.

I do have checked the "Enable video support" checkbox in the Lightbox2 configuration, yet I cannot seem to find a way to display a video in those! One thing I wonder, is why don't I get the same field format "Lightbox2" options as for images?

# Answer
> 1 votes
Well! Thanks to this answer, I just found a workaround. I had to install the Video Embed Field module, and now I can display YouTube videos in a Colorbox popup window perfeclty fine. And Colorbox only, because Lightbox2 is still not supported by Video Embed Field.

# Answer
> 0 votes
You can do it easily with these modules (for Druplal 7)

* Media
* Media Video Embed
* Colorbox
* Embedded Media Field
* Media Colorbox

Maybe some more, such as requirements, but with those modules you can get the job done. You must install all of these module. The colorbox module needs the jquery.colorbox-min.js plugin.

What you do is this:

enable "colorbox load" of the colorbox config

create a new field for your content-type with an "embedded video" field

in the display setting for the field, choose "thumbnail with colorbox" of something to that effect

if it's not working then your missing a module or js plugin, or something is ill-configed, or you need to wait for the Media Internet field to fetch the thumbnail

---
Tags: views, media, javascript, files
---


# Question
Title: Is there a way to find out how many activated, registered users there are?
I am seeking to track some KPIs for my site, one of which is the number of activated, registered users there are on the site. Is there a way to get this number?

# Answer
You can query the `users` table, counting the number of rows where `status = 1`, which will give you the number of active user accounts.
> 2 votes

# Answer
The Drupal way would be to use Views to create a report for yourself (I would avoid querying any tables in the db directly.)

If you don't have the Views module installed, download and install it from http://drupal.org/project/views.

Once installed, create a new View on the User object. You will be able specify which fields you want to display, sort order, and filters.

Depending on which version of Views you are using (might be Views 2 in Drupal 6) you may also need to use an additional module called Views Calc in order to get the count of records returned: https://drupal.org/project/views\_calc
> 1 votes

---
Tags: 6, users, nodes
---


# Question
Title: How to append classes for dynamic terms in jquery?
I have installed a rating module, there I want to change the style. for that what I need is there is a css class called

```
$('.rate-widget-fivestar)

```

there are totally 3 widgets. the value of five star increses to 1,2,3 for three widgets respectively.

I want to add a class for each widget. (ie)

```
if($('.rate-widget-1))
 {  //class 1
 }
 if($('.rate-widget-2))
 {  //class 2
 }
 if($('.rate-widget-3))
 {  //class 3
 }

```

how can i acheive that in jquery??

# Answer
> 1 votes
I hope below code works for you.

```
if ($('.rate-widget-fivestar').hasClass('rate-widget-1')) {
  $(this).addClass('class1');
}

if ($('.rate-widget-fivestar').hasClass('rate-widget-2')) {
  $(this).addClass('class2');
}

if ($('.rate-widget-fivestar').hasClass('rate-widget-3')) {
  $(this).addClass('class3');
}

```

---
Tags: javascript
---


# Question
Title: A node reference is empty, although the multilingual support is enabled, and the node is translated
I just created a multilingual site (English-French) using Drupal 7 with the module Internationalization 7.x-1.4.
Everything is working fine except with the module References 7.x-2.0. For instance, I created a content type "School" so that each user is affiliated to a school (User A --\> School 1, User B --\> School 2, etc.), meaning I simply added a node reference to "School" in the user account settings. But here is the problem: if a user chooses a school on the English version of the site it won't remember the school choice on the French version (the node reference becomes empty) and vice versa.

How do I solve this?

I did enable the multilingual support for "School" with translation.

# Answer
Have a look at this.

http://www.ostraining.com/blog/drupal/multi-lingual-drupal/
> 0 votes

# Answer
The problem is that a node reference can only reference content in the same language. What you need to do is provide a translation of the school node in both English and French in order for both sides to see it. Also dont forget to clear cache.
> 0 votes

# Answer
You may try entity reference module,and the problem will be fixed.
> 0 votes

---
Tags: nodes, i18n-l10n
---


# Question
Title: "Cannot modify header information - headers already sent by (output started at codefolder\modules\user\user.module:1)"
i am using drupal 6, mysql 5.5 on apache 2.2 it is working fine. but when i migrated my code on xampp1.7.3(contain apache2.2 and mysql 5.5). it gives issue and error.

> warning: Cannot modify header information - headers already sent by (output started at codefolder\modules\user\user.module:1) in codefolder\includes\session.inc on line 99. warning: session\_regenerate\_id() \[function.session-regenerate-id\]: Cannot regenerate session id - headers already sent in codefolder\includes\session.inc on line 102. Blockquote

and after login pages containing urls like localhost/node/55 shows white pages. while without login it works fine.
while searching on google i found this issue might be due to header but i haven't used any header redirect in my .tpl.php files.

# Answer
This was issue due to verision of XAMPP.
Don't know why but on one friend suggestion I started using XAMPP 1.7.4, and it resolved error, previously i have used XAMPP 1.8.3 and then XAMPP 1.7.3.
> 0 votes

# Answer
Check that you don't have any ending php tags at the end of your php files. Sometimes whitespace (spaces, tabs, newlines) will sneak in at the end of the file after the tag and cause php go into html mode and send the headers too early.
> 1 votes

# Answer
This is mostly Found in php bust as @Kari Kaariainen said do it and another thing is that go to the top of that page and make sure there is no white space.
> 0 votes

---
Tags: 6, sessions
---


# Question
Title: How to pass variable from module to other theme
I would like to pass variables from my custom module to some of my custom themes. The most tutorials are concerning using hook\_theme function but as I understand, it works only for creating new theme functions (new tpl files) inside module, where the hook\_theme is defined. But I would need to alter theme definition of some custom theme in /sites/all/themes folder from my custom module /sites/all/modules

In particular, I need to add a variable into thems's html.tpl.php file. I would like to use custom module to define variable, because I need to make database queries to fill variable with value, and db queries should not be done in theme.

I have tried implementing hook\_theme\_registry\_alter. I have tried to add variable like this:

```
function mymodule_theme_registry_alter(&$theme_registry) {
$theme_registry['html']['variables']['test'] = 'test value';
}

```

but I got error "Undefined index: #children in template\_process\_html"

Can anybody help?

# Answer
For your needs, you'll need to create a custom module and implement `hook_preprocess_html`:

```
function hook_preprocess_html(&$vars) {
  // This is where you do the db query
  $myvar = _get_my_var();

  // After this $myvar will be available in html.tpl.php
  // where you need to print it out
  $vars['myvar'] = $myvar;
}

```
> 7 votes

---
Tags: 7, theming
---


# Question
Title: How can I check whether cck field's content is changed in node_update hook?
I want to check whether cck field's content is changed in node\_update

I tried the same with following conditions but it gave me incorrect result.

```
if($node->field_event_type['und'][0]['value'] == $node->original->field_event_type['und'][0]['value']){
   echo "same";
}else{
   echo "changed"
}

```

Thanks.

# Answer
> 2 votes
From documentation:

> Note that when this hook is invoked, the changes have not yet been written to the database

So you can use

```
$old_node = node_load($node->nid);

```

Then simply compare `$node` provided to a hook with `$old_node` obtained from database.

---
Tags: nodes, updating
---


# Question
Title: What are the different ways I can export permissions from a preconfigured Drupal site
I have a site that I need to export permissions from and import into version-controlled code. We aren't using feature, strongarm etc, so although I know a lot of people will say these are the go to solutions, I need to look at alternatives. Are permissions stored as variables in the site or otherwise? I would I export and import variables into an install profile or in a module?

# Answer
> 3 votes
This module(Export roles and permissions) allows you to exports roles and permission by generating a hook\_install implementation

> This module allows you to generate a hook\_install() implementation that creates the chosen roles with their associated permissions. The main purpose for creating this module was to transfer roles from a local dev machine to a remote stage/live server.

---
Tags: 7, users
---


# Question
Title: Can Apache Solr Search allow a user to search 'within' current results?
I'm looking for a way to allow a user to search 'within' current Solr search results (not search api solr results).

Is there existing functionality that provides this?

If I need to implement a module to do so, so be it; recommendations for what hooks to implement in that case would also be helpful.

Edit:

Re. amateurbarista's comment. I'm wondering if there is a way to make a second query against the results of a first. I don't think Facets allow me to do this, is that so?

For example suppose my first search query returns 10 nodes. I'm asking what it would take to allow a second query to search only within those 10 nodes.

# Answer
> 0 votes
This is from my experience using Database Search not Solr but it might work.

I'm also not sure it's exactly what you're looking for but it might be a starting point.

1. Clone your view, but keep the URL the same.

This allows you to run two exposed forms both of which re-direct to the same view. So I have one on my homepage and then one on my search results page. When you search from the home page the values are automatically populated into the second exposed form when you land on the results page.

Because the exposed forms are different this means you can show more fields on the exposed form on the search results page and because it remembers the first search, technically, you're searching within the original search.

---
Tags: search
---


# Question
Title: Cannot fetch form_state['values'] of text field from dynamically created Ajax fields
I have a custom form with dynamically generated fields. I am unable to fetch values from these fields using form\_state\['values'\]. Code is attached below. I have been struggling with this since two days, but have not found anything that can fix the issue. Please help!!!

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

$form['#tree'] = TRUE;

$form['names_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('People coming to the picnic'),
  '#prefix' => '<div id="names-fieldset-wrapper">',
  '#suffix' => '</div>',
);

if (empty($form_state['num_names'])) {
  $form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
);
if(!empty($form_state['values'][$i]) &&  ($form_state['values'][$i] !='')) {
drupal_set_message($form_state['values'][$i]);//<-- This statement never gets executed. Also cannot fetch the value of $form_state['values'][$i]
}

}
 $form['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('ajax_example_add_more_add_one'),
  '#ajax' => array(
  'callback' => 'ajax_example_add_more_callback',
  'wrapper' => 'names-fieldset-wrapper',
),
);
if ($form_state['num_names'] > 1) {
  $form['names_fieldset']['remove_name'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#submit' => array('ajax_example_add_more_remove_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
  ),
);
}
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
);

return $form;
}

function ajax_example_add_more_add_one($form, &$form_state) {
 $form_state['num_names']++;
 $form_state['rebuild'] = TRUE;
}

function ajax_example_add_more_callback($form, $form_state) {
 return $form['names_fieldset'];
}

function ajax_example_add_more_remove_one($form, &$form_state) {
 if ($form_state['num_names'] > 1) {
   $form_state['num_names']--;
 }
 $form_state['rebuild'] = TRUE;
}

```

# Answer
You have used `$form_state['num_names']` instead of `$form_state['values']['num_names']`.

Please try to update and see.
> -2 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Adding a Custom Solr Search Block that restricts search to one content type
I have Apache Solr search 7.x-1.1 installed and working as my main site search.

I would like to add a search block to one page that allows the user to search, but restricts the results to a single content type. The new search block should be placed in a different location to the main site search, and the two should be able to co-exist on the same page.

What is the simplest way of achieving this please?

# Answer
> 3 votes
Once i stumbled upon Custom Search module I found this was easy to achieve. Install the Custom Search module and when configuring the module click on the 'search blocks' tab. Change the number of blocks to the number of additional search blocks you require. I needed two - each one searching by an different content type.

Now go to manage your blocks. Find the new search blocks within the list of block. Click 'configure' for search block to set the options and which content type to restrict to. Note that if you choose more than one content type you can choose whether to add radio buttons, or a drop down etc to allow the user to select what they will search for. This module also has some other interesting features which are outside the scope of this question - check it out.

---
Tags: 7, search
---


title: can't unassign role from user

text:
# Question
Title: can't unassign role from user
I am working on a site which uses someones custom module which makes some modifications on the user account page as well as his profile pages.

On this site, I registered myself as a user and logged in and found that I was assigned to all roles, even administrator. When I tried unclicking the checkboxes on the user page to unassign roles, it didn't work, the roles stayed the same. I tried this while logged in as the user himself and also as the admin.

What types of things could be causing this issue? Where should I look?

# Answer
As per my understanding, there are custom modules from which it is updating.

Try searching hooks like `hook_user_insert(&$edit, $account, $category)` and `hook_user_update(&$edit, $account, $category)` from custom modules. I hope they might have written a piece of code to update the roles.
> 1 votes

---
Tags: 7, users
---


title: Hooking into page not found event

text:
# Question
Title: Hooking into page not found event
My question is similar to How to redirect user for specific pages not found and some what useful discussion here: https://drupal.org/node/344960 and redirect missing pages to another site

I've a job site and I want to redirect using 301 all expired jobs to one common page. All expired jobs are deleted. To make it easy the job urls have unix timestamp suffixed in some pattern so that I can recognize a url as expired job.

Whenever a page request comes, I want to let it go normally but if page is not found then only I want to check the url with specific pattern and then redirect 301 to common page if it is url of expired job.

Is there any way to do it?

# Answer
> 1 votes
Go to Home » Administration » Configuration » System and set Error pages to some not used yet value, like `http://localhost/403` and `http://localhost/404`, or `http://localhost/forbidden` and `http://localhost/not-found`. Then create a custom module. Implement `hook_menu()` to provide these pages. Use all logic you need in page callback function.

---
Tags: 7, uri
---


# Question
Title: is there any Function to extract all the view modes for specific node?
Is there any function which can give you all the types of view modes available for specific node? Also is there any direct(UI) way to check it ?

Is going to edit-\>manage\_display the only way to get the view modes ?

# Answer
> 0 votes
The code below will give me the list of view modes

```
$entity_info = entity_get_info('node');
$list_of_view_nodes = array_keys($entity_info['view modes']);

```

---
Tags: 7, views, nodes
---


# Question
Title: How to call a function when a node is being viewed?
Whenever I view a node page, I want to call a function but I'm not sure how to do that.

I was thinking I should use `hook_menu()` and declare the path as node/%, and attach a callback function to that path. Is that the right way, or is there a correct/better way?

# Answer
You can implement `hook_node_view()`

> Act on a node that is being assembled before rendering.

e.g.

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'the_type' && $view_mode == 'full') {
    // Call your function here.
    my_function($node);
  }
}

```
> 6 votes

# Answer
Rules module can also react to URL access. You can specify an *action* supposed to happen on *event* if *condition* is true.
> 2 votes

---
Tags: 7, nodes, routes
---


# Question
Title: Adding a date time field value within a node programmatically
```
 [field_download_time] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => 2012-11-27 09:38:00
                                [timezone] => America/Phoenix
                                [timezone_db] => America/Phoenix
                                [date_type] => datetime
                            )

                    )

            )

```

What I see for a field\_download\_time is given above.. I am adding nodes programmatically so the code for following field is as given below

```
 $download_node->field_download_time[]['value'] = date('m-d-Y H:i', REQUEST_TIME);//--?

```

I don't get an error on running the above code but **the value of current date** is not displayed

But When I run the following code given below I get an error **THE ERROR** :
**Actually the code is such that when u go to the link it downloads a file .Basically the error is that file is not downloaded.**

```
  $download_node->field_download_time['und'][]['value'] = date('m-d-Y H:i', REQUEST_TIME);//--?

```

# Answer
```
[0] => Array
                            (
                                [value] => 2012-11-27 09:38:00
                                [timezone] => America/Phoenix
                                [timezone_db] => America/Phoenix
                                [date_type] => datetime
                            )

```

As seen above, the error was occuring due to improper date format So when I changed the date format to **`date(Y-m-d\TH:i:s, REQUEST_TIME);`** the `$download_node->field_download_time['und'][]['value']` did not gave any error .
> 3 votes

# Answer
Try this :

```
$mynode->field_download_time[LANGUAGE_NONE][0]['value'] = "2012-11-27";
$mynode->field_download_time[LANGUAGE_NONE][0]['timezone'] = "America/Phoenix";
$mynode->field_download_time[LANGUAGE_NONE][0]['timezone_db'] = "America/Phoenix";
$mynode->field_download_time[LANGUAGE_NONE][0]['date_type'] = "datetime";

```
> 1 votes

---
Tags: nodes
---


# Question
Title: Views one to many relationship, display many records in columns
I have a View with a one to many relationship. ID and Session are in my main table, and "mark"'s are rows in a custom table. When I look up a single ID, I get this result because of the 'many' results in the custom table.

ID | Session | mark

15 | Spring 2013 | 16

15 | Spring 2013 | 3

15 | Spring 2013 | 5.5

My desired result is:

ID | Session | mark 1 | mark 2 | mark 3

15 | Spring 2013 | 16 | 3 | 5.5

# Answer
> 1 votes
How about using the viewsfield module? You can try solving your problem by creating two views A and B, such that -

1. View A excepts an argument 'ID' and lists all the marks associated with it, by having only the 'marks' field included for display/output.
2. View B has an ID field, a session field, and a viewsfield. In this third field the view A is embedded.

I hope this helps. I have not tried this, but I am reasonably sure it should help if the module is doing what it promises to do.

# Answer
> 1 votes
I advice you to use a custom php method inside each mark column

See Views php module

Your method could return the right value based on the delta index :

```
// in the custom php field (view)
return _my_method( $data->field_mark, 1 ); //(value, delta)

//do it 3 times, in each column
return _my_method( $data->field_mark, 2 ); //(value, delta)
return _my_method( $data->field_mark, 3 ); //(value, delta)

// in your module
function _my_method( $marks, delta ){
  return isset( $marks->['und'][ delta ]['value'] ) ? $marks->['und'][ delta ]['value'] : NULL;
}

```

# Answer
> 0 votes
Have you tried grouping your fields under the Format settings?

---
Tags: 6, views
---


title: Change label in views php

text:
# Question
Title: Change label in views php
I am using the views php module and want a custom label.

The label field doesn't allow php to be entered, how would I go about changing the label?

# Answer
> 1 votes
In the view UI, choose a php field type

and your custom php code can be entered here:

---
Tags: views
---


# Question
Title: How do I get raw urls with contextual filters to work with views in Drupal 7, when i'm using panels, and panels everywhere?
I've scoured the site for solutions, and I have no idea what's going on. I have drupal 7 running off a local installation (mamp), and my site is structured with Panels and Panels Everywhere. I have a view that is in the sidebar, and I want it to pull up anything tagged with the name of the page. (for example walldamp/drupal/architecture would pull up architecture, or walldamp/drupal/acoustics would pull up all nodes tagged with acoustics).

The preview works just fine when I type in a tag, but it just won't work with the sites. If anyone could help, I'd really appreciate it.

I'll post a picture as soon as I get more reputation, but currently my settings are as follows for the contextual filter.

* Configure contextual filter: Content: Has taxonomy term ID
* Provide Default Value
* Raw Value form URL
* Path Component: 3
* Exception Value: All
* Specify Validation Criteria
* Validator: Taxonomy Term
* Filter Value Type: Term Name converted to Term ID
* Transform dashes in url to spaces in term name filter values
* Action to take if filter value does not validate: Display a summary.

It's just displaying the summary in my sidebar, no actual blog posts or images like in the preview. Any help would be appreciated.

# Answer
Try using argument 2 (URL arguments start at 0 not 1) as opposed to argument 3. A Failing that, disable the validation, oftentimes the validation is screwy and excludes valid content. Start with as little filtering, validation, exclusion, etc. to make sure you're getting data and tighten the parameters from there.
> 1 votes

# Answer
If the preview works when you type in the tag, then you may need to switch the Filter Value Type to Term ID rather than use the term name. This is often because Pathauto settings are not the same as Drupal's internal path. Try the above change to the filter value and then check Devel on your pages, you should have a 'tid' variable that is populated with the appropriate term ID.
> 0 votes

---
Tags: views
---


# Question
Title: Possible to alter user account status options on user_register_form?
I'm looking to alter user\_registration behavior to allow certain users to reopen their closed or blocked accounts but not users who have been explicitly banned. As such, I'm looking to modify the current form element for \['account'\]\['status'\] from just allowing 'Blocked' and 'Active' to something like this

> $form\['account'\]\['status'\]\['#options'\] = array(t('Blocked'), t('Active'), t('Banned/Dead to Me'));

This is an easy form\_alter hook to execute and Drupal will add the new value ('2') in the users table but it doesn't know what to do with it in other functions, ex. on the admin/people page, it doesn't recognize the new value:

> Notice: Undefined index: 2 in user\_admin\_account() (line 226 of /public/modules/user/user.admin.inc).

Is there another way to customize the user status options or is this a protected core value? Are there already modules that add new user status options that I could look at as a model?

# Answer
Finished working through the implications of this and have confirmed it is not possible to alter the user\_status fields through Drupal without causing other complications through other modules -- the 0/1 logic for users is too ingrained in core to overcome.

I've addressed the requirement through a number of other Drupal hooks that work alongside the user module, will be releasing user\_reopen module shortly to community.
> 0 votes

---
Tags: 7, users
---


title: Why doesnt my JavaScript run?

text:
# Question
Title: Why doesnt my JavaScript run?
I'm trying to change the background color of a Colorbox (in which nodes are presented) based on the clicked node. See https://stackoverflow.com/questions/18173943/change-background-color-of-colorbox-using-js-based-on-node-id?noredirect=1#comment26626591\_18173943

This doesn't work, although I've confirmed it working for others, and on Fiddle: http://jsfiddle.net/nevster/YSgMx/

Why doesn't this work?

The site is built on latest Zen and I've added the JavaScript code in the script.js file (inside the function that says I should put it there) and added the file in the theme .info file.

JavaScript:

```
$(document).ready(function () {
$(".colorbox-color").colorbox({
    onComplete: function(){
        var bg = $.colorbox.element().data('bg');
        $('#cboxWrapper').css('backgroundColor', bg);
        $('#cboxLoadedContent').css('backgroundColor', bg);
    }
});
});

```

I'm using Drupal 7 with Views to show the nodes, together with Colorbox and Colorbox Node.

# Answer
You shouldn't include the ready function, the latest Zen wraps your script in a custom behavior. Try putting your code directly inside the custom behavior that is already included in the script.js file.

```
(function ($, Drupal, window, document, undefined) {

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

    $(".colorbox-color").colorbox({
      onComplete: function(){
        var bg = $.colorbox.element().data('bg');
        $('#cboxWrapper').css('backgroundColor', bg);
        $('#cboxLoadedContent').css('backgroundColor', bg);
      }
    });

  }
};

})(jQuery, Drupal, this, this.document);

```
> 4 votes

# Answer
Instead of changing the background color on the *onComplete* event, try to add it on the *onOpen* event. Maybe the *onComplete* is never called because of a load error ...

```
$('.colorbox-color').colorbox({
    onOpen: function(){
        var bg = $.colorbox.element().data('bg');
        $('#cboxWrapper').css('backgroundColor', bg);
        $('#cboxLoadedContent').css('backgroundColor', bg);
    }
});

```
> 0 votes

# Answer
Its unclear in your post how you are rendering the images (ie, views, display suite, etc.) so I'll give a generic (static) example for a html page or block. Also, I'll assume you're using the colorbox module to supply the library to Drupal.

1. Using your JSFiddle example (http://jsfiddle.net/UFtrK/112/), I made a basic page with Full HTML as the text format. The only thing that differs is the classes. For example:

```
<a class="colorbox-color colorbox inline" data-bg="#ccf" href="http://www.jacklmoore.com/colorbox/content/ohoopee3.jpg" title="On the Ohoopee as an adult"><img src="http://www.jacklmoore.com/colorbox/content/ohoopee3.jpg"/></a>

```

2. In `scripts.js` I added the following code in between

`(function ($, Drupal, window, document, undefined) {`

and

`})(jQuery, Drupal, this, this.document);`

```
Drupal.behaviors.cbox = {
      attach: function (context, settings) {
        $(".colorbox-color").colorbox( {
          rel:'colorbox-color',
          onComplete: function(){
            var bg = $.colorbox.element().data('bg');
            $('#cboxWrapper').css('backgroundColor', bg);
            $('#cboxLoadedContent').css('backgroundColor', bg);
          }
        });
      }
};

```

3. Go to admin/config/media/colorbox and make sure that "Enable Colorbox inline" is selected.
4. Clear your cache and give it a try!
> 0 votes

# Answer
Have you tried using `context`?

```
$('#cboxWrapper', context).css('backgroundColor', bg);

```

It makes sure your CSS is ran with the new markup.

Did you check that your selector actually works?

```
console.log($('#cboxWrapper')); // Then check your console

```
> 0 votes

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


# Question
Title: How to place a users role after username in Forums
On my site, i have the Forums module enabled.

Please is it possible to put a users role in parenthesis next to the users username in the Forums?

For example "Brian (Student)" and David (Teacher)".

Thank you.

# Answer
If you can find the display in views.

You can add a "User: Roles" Field. Mark it as excluded.

Then

Under "user: name" field. select "Rewrite the output of this field" and include the \[rid-role\] token in the username.

Be sure to add the "role field" before "user field" otherwise the token will not be available.

Example
> 1 votes

---
Tags: views, nodes
---


title: Multipage form progress indicator

text:
# Question
Title: Multipage form progress indicator
How would I go about adding a **progress indicator** to my multi page form?

So for example, I would like to have a Heading at the top of each of the form pages/stages. I would like them all to be displayed at all times, but with a "status box" or something similar next to each status, which changes once a certain stage has been completed (all the mandatory fields have been populated).

Any advice on how to achieve this?

# Answer
> 2 votes
Taken from Bala's answer. I had to do a great deal of work on the code before it worked so I thought I'd paste my corrected code here:

Copy sites/all/modules/webform/templates/webform-form.tpl.php to your sites/all/themes/ folder so that you don't hack the original tpl.

In the sites/all/themes//webform-form.tpl.php copy add the code:

```
<?php
    if($form['details']['page_count']['#value'] > 1){
        $output_pagenum = '<div class="page-count">Page '
            . '<span class="actual">' . $form['details']['page_num']['#value'] . '</span>' . ' of '
            . '<span class="total">' . $form['details']['page_count']['#value'] . '</span>';
        echo $output_pagenum . '</div>';
        // End of custom code
    }

  // Print out the main part of the form.
  // Feel free to break this up and move the pieces within the array.
  print drupal_render($form['submitted']);

  // Always print out the entire $form. This renders the remaining pieces of the
  // form that haven't yet been rendered above.
  print drupal_render($form);

```

Then in your js file:

```
//Progress bar for webforms.
    var actual = $('.actual').text(); //Get the value of the actual page.
    var total = $('.total').text(); //Get the value of the total of pages.

    if(total > 1) { // check if is a single page form and the webform has no breaks
        var percentage = (actual/total)*100; //Divides the actual value between all the pages.
        percentage = percentage + '%';
        var progressbar = '<div id="progress-container" style="background:#c2c2c2;">'
         + '<div id="progressbar" style="margin-top:10px;background:#762C39;min-height:15px;"></div></div>';

        $('.page-count').append(progressbar);
        $('#progressbar').css('width', percentage); //Depending on which page break youre on modifies the width of the progress bar.
    }

    //End of Progress Bar

```

# Answer
> 1 votes
Open sites/all/modules/webform/templates/webform.tpl.php and add this code

```
<?php
//Add this ..
$output_pagenum = ‘<div>Page ‘
. ‘ActualPage”>’ . $form['details']['page_num']['#value'] . ‘‘ . ‘ of ‘
. ‘TotalPage”>’ . $form['details']['page_count']['#value'] . ‘‘;
echo $output_pagenum;
// End of custom code

// Print out the main part of the form.
// Feel free to break this up and move the pieces within the array.
print drupal_render($form['submitted']);

```

Add the below code to script.js file, by adding scripts\[\] = js/script.js in your .info file and place the script.js in your theme folder -\> js folder -\> script.js

```
(function ($, Drupal, window, document, undefined) {
$(document).ready(function() {
//Progress bar for webforms.
$actual = jQuery(‘.ActualPage’).text(); //Get the value of the actual page.
$total = jQuery(‘.TotalPage’).text(); //Get the value of the total of pages.
$percentage = ($actual/$total)*100; //Divides the actual value between all the pages.
$percentage = $percentage+’%';
$progressbar = ‘<div id=”progressbarContainer” style=”background:#c2c2c2;”><div id=”progressbar” style=”background:#a3a3a3;min-height:15px;”></div></div>’
jQuery(‘.page-count’).append($progressbar)
jQuery(‘#progressbar’).css({‘width’: $percentage}); //Depending on which page break youre on modifies the width of the progress bar.
// check if is a single page form or the webform has no breaks
if($actual == 1 && $total == 1) {
$(‘.page-count’).remove();
}
//End of Progress Bar
});

})(jQuery, Drupal, this, this.document);

```

Taken from the source Progress bar webform with page breaks Drupal 7

---
Tags: webforms
---


# Question
Title: In the File Entity module, what is the difference between "Manage display" and "Manage file display"?
As per the screenshot, what is the difference between "Manage display" and "Manage file display"?

# Answer
Manage display is the core page to manage the display of fields for various view modes.

The Manage file display tab is provided by the File Entity module; the page callback for that tab is `file_entity_file_display_form()`, whose description is:

> Form callback; presents file display settings for a given view mode.

So the difference is that display settings that relate to the file entity module have been separated out from the core Manage Display form, on a per view-mode basis, and that extra tab is where you set them.

As noted in the comments this is covered in a lot more detail as part of a broader question
> 2 votes

---
Tags: media, files
---


# Question
Title: Panels cache terminology- what's the difference between caching by argument vs. by context?
I'm trying to learn how to set up Panels caching. I watched a video on mastering Drupal caching and I have the book by Earl Miles on Panels and Views, *Drupal's Building Blocks*, but unfortunately there's not a chapter specifically on caching.

So, I have a panel that overrides the user profile, and on this panel I have a variant that has a number of views content panes. I would like to cache these content panes per user profile displayed, since obviously they should be different for each user who is viewed.

Each of these content panes has a **Contextual filter** on *Content: Author UID*.

The value is supplied to Panels by the *Argument input* option in Views, for which the **Content: Author uid source** is set to *From context* and **Required context** is set to *User ID*:

In Panels, on the **Simple cache** configuration screen, for the **Granularity**, I can choose *Argument* or *Context*, and the help text is this:

> If "arguments" are selected, this content will be cached per individual argument to the entire display; if "contexts" are selected, this content will be cached per unique context in the pane or display; if "neither" there will be only one cache for this pane.

But in Views, the option is called *argument input* and the value I chose was *from context*. So am I dealing with an argument or a context?

If possible, both a general answer describing the difference between argument and context in this case and a specific answer to my question would be fantastic.

# Answer
Disclaimer: I usually find that the setup is simple enough that the distinction isn't necessary, thus I must admit my practical experience is limited, and I could be wrong below.

`Arguments`, are based on the URL. `node/5` gets cached separately from `node/7`, because 5 is different from 7. `node/5/7`, if you where to have such a path, is yet another cache.

`Contexts`, are generally derived from `Arguments`, and in the examples above, it's very likely that the caches would be exactly the same, regardless of which cache option one would pick. However, `Contexts`, can also come from (at least) three other sources, `Relationships`, manually defined ones, and the special case, the logged in user.

If your context is both a node from the URL, and a user pulled from an `entity reference` on the node, then your context has two unique entities, or two contexts, but only one argument.

So one chooses `Context` or `Argument` depending on whether you want the cache to take any "extra" contexts into question, or not.

> But in Views, the option is called argument input and the value I chose was from context. So am I dealing with an argument or a context?

Unfortunately the terminology isn't exactly the same between the two modules. Panels calls dynamic pieces of the URL arguments, and it creates contexts from those. Views, means something closer to a function argument, when it refers to arguments, and in this particular case, it will derive the argument from a context, passed in by Panels.
> 7 votes

---
Tags: panels, caching
---


# Question
Title: Is the Panels simple cache lifetime a minimum or maximum?
In Panels, one can configure caching for blocks/content panes/etc. The built-in method is **Simple Cache**, for which two settings can be configured: **Lifetime** and **Granularity**.

For **Lifetime**, one can choose a value from *15 sec* to *7 days*.

Is this lifetime a minimum or a maximum? In other words, if I set the **Lifetime** to *7 days* for a content pane, will that content pane be cached for 7 days no matter what? Or will it be cached for 7 days unless it is updated?

# Answer
> 5 votes
Simple cache, is unfortunately not very clever, hence the name "Simple".

A 7 day cache will be cleared when the first request past the 7 day mark occurs, so it is the minimum lifetime of the cache.

The reason that it isn't smarter than that, is probably that content panes can come in a great deal of forms, and it's not trivial to implement a generic solution to knowing "When something was updated".

Continuing on that, I've implemented Panels cache which attempts to be smarter, but is limited to Content panes based on an entity context. It considers the cache lifetime to be infinitely long, but clears it when the entity that is the context is updated.

It's not terribly well tested, but it was written for a paying client that had it running in production without issues or complaints at least for the months I worked with them.

---
Tags: panels, caching
---


# Question
Title: Apache Solr Framework with Views (for Facet Search)
**What I want**

I want to use the Apache Solr Search to: 1. built a Global Search with a customized Search Results Display 2. built a Facet Search for specific content types

**Problems**

Currently I'm trying to use the Apache Solr Framework Module: https://drupal.org/project/ApacheSolr

So my first question: As far as I can see, this module has no native integration with views, right?

As a result I installed the "Apache Solr Views Integration" Module: https://drupal.org/project/apachesolr\_views

But when I create a view of the new typ "Apache Solr .." I am experiencing different problems: 1. Not all fields are available (for the facet search I only need to display specific fields) 2. It is not possible to filter the Content Type (needed for the facet search) 3. It is not possible to set the ouput to "rendered entity" (needed for the global search!)

Does anybody know to achieve the result that I want? What are your expieriences with the Apache Solr Framework? How do you integrate this with views?

# Answer
> 1 votes
I have typically achieved this type of thing using the Search API module which provides ability to select which fields are indexed and thus exposed to Views in turn along with Apache Solr integration.

The Search API provides a great base onto which to build very powerful search applications.

# Answer
> 0 votes
I believe you can use the search API to search attachments. search\_api\_attachments module

Seems that Search API is the prefered way to display search results within Views

> If you want a full integration with Solr and Views you should use Search api with Search Api Solr. see this answer

I've tried to use https://drupal.org/project/apachesolr\_viewson a recent project but it's lack of a way to display spelling suggestions in the View page has complicated that for me.

The choice between Solr and Search API backed by Solr can be difficult depending on your requirements, for example do you need to index Multilingual content ?

---
Tags: views, search
---


# Question
Title: How to create a panel for a argument path
How do you create a panel for a url that looks like product/%nid/title.

* The Title should be from the node.
* The node paths have already been setup with pathauto.

What i have so far in my panel

The panel doesn't get used on the page

# Answer
Separate answer. The original one still contains useful information, so I don't want to edit/remove it, but it doesn't answer your edited question.

I believe you are confusing "What the end users sees in the address bar", with "How Drupal internally handles URLs". Those are often not the same.

In your Panel page, you don't need to include the title argument at all, whether the title is part of the shown URL or not is a problem for Pathauto to handle. Page manager only cares that it's a node that is being displayed, so internally it uses the path `node/X`.

So the simple answer is, just use the already provided default "Node view" page, and you'll be on your way.
> 1 votes

# Answer
I'm not sure what you are after. You just want the URL to look right, then all you need is Pathauto.

What you are asking however, is essentially how to tell Page manager to load content based on the title of the content. That *could* make sense, if it wasn't because you already load it by the ID, so loading it again would just be redundant.

If that's *really* what you want though, here goes:

Page manager doesn't know how to load nodes by title, so you will need to explain to it.

This is a called a `Context`.

See What are Ctools plugin (content type, access, etc), and how does one create them? for the basics of how to implement a ctools plugin. Look at the existing contexts in the ctools examples directory, and creating the context shouldn't be to hard.
> 1 votes

---
Tags: panels
---


# Question
Title: In the File Entity module, what is the purpose of multiple "Enabled displays" and "Display precedence order" for a single display mode?
In the File Entity module, what is the purpose of multiple enabled displays and Display precedence order for a single display mode? Or what is the use case where I would need to provide multiple ones and define precedence of one over another?

There is little to no documentation on File Entity (understandably as it is still under heavy development), and I am trying to wrap my head around it a bit more. I just can't think of a use-case where I would need more than one "display" for a single "display mode", where the first would not "validate" and therefore look at subsequent ones that are defined.

# Answer
> I just can't think of a use-case where I would need more than one "display" for a single "display mode", where the first would not "validate" and therefore look at subsequent ones that are defined.

It's not a feature that I expect it used very much, but that is exactly the purpose.

An example, where one looks at the user agent, could be:

Let's say you're showing a video, a video player is your primary option.

Then there's a user agent that you recognize as a screen reader. Suddenly, showing video doesn't make sense. However, the audio still does, so you fall through the first option, to your second, which is an audio player, that only pulls in the audio stream, significantly reducing the bandwidth usage for both server and client.

Finally, a really low powered mobile device comes along, and then you simply default to displaying an image of the videos first frame, together with a link "Mail me this video", making it convenient for the user to find the video again when using a more powerful computer.
> 4 votes

---
Tags: media, files
---


title: restrict blocks in multilanguages site

text:
# Question
Title: restrict blocks in multilanguages site
I want create a multi language website, I have some problems,
according my search about menu link in multilanguage drupal website ( I did this job in some year ago but forget it(because some personal life change I abandon drupal form 1 year) ) it is better to create seperate menu type and put them in menu block (with menu block moudle ).but I have some problesm,
first How can I restrict block shows in only specify language , I want did it in cofiguration of block in **pages** section limit it by something like ***en/**** but in front page of my two languages not work correctly, please tell me how can I restrict blocks in languages.

# Answer
You can use The Block languages module, part of the Internationalization (i18n) package allows you to configure for which languages each block is visible. The settings for visibility per language are provided under Visibility Settings via the Languages tab when configuring a block.
> 1 votes

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


# Question
Title: how to render a template inside a template?
I have entity Car which has a node reference of another entity: Review

Car has a custom .tpl file `node--car.tpl.php` and reviews have there own .tpl files "node--reviews.tpl.php"

when i try to render the reviews of the Car inside the `node--car.tpl.php` the reviews does not render using their own .tpl files,

i am using `render()` drupal function

can someone explain me why?

EDIT:

Heres the code which fetches the reviews:

```
function mymodule_get_reviews( $nid, $full = false ) {
    $field = 'field_car_reference';
    $sql_query = 'SELECT DISTINCT entity_id AS reference FROM {field_data_' . $field . '} WHERE ' . $field . '_nid IS NOT NULL
        AND ' . $field . '_nid = ' . $nid;

        $queryObj = db_query( $sql_query );

        $type = 'review';
        $nodes = node_load_multiple($queryObj->fetchCol('reference'));

    $reviews = array();

        if( !empty( $nodes ) )
        {
            foreach( $nodes as $nid => $node_review )
            {
                    if( $node_review->workbench_moderation['current']->state == 'published' ) {
                        $node_review = node_show( $node_review );
                        $reviews[] = $node_review;
                    }
            }
        }
    return $reviews;
}

```

the function is called as:

```
$reviews = mymodule_get_reviews( $node->nid );
if( !empty( $reviews ) ) {
  echo render( $reviews );
}

```

# Answer
> 0 votes
When a template is not being applied, the first thing to always check for is the filename of the template :)

Make sure it matches the machine name of the content type.

---
Tags: 7
---


# Question
Title: Is it possible to remove Route objects from a RouteCollection object?
When I look at the code used for the method handling a RoutingEvents::DYNAMIC event, which receives a RouteBuildEvent object, I notice the code is always similar to the following one.

```
$collection = $event->getRouteCollection();
$route = new Route("$path/display", array('_form' => '\Drupal\field_ui\DisplayOverview') + $defaults, array('_permission' => 'administer ' . $entity_type . ' display'));
$collection->add("field_ui.display_overview.$entity_type", $route);

```

Since the RouteCollection class defines the RouteCollection::remove() method, would not removing routes from the collection be possible? I was thinking of removing a route to redefine it.

# Answer
There is also a `RoutingEvents::ALTER` event, which runs afterward.

You can think of the difference between `RoutingEvents::DYNAMIC` and `RoutingEvents::ALTER` as similar to the difference between `hook_menu()` and `hook_menu_alter()`.

There is a Views issue that discusses *replacing* routes, as opposed to removing and adding them, perhaps follow their example.
> 5 votes

---
Tags: 8, routes
---


# Question
Title: Image field: mark an image as a "cover photo" with a radio button
In a given content type, I have three **Image** fields, each of them set to **Unlimited** cardinality. It's like a little **gallery** with 3 fixed **albums**: when using Display Suite, I have the ability to limit the number of values getting displayed, I limited it to 1:  and this way **only the first image gets displayed**. The fields link to a page created by Views, which shows the images separately as a gallery, etc...

Here's an example of the result:

What I would like to achieve is to **provide a radio button near the images** to the user **when editing these fields** to be able to **select** which image I would like to **show as a "cover photo"** **without reordering the images**. In the example above, I can only show the 1st one in the "album".

Do you have any ideas for that? Is there a module for this task, or do I have to code?
Can I solve this problem without converting my solution to other gallery solutions? I was thinking about Flag module, but I couldn't find out how I could use it for this task. I'm using File entity (fieldable files) module, which may help in solving this question.

# Answer
One approach would be to use file entity and add a field to the image file entity, but that would require re-working your current solution quite a bit.

Another approach would be to use the

Field Attach API

e.g:

to attach the additional field to the image. The field would then need to be checked during output to show/hide that image as the cover image.

Update:

Here's an example to add a checkbox to an image field. I had some settings on the instance form to show/hide the extra fields, removed for conciseness here. You may be able to use hook\_field\_attach\_form though I used a element process hook instead.

```
/**
 * Implements hook_element_info().
 */
function MODULE_element_info() {
  $extra = array(
    '#process' => array('MODULE_element_process'),
  );

  $elements = array();
  // Add our process function to all managed_file elements
  $elements['managed_file'] = $extra;

  return $elements;
}

/**
 * An additional preprocess callback to append the form.
 */
function MODULE_element_process($element, $form_state, $complete_form) {

  if (!isset($element['#entity_type']) || !isset($element['#field_name'])) {
    return $element;
  }

  // You can get the field data, settings etc.. like this
  $item = $element['#value'];
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
  $settings = $instance['settings'];
  $widget_type = $instance['widget']['type'];

  // Add element, only if file id available
  if ($element['fid']['#value']) {
    // Note default value selects from cache / db table TABLE_file_data
    $element['cover'] = array(
     '#type' => 'checkbox',
     '#title' => t('Cover'),
     '#default_value' => MODULE_file_data_value($element['fid']['#value'], 'cover', '')
    );
  }

  return $element;

}

/**
 * Implements hook_field_attach_presave
 *
 * Saves a files additional field data.
 */
function MODULE_field_attach_presave($entity_type, $entity) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $supported_widgets = array('image_image', 'imagefield_crop_widget');
  $instances = field_info_instances($entity_type, $bundle);
  foreach ($instances as $field_name => $instance) {
    if (in_array($instance['widget']['type'], $supported_widgets)) {

      $settings = $instance['settings'];
      // I have some settings I check as well, if enabled on field instance..
      //if (empty($settings['display_cover'])){
      //  continue;
      //}
      // Find all of the field items.
      $items = field_get_items($entity_type, $entity, $instance['field_name']);

      if (is_array($items)) {
        // Loop over and save extended field values
        foreach ($items as $delta => $item) {
          $fields = array();
          if (!empty($item['fid'])) {
            if(isset($item['cover'])){
              $fields['cover'] = $item['cover'];
            }
            $fields['changed'] = REQUEST_TIME;
            db_merge('TABLE_file_data')
              ->key(array('fid' => $item['fid']))
              ->fields($fields)->execute();
            // Need to clear entity cache for this file
            // as update was not with api but direct query
            cache_clear_all($item['fid'], 'cache_entity_file');
          }
        }
      }
    }
  }
}

```
> 4 votes

---
Tags: flags, media
---


# Question
Title: How to import Term reference (autocomplete term widget) inside field collection with Feeds & feeds tamper
I would like to be able to import content from CSV using Feed. My content type are like this : -Titre

-Field Collection :

--Name (simple text)

--Term (Term reference of type Autocomplete term widget (tagging)

For begin able to import field collection i have applied the #16 patch https://drupal.org/node/1063434#comment-5217400

Everything is working fine exept the insert of my Term field in my fieldcollection because is it of type Autocomplete term widget and if its a new term. I want to keep this type of widget because i want to be able to create new term if they doesnt exist already. I confirm that if i enter a existing term value for my Term field in my csv, my term is succesfuly added.

I am using :

Feeds : 7.x-2.0-alpha8+7-dev

Feeds Tamper : 7.x-1.0-beta3+56-dev

Field collection : 7.x-1.0-beta5

I dont know what i have missed... i am lost and blocked on this bug since 2 weeks.

I hope someone will help me,

Best regards

Jérôme

# Answer
A couple of things.

1. You are using a very old patch. In my implementation I am using the one in #102 (I see its now up to #119) https://drupal.org/node/1063434#comment-7395840
2. You need to tell feeds that it is ok to create new terms for you. Once you've added the target in Node processor \> mapping for the term reference you can change it's target configuration (the cog icon). There is a checkbox there 'Auto create'

\[edit\] Please use the new patch in #121 https://drupal.org/node/1063434#comment-7792223 which corrects your issue.
> 1 votes

---
Tags: feeds, entities
---


# Question
Title: What changed in the way to implement a block?
The documentation for Drupal 8 lists the following hooks as the ones necessary to implement a block.

What I don't find is `hook_block_info()`, which in Drupal 7 allowed to expose the blocks defined from modules, and `hook_block_view()`, which was invoked when a block defined from a module was rendered in a page.

How do modules expose blocks, in Drupal 8? How are the blocks rendered?

# Answer
> 11 votes
Using the "Powered by Drupal" block as an example:

## Drupal 7

### modules/system/system.module

```
/**
 * Implements hook_block_info().
 */
function system_block_info() {
  $blocks['powered-by'] = array(
    'info' => t('Powered by Drupal'),
    'weight' => '10',
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function system_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'powered-by':
      $block['subject'] = NULL;
      $block['content'] = theme('system_powered_by');
      return $block;
  }
}

```

## Drupal 8

### core/modules/system/src/Plugin/Block/SystemPoweredByBlock.php

```
<?php

/**
 * @file
 * Contains \Drupal\system\Plugin\Block\SystemPoweredByBlock.
 */

namespace Drupal\system\Plugin\Block;

use Drupal\block\BlockBase;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;

/**
 * Provides a 'Powered by Drupal' block.
 *
 * @Plugin(
 *   id = "system_powered_by_block",
 *   admin_label = @Translation("Powered by Drupal"),
 *   module = "system"
 * )
 */
class SystemPoweredByBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#children' => theme('system_powered_by'),
    );
  }
}

```

The `hook_block_info()` is replaced by an annotation, containing all of the necessary metadata within the `@Plugin` portion of the docblock. `hook_block_view()` is replaced by the `BlockPluginInterface::build()` method.

The directory structure is the key here. All blocks must be placed into a specific directory within their module folder (src/Plugin/Block).

---
Tags: blocks, 8
---


# Question
Title: Show block for pages of every content type but one; including the front page
I've created a custom block, and I want to show it on every page including the front page, *except* for pages of one specific content type.

In block settings, under "Visibility Settings", there is a list of checkboxes for each content type. If none are checked, the block shows on every page; but if any are checked, the block only appears on pages with the checked content type. So I tried checking everything except the one content type I want to exclude.

Except that this *also* excludes the block from the front page. It appears as though the front page doesn't have a content type you can choose to make the block show up.

Is there a way to get my block on the front page as well, while still excluding some content types from showing it?

# Answer
The Context module is perfect for this task.

1. Download and enable the Context module and add a new context under Structure -\> Context
2. Add a 'Path' condition and set it to `<front>` http://d.pr/i/x4R5
3. Add a 'Node type' condition and check every node type, except the one where you don't want your block to show http://d.pr/i/PSO4
4. Add a reaction called 'Blocks', on the right check the block you want to show when the first to conditions are met, and click 'Add+' next to the region where you want your block to show. http://d.pr/i/a3RG
5. Save the context and that's it

Also make sure to leave 'Require all conditions' unchecked so the context will activate if the first or second condition is met.
> 2 votes

---
Tags: blocks, nodes
---