# Question
Title: Drupal 7 - How to apply Image Styles to a User uploaded logo for a theme
I have need to be apply an Image Style setting to the logo uploaded at appearance/settings/THEME\_NAME

Use Case is: The theme will be used across multiple unique instances within the organization and associated groups, each with different branding. The installation will be via an Install Profile including preset Image Styles. The logo will need to be set by the individual installing the site. It is a requirement that this individual will not need the skill to modify a tpl file in order to set the logo path/size or use any image editing software to modify the logo's dimensions pre upload.

... where to begin?

I suspect there are two routes:

1. Modify the existing logo field via page.tpl.php to use a predefined image style.
2. OR Add a new Image field to the Theme's settings form and calling that in page.tpl.php

Either task is pushing my Drupal ability so before I begin I thought I would ask for opinions on my assumed solutions above or better yet, actual solutions to setting image styles for the logo upload. :)

Thanks in advance, Nick

# Answer
You should be able to alter the logo-path in `hook_preprocess_page` and replace the logo path with the path of the transformed logo:

```
function mytheme_preprocess_page(&$variables) {
  $variables['logo'] = image_style_url('my_image_style', $variables['logo']);
}

```

Didn't try it out, but it should work somehow this way.

edit: there is a LOT of "logo" in my first sentence ;)
> 3 votes

# Answer
This is a design flaw in Drupal. Unfortunately, $logo is a bare HTTP URL, but there is no standard function available to convert a HTTP URL to the Drupal URI that the image\_style\_url function needs. However, you can convert the URL manually like this:

```
function mytheme_preprocess_page(&$vars) {
 $vars['logo']=image_style_url('my_image_style',str_replace($base_url.'/sites/default/files/','public://',$vars['logo']));
}

```

Please have a look at this and be aware that the solution above involves hard-coding (and is not very pretty).
> 0 votes

# Answer
I created a module Logo Image Style which lets you choose an image style for your site logo.

**Logo Image Style:**

> Logo image style allows the site builder to use image styles to render the theme logo. The used image style can be set on a per theme basis.
> 0 votes

---
Tags: 7, theming, media
---


# Question
Title: How to use Rules to flag a node on behalf of ALL users who had previously flagged it with a different flag?
**Here's what I'm trying to do:**

* I have a content type of Question.
* Questions have a field that identifies their status as "asked" or "answered".
* Questions marked "asked" can be flagged (using Flag Module) as "follow" by users.
* When an admin changes the status field of a Question from "asked" to "answered" I would like to flag the Question with an additional flag called "archive" for all the users who "follow" the question.

**This is how I set up the rule:**

**1. Events:** After updating existing content

**2. Conditions:** Entity has field (Parameter: Entity: \[node\], Field: field\_question\_status) *AND* Data Comparison (Parameter: Data to compare: \[node:field-question-status\], Data value: Answered

**3. Actions:** Fetch users who have flagged a content (Parameter: Flag: Follow, Content: \[node\] Provides variables: Users who flagged (users) *LOOP* (Parameter: List: \[users\] List item: Current list item (list\_item)) *ACTION-IN-LOOP* Flag a Content (Parameter: Flag: Archive, Content: \[node\], User on whose behalf to flag: \[users:0\], Skip permission check: true)

**Here's my problem:**

The rule seems to be working for only one user at a time. So if 3 users have "followed" a Question and it is switched to "answered" status only one of the users will have the Question flagged as "archive". I found I can specify an individual user in the *ACTION-IN-LOOP* (action nested in the loop) by changing the value of "User on whose behalf to flag: **\[users:0\]**". If I switch the value to users:1 or users:2 then the rule works for those individual users but not all. The only other option I can think of is to try \[users\] without any additional chained value, but this gives the error "The data type of the configured argument does not match the parameter's flagging\_user requirement." How do I get a rule to flag the node (with "archive) on behalf of ALL users who had previously followed it?

# Answer
> 1 votes
You need to flag on behalf of the user that the loop is operating with each iteration. Either that or add a numerical variable that you increment each loop and fetch that index from the list of users for the behalf of which to flag

---
Tags: rules, flags
---


title: rules - check if email is in use

text:
# Question
Title: rules - check if email is in use
I would like to create user account using rules, after anonymous user creates a node and inputs his email to a email field. Before that I need to run a condition if the email is already in use. What would be the easiest way of doing this? Using fetch entity by email or using custom php? I read about user\_authenticate function but I do not know how to use it. Thank you for advice.

# Answer
```
$check=db_select('users','u')
    ->fields('u',array('uid'))
    ->condition('mail','user email comes here','=')
    ->execute()
    ->fetchField();

if($check!='')
{
    form_set_error('mail','Email Already Exists');
}

```

You can use this.
> 1 votes

# Answer
Add a Rules Component that takes a list of users as a parameter and put all the actions in this component. Add a list count comparison condition as less than 1. In the original rule Fetch entity by property of type User with the email address you need to check. Pass the list that is fetched to the Rules Component as the parameter. Only if no users exist with that email address will the actions of creating a new account happen.
> 1 votes

---
Tags: 7, rules
---


title: How to insert user table

text:
# Question
Title: How to insert user table
I would like to know how I can show registered users in a table with profile pictures like this site has. I would like to make this kind of site where actors can make a profile so they are put in a actors user role and that I can give people who look for actors an other role, so they can look for them in the database and actors can't. I am kind of a newbie to this sorry for that. Thanks!

# Answer
The Views module is typically how this kind of thing is done. There are options for outputting tables or unstyled divs that you can theme yourself.
> 2 votes

---
Tags: users
---


title: How to avoid duplicate pages?

text:
# Question
Title: How to avoid duplicate pages?
Assume the following. We have a taxonomic vocabulary called **product**. Which contains two terms: **tables** and **chairs**. This taxonomy creates the following URL's:

Taxonomy Menu module to create a menu that taxonomy. If we click the *Tables* menu item leads to *http://www.mydomain.me/product/tables*. Which shows a list of all published tables. Same with the chairs.

All right. But we want to customize this list, so we to use Views. Views creates the following two pages:

**Here is my problem. How do we make the taxonomic menu leads us to pages created with Views?**

Currently I get this by changing the URL's menu with jQuery. But this may not be the best way.

Does anyone know how to deal with this duplicity of pages (taxonomy page, and Views page)?

Greetings!

# Answer
Here is what I would do:

1) Create a view BLOCK instead of page.

2) Go to manage display of your taxonomy page and disable all fields (you should have an empty page now).

3) In blocks, grab your `view name block` and put it under content area.

Select **Display Only In**.

In the text box, put: `product/*` (so it will display the view in all `/product` pages).
> 1 votes

# Answer
Create a view of taxonomy terms for the specific vocabulary. If you select the path `/taxonomy/term/%` (the `%` is really important) for your view, and select a Contextual Filter to the view for `Content: Has taxonomy ID term`, this will effectively override the path of the default core display for the Taxonomy Term, EVEN if you have defined an alias to the taxonomy term path.
> 0 votes

# Answer
With the module Views, you have automatically a default views on this page path `/taxonomy/term/%`, `/taxonomy/term/%/%/feed`

It's **disabled** by default. Just activate the view and you can modify it as you want.

No need to create special menu or so, it will be effective in the menu too.
> 0 votes

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


title: How do I create an ajax link?

text:
# Question
Title: How do I create an ajax link?
I want to create an ajax linking a view (front page, for example).
I create an ajax edit link to edit content directely in the node. I success to add a link but when i click to it, a popin was opened(to edit content). I know how to make it in Drupal 7, but I don't find the solution for Drupal 8.

This is the code I am using.

```
    $build['ajax_edit_link'] = array(
    '#theme' => 'links',
    '#weight' => -2,
    '#links' => array(
      'ajax_edit_link' => array(
        'title' => t('Edit'),
        'url' => $entity->urlInfo('edit-form'),
        'attributes' => array(
          'class' => array('use-ajax'),
          'data-dialog-type' => 'dialog',
          'data-dialog-options' => Json::encode(array(
            'width' => 1200,
            'height' => 500,
          ))
        ),
      ),
    ),
  );

```

Here is all captures of the result of this edit ajax link in Drupal 8 (popin).

And here are the capture I want to make in Drupal 8 (Capture in Drupal 7 site).

# Answer
> 5 votes
Your code is missing one part that I can see, the `#attached` key:

```
  $build['ajax_edit_link'] = array(
    '#theme' => 'links',
    '#weight' => -2,
    '#links' => array(
      'ajax_edit_link' => array(
        'title' => t('Edit'),
        'url' => $entity->urlInfo('edit-form'),
        'attributes' => array(
          'class' => array('use-ajax'),
          'data-dialog-type' => 'dialog'
          'data-dialog-options' => Json::encode(array(
            'width' => 1200,
            'height' => 500,
          ))
        ),
      ),
    ),
    '#attached' => array('library' => array('core/drupal.ajax')),
  );

```

---
Tags: ajax, 8, navigation
---


# Question
Title: How to make an entity reference field an editable field in views
I have a view that displays entity references. Entity references are assigned via select list and are filtered by a seperate entity reference field.

I installed the Editable Views module so that I can directly edit the field from the view.

Even though the admin user has all the right permissions set up, they are still only able to see the entity reference field displayed on the view, but not actually edit it. Is there a conflict between the two modules? Or is there some kind of extra setting that I am missing.

# Answer
All I need to do was to change the format of the view from "Table" to "editable table" :/
> 3 votes

---
Tags: views, entities
---


# Question
Title: Contextual value when the filter is not available and PHP code
I have block view that should be rendered in the node details page. i.e `/node/*`. The block should render latest 6 nodes published under the Category `category_field` that the node has its value.

However, the URL is rewritten and the category id `tid` is not available. The URL is looks like the following:

`http://example.com/Category/world/the-node-title`

So the contextual filter is not available in the URL. So, I created the following PHP code, shown in the screen shot, to get the category tid and return it:

In the `node.tpl.php` when I try to `var_dump($node->field_category['und'][0]['tid']);` it returns the number of `tid` of the current node. However, the above demonstrated code seems to be not work in the PHP filter code. When I try to return any available value for an category id such as `19` for example, it works.

In other words, how could I return the current node's category field id to the filter?

# Answer
I found the cause of the problem from this resource and I have to define the `$node` variable by:

```
$node = node_load(arg(1));

```

Then I use the `$node` as shown in the question above.
> 1 votes

---
Tags: 7, views
---


title: Menu Token Broken

text:
# Question
Title: Menu Token Broken
I have been looking around for an answer and haven't found an answer, so if this is a duplicate, let me know and I'll delete it.

My menu token module no longer works, even with the same settings. I do have everything set up the way it should, meaning I've got "node from context" and the same field as I have had in the past.

If you go to this page: http://arvadahistory.org/hf/wadsworth-looking-north-arvada-clear-creek-bridge \- and look at the right hand side, you'll see "Order Photograph" and "Photograph Order", when you click on the "Order Photograph" link, you'll be led to a form using this url: arvadahistory.org/historic-photograph-order-form?hin=\[node:field\_ahs\_colleciton\_number\] (sorry it's not a link, I need more reputation points) - however, in the older working version, it would have ended up like this: http://arvadahistory.org/historic-photograph-order-form?hin=AHS.HF.0001

So I'm not sure what has changed, does anyone have an idea as to where I can start to work on?

Matt

# Answer
> 1 votes
Rolled back from Beta6 to Beta5, poor response on module projects issues site but as the comments state, there are several larger bugs not being addressed by the project. Have downgraded back to Beta5 and all issues have been resolved.

---
Tags: tokens
---


# Question
Title: How to reverse order of pulldown Views Exposed Filter showing taxonomy terms reference field
In Views 3 D7, I have a view with an exposed filter pulldown that is based on a taxonomy vocabulary called Versions. The filter pulldown shows the versions in the order of the vocabulary (so 1.0, 2.0, 3.0) and I need it to show them in the reverse order (3.0, 2.0, 1.0).

I have tried using Better Exposed Filters to render the filter, but I haven't seen any option for sorting order. I also tried using the default Drupal filter and again no sorting order.

I tried using the Entity Reference solution in this SE post, but the problem is that I cannot then use autocomplete widget to create new Versions in the node/add form, so I'm locked (I think) into using term reference. Searched around SE and google for quite some time but no solution yet. Any help would be appreciated!

# Answer
> 0 votes
You should give Entity Reference a go. You don't need to use the autocomplete widget. The standard dropdown list is sufficent. Just create a entitiy reference, type "taxonomy term", select your vocabulary, set to sort by "A property of the base table of the entity" and select "name" and "descending". This should work...

If you need to add new terms on node creation, you could try Entity Connect module. The module will allow you to dynamically create and edit some entity types (e.g. taxonomy terms) which should be referenced into an Entity reference field.

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


# Question
Title: How to add views exposed filter blocks into views
I am trying to move a **views exposed filter** into a custom block, and then add it back to the **views header**. The reason for this is because I would like to intersperse the filter with other blocks/markup in the views header. When I selected the option to turn the filter into a block, it does show in the Block UI, but not as an option to add to the view header.

Is this possible in views?

# Answer
> 1 votes
Add the following function in your template.php

```
function THEMENAME_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

```

then in your views header render the block like so

```
<?php print THEMENAME_render_block('<moduleName>', 'delta', array('title' => t('Filter Title'))); ?>

```

For this you must have views php module enabled if you want to render the block from views header or else you can use tpl file to render the block in the header as @rooby suggested.

---
Tags: 7, views
---


# Question
Title: How to add product display nid to user order view?
On a typical Drupal Commerce website a user can see the following tabs on his user-page:

```
View
Edit
Orders
Address Book

```

I am trying to figure out how to get Products tab added to this list, which would list all the Products (actually Product Displays to be exact in Drupal Commerce terms) purchased by the user. It would be very much like Orders page, but instead of Order numbers this page would be outputting Product Display nids, titles, etc.

Alternatively, getting Product Display nids listed on the Orders page would suffice to my purposes, if this is easier. The order page is represented by the 'commerce\_user\_orders' view, but I can't figure out how to get product display nid there as there is no any product-related options. There is a "Line items" option which lists Title of the product, but doesn't link to actual Product Display page. Basically I need users to be able to go to the specific Product pages from their orders pages directly associated with the product displays.

# Answer
You can use the module commerce\_product\_attributes to show more product details on the line item.

> Attribute field for line item: This field allows the presentation of the product in the shopping cart by a separated view mode. A new product display is added. There you can define the fields which should be displayed for this product type in the shopping cart.

While it can be used on the shopping cart, it can also be used on the Orders view.
> 0 votes

# Answer
You should be able to use the View field called:

> Commerce Line item: Display path
>
> Appears in: commerce\_line\_item:product, commerce\_line\_item:product\_discount.

This field links the line item to the product page that added it.
> 0 votes

---
Tags: commerce
---


title: Multiple URL aliases for same node

text:
# Question
Title: Multiple URL aliases for same node
I have the following URL aliases for the same node.

* /products/single-room/product-listing/wall-mount
* /products/multi-room/product-listing/wall-mount

I have two details button Single & Multi-rooms; Single Room button has a link to /products/single-room/product-listing/wall-mount and Multi Room button has a link to /products/multi-room/product-listing/wall-mount. When I click on Single Room or Multi Room Button, both will redirect to /products/multi-room/product-listing/wall-mount; when I delete the multi-room alias the single-room button will go to /products/single-room/product-listing/wall-mount which is correct but multi-room will give the *404 not found* error.

What I need is to have two aliases for same node: When users click on single, they are redirect to the same node with /products/single-room/product-listing/wall-mount as URL; when users click on multi-room, they get redirected to the same node with /products/multi-room/product-listing/wall-mount as URL.

Please help me out?

# Answer
> 0 votes
Disable the Global Redirect module. This module is specifically built to do the behavior you are describing, because search engines like it.

Unless you are using those path segments as contextual filters somewhere, there should be no reason to do this. If you are using those path segments as contextual filters, there should be a better way to do this. Either a view page or a panel page would be able to hold that page open, use wildcards for those address segments, and get the functionality that you want without having to upset the search engine bots.

---
Tags: nodes, path-aliases
---


title: POST method returns 415

text:
# Question
Title: POST method returns 415
Trying to create a node `page` through web-service.But returns **415 Unsupported media type**

This is how I have done

# Answer
Here is some example raw data you should be sending (don't send it as form data):

```
{
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hello World"}]
}

```

You do not need to send the `Accept` header, because that no longer matters because of the `_format=json` query string. And in this case, when successful, it will return a 201 so you can disregard the `_format` query string.

The POST to `?q=entity/node` is correct, but don't forget to send an `X-CSRF-Token` header with a value that can be retrieved here: `?q=rest/session/token`
> 2 votes

# Answer
You are apparently trying to send form-data encoded values? If you claim the send json, then you actually need to send a valid json structure. This is a service, not a form.

Create a new in the UI that looks like one that you want to create, then access it using GET through rest with the same format. Adjust that, e.g. remove the ID and UUID and then use that as the template/value to POST.
> 1 votes

---
Tags: 8
---


# Question
Title: How to Begin a French Version of My Site?
I have an English site at the moment. I'd like to start a French version of it, but I get a bit confused when I look at the options out there. I am running Drupal 7.

Here's what I'd like:

* When you go to example.com, it is in English. When you go to example.fr, it is in French.
* There should be an option to switch from English -\> French or French -\> English, redirecting to the appropriate domain.
* Some nodes on the English side will not have equivalent nodes on the French, and vice-versa. Some will, and some will not.
* I wonder if it's possible to have different settings per site? For instance, I have a social media module that has icons for following on Twitter/Facebook etc. I'd like to have the French site show the links to the French versions of those, like my French FB page.

What would be the best way of doing these things?

# Answer
> 0 votes
Drupal support multi-language websites and creating a multi-language site is very easy.

You can configure a Drupal website to use a language other than English and you can configure a site to use multiple languages.

If your site requires the interface to be displayed in multiple languages or if you need to customize the interface of a single language site, the first step is to enable the multilingual capabilities of Drupal.

You can also configure a Drupal site to allow your users to switch languages and you can translate content into multiple languages.

**Helpful Resources:**

**Videos:**

**Getting Started:**

* Localized Drupal Distribution: A small distribution to install Drupal with user interface translations pulled automatically from localize.drupal.org. It is suggested you use this distribution to start off with Drupal if you'd like to set up a localized site.
* Internationalization: This is a collection of modules to extend Drupal core multilingual capabilities and be able to build real life multilingual sites.
* Internationalization (i18n) Submodules: A collection of submodules that provides extended multilingual support for Drupal. Each module addresses a specific functionality.
* Apache Solr Multilingual: The goal of this project is to cleanly extend Apache Solr Search Integration to provide: better support for non-English languages, support for multilingual search, cross-language information retrieval (CLIR), and an easy-to-use administration interface. Apache Solr Multilingual does not replace Apache Solr Search but is based on it.
* Related Modules: A list of additional contributed Drupal 7 modules that extend Drupal's multilingual features

---
Tags: i18n-l10n
---


# Question
Title: Displaying multiple File entity types in a view, when they have different fields to display
Working with the Media module, I want audio and video files to show (user uploaded/selected) preview images when displayed in areas throughout the site (instead of the default soundwave and film clip image.) So, I added fields to those files type entities, but since Image can be it’s own preview, I didn’t add that field (since it would seem odd to make the user upload/choose the image again.) This has become a GIANT pain when trying to figure out how to show all the file types together in a single view. (I want it to show field\_image for audio and video, but the file for images.)

Does that sound undoable? Nothing I've been able to try with views and relationships gets me what I need. I tried customizing the preview display mode for each, then display the "rendered entity" (which got me what I needed for displaying the images), but left me with other issues, since I was displaying field\_image fields for some, but file fields for others.

Slight Update: I tried adding the field\_image field to the image file type, but that seems to cause some kind of infinite loop/server error when viewing/editing that file anywhere.

# Answer
> 0 votes
What I ended up doing was just add custom tpl.php files for each of the types I was interested in (audio/video/images; e.g. file--image.tpl.php). Then, in the views, just say to render the entity instead of using fields.

I'd have liked a more elegant way, since I now have 3 more tpl.php files to worry about, but it DID fit the bill.

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


# Question
Title: How to select a custom block and region according to a view
I have a view / display page that needs to be displayed in a specific html - page format. I did a `html--viewname.tpl.php` and `page--viewname.tpl.php` to display my view.

Within `page--viewname.tpl.php` I call `print render($page['content']);` to render my view. All is working except that block.tpl.php and region.tpl.php are called by drupal system to wrap the view `content` adding several html tags (div) that I don't want.

I expected to use function `MYTHEME_preprocess_block(&$variables)` to ask drupal to use a custom block.tpl.php file, but within this function I didn't find the way to know if the function is called to render my viewn or anything else.

# Answer
When dealing with a page view you can use the views\_get\_page\_view() function, to get the view object for the current page, like this:

```
/**
 * Variable preprocessor for the block template.
 */
function MYTHEME_preprocess_block(&$variables) {
  // If we are on a views page display.
  if ($view = views_get_page_view()) {
    // If we are on the MYVIEW view.
    if ($view->name == 'MYVIEW') {
      // Add the view object to the variables for use in the template (if you need it).
      $variables['view'] = $view;

      // Use a custom block template for this specific display (if required).
      $variables['theme_hook_suggestions'][] =  "block__{$view->name}";

      // Add your block customisations for this specific view (if required).

      // If we are also on the MYDISPLAY display of MYVIEW.
      if ($view->current_display == 'MYDISPLAY') {
        // Add your block customisations for this specific view and display here (if required).

        // Use a custom block template for this specific display (if required).
        $variables['theme_hook_suggestions'][] =  "block__{$view->name}__{$view->current_display}";
      }
    }
  }
}

```
> 1 votes

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


# Question
Title: Views Search is displaying no results behavior by default
I've created a Drupal 7 Views Search page. It works overall. However, when there are no returned results I want it to display a message such as 'your search returned 0 results. try something else.' So I put that message in an unfiltered text area using 'advanced \> no results behavior' but now it's showing that message by default before someone has even entered their search terms.

I want the search page to only show that message once they've entered a search term in the 'search: search terms' exposed filter criteria and it actually returns no results. I don't want it to display right when they get to the page.

Anyone know how to keep that from happening?

# Answer
> 4 votes
I assume you are using the "On empty input: Show none" option of the search terms filter. In this case the view is actually still running but returning no results due to the filter, so you get the empty text displaying.

To stop that you can change the "Exposed form style" to "Input required".

Then the view will not run until a search term is entered, which means no unwanted empty text.

# Answer
> 0 votes
I THINK I fixed it. if I turn off 'remember the last selection' for my exposed filter it seems to NOT show results.

---
Tags: views
---


title: Embed a contact form

text:
# Question
Title: Embed a contact form
Is it possible to take a contact form and embed it into a page.html.twig or node.html.twig file? Or is the form only accessible via its contact/machine\_name link?

# Answer
> 5 votes
Check out Contact Storage.

Among various other features, like being able to store contact messsages, the latest version has a view builder that allows to display a referenced contact form (it's a config entity, so you can reference it using a standard entity reference field).

---
Tags: forms, 8, emails
---


title: Alter cart unit price and total amount

text:
# Question
Title: Alter cart unit price and total amount
I need help on this code which is invoked on calculate sell price rules event on cart view. Line items and order are properly modified. But nothing is displayed, old unit price amount and old total amount are displayed. Even after cart refresh. Any idea ?

```

/**
* Calculates the price when line item are dispalyed
* or created.
*/

function mymodule_calculate_product_price_cart($order) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    // Iterates on line items and alter the price.
    $commerce_line_items = array();
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      $type = $line_item_wrapper->commerce_product->value()->type;
      if ($type === 'insurance') {
        $package_price   = $line_item_wrapper->commerce_product->field_package_ref->commerce_price->amount->value();
        $warranty_price  = $line_item_wrapper->commerce_product->commerce_price->amount->value();
        $amount = _mymodule_calculate_policy_price($warranty_price, $package_price);
      }
      elseif ($type === 'little_product') {
        $amount = $line_item_wrapper->commerce_product->commerce_price->amount->value();
      }
      else {
        $commerce_line_items[$delta] = $line_item;
        continue;
      }
      $qty = $line_item->quantity;
      // This sets the unit price by adding a component price 'base_price'
      mymodule_line_item_price_amount($line_item, $amount, 'commerce_unit_price');
      mymodule_line_item_price_amount($line_item, $qty * $amount, 'commerce_total');
      commerce_line_item_save($line_item);
      entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
      $commerce_line_items[$delta] = $line_item;
    }
    $order_wrapper->commerce_line_items = $commerce_line_items;
    module_invoke_all('commerce_cart_order_refresh', $order_wrapper);
    commerce_order_save($order_wrapper->value());
  }

```

# Answer
> 6 votes
I finally made it work.

```
function mymodule_commerce_commerce_cart_order_refresh($order_wrapper) {
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
    $type = $line_item_wrapper->commerce_product->value()->type;
    if ($type === 'insurance') {
      $package_price   = $line_item_wrapper->commerce_product->field_package_ref->commerce_price->amount->value();
      $warranty_price  = $line_item_wrapper->commerce_product->commerce_price->amount->value();
      $amount = _mymodule_commerce_calculate_policy_price($warranty_price, $package_price);
    }
    elseif ($type === 'little_product') {
      $amount = $line_item_wrapper->commerce_product->commerce_price->amount->value();
    }
    else {
      return TRUE;
    }
    $qty = $line_item->quantity;
    // This sets the unit price by adding a component price 'base_price'.
    mymodule_commerce_line_item_price_amount($line_item, $amount, 'commerce_unit_price');
    mymodule_commerce_line_item_price_amount($line_item, $qty * $amount, 'commerce_total');
    commerce_line_item_save($line_item);
    entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
  }
}

```

# Answer
> 3 votes
I tested the above answer, it useful but not changed the **Order Total Amount**.
After do some research and I finally get all done.
For those people who don't want to use rules and hope to alter the price directly. Here is my solution:

```
// Alter the price in list and single product page
function my_module_commerce_product_calculate_sell_price_line_item_alter($line_item){

    $price = 100; // 1 dollar
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount']=$price;

}

// Alter the price in cart & order
function my_module_commerce_cart_line_item_refresh($line_item, $order_wrapper){

    $price = 100; //1 dollar
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount']=$price;
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount']=$price; // alter the base_price component

}

```

# Answer
> 2 votes
I made own solution to alter price, in this example it just double price (for which is Rules solution better) but I need robust solution for my ecommerce site with custom products.

```
/**
 * Implements hook_commerce_cart_line_item_refresh().
 */
function HOOK_commerce_cart_line_item_refresh($line_item, $order_wrapper) {
  $qty = $line_item->quantity;
  $price = $line_item->commerce_unit_price[LANGUAGE_NONE][0]['amount']*2;

  $line_item->commerce_unit_price[LANGUAGE_NONE][0]['data']['components'][0]['price']['amount'] = $price;
  $line_item->commerce_unit_price[LANGUAGE_NONE][0]['amount'] = $price;
  $line_item->commerce_total[LANGUAGE_NONE][0]['data']['components'][0]['price']['amount'] = $qty*$price;
  $line_item->commerce_total[LANGUAGE_NONE][0]['amount'] = $qty*$price;
  commerce_line_item_save($line_item);
  entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
}

```

# Answer
> 1 votes
If I am not mistaken this can be entirely done with Rules, as I just discovered.

1. In the admin menu, go to Store » Settings » Product pricing rules.
2. Add a new pricing rule.
3. Leave the `Calculating the sell price of a product` trigger.
4. Add the condition `Order is a cart`.
5. Add any other conditions you might need such as product types. (You might need to add the `Entity had field` condition to check if the commerce-line-item has a commerce-product field in order for product properties to be exposed).
6. Add one of the actions in the Commerce-line-item group. They offer to set specific amounts, or perform calculations.

More information about pricing rules

# Answer
> 0 votes
Try to implement `hook_commerce_cart_product_add` in your module.

# Answer
> -1 votes
This part :

```
line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount']=$price; // Alter the base_price component

```

... made my day (Commerce 7.x-1.10).

It correctly sets the order total amount on top of the line item amount.

If you don't do this, your order total will be out of sync.

---
Tags: commerce
---


# Question
Title: How to theme the heading in a view with grouped fields
I have a view of a list of nodes, the nodes are being displayed as fields, in an html list. I'm grouping by two fields, (type and category) so that my view displays like this

Type A Catagory A Node1 Node2 Catagory B Node3 Node4

The view prints both groupings, and now I'm trying to customize the css of both the type and category titles. Unfortunately when I try to alter the field template (by creating a new one) I can't seem to add the code in the right place. When I alter my field template to this.

```
<div class="menu-category">
   <?php print $output; ?>
</div>

```

it prints that div within the tag and therefor does not work.

```
    <div class="view-grouping-content">
<h3>

   My Category

</h3>

```

Can anyone help with this?

# Answer
> 0 votes
You can rewrite the result of each field, do this steps for the two fields:

1. In the views edit page, click on the field (type) then check "rewrite result".
2. using replacement patterns you can print the field value between `H3` tag like this:

```
<h3 class="some-class">[field_type]</h3>

```
3. click save.

After That you have to write CSS style in `style.css` file as you like.

# Answer
> 0 votes
You can do this by overriding a couple of views templates.

If you are only grouping by one field then you would override it in the display template, which in your case is `views-view-list.tpl.php`.

The part that you want to modify is:

```
<?php if (!empty($title)) : ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>

```

If you are grouping by 2 or more fields then the last of those is handled as above. The others are handled by overriding the `views-view-grouping.tpl.php` template. The part you want to modify is:

```
<div class="view-grouping-header"><?php print $title; ?></div>

```

---
Tags: views, theming, entities
---


title: Issue with Uploaded Images

text:
# Question
Title: Issue with Uploaded Images
Alright, I've got an odd issue with what I am guessing to be is size. I have uploaded several images to a site, and while they upload correctly (meaning I can find the image in the appropriate folder without loss of quality), I can't see images larger than what I am guessing is from 400-500KB. As you can see, the two bottom images are 353KB or less in size, and I can see them. However, the upper three are 850KB or larger and cannot be seen, am I doing something wrong with this? Thanks.

# Answer
I had a similar issue, I just reset and added to the PHP limits in my configuration. After that, worked like a charm.
> 0 votes

---
Tags: media
---


title: Drupal search api custom sort order

text:
# Question
Title: Drupal search api custom sort order
I am using search api solr and using views for search results. In my content type, there will be a multilingual field using entity translation and also a field representing language of the node. I am having three languages in the site.

I would like to sort the results by language.

Like, if the site language is set to english,

The search results should first list all english language nodes and then second language and then third. Suggest me a way to fix this.

# Answer
> 0 votes
I fixed this by using hook\_search\_api\_solr\_query\_alter() and solr function. Here is my code:

`function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
 if ($_SESSION['language'] == 'en') {
 $call_args['params']['sort'] = 'termfreq(ss_field_name,EN) desc';
 }
}`

---
Tags: 7, search
---


# Question
Title: How can I hide the username on a custom user-profile.tpl.php page?
I'm making a custom user-profile.tpl.php page and want to put the "business name" field where the Title/Username normally occurs and print the username elsewhere.

The username doesn't appear in the list at: Administration » Configuration » People » Account settings » Manage Display so I can't remove it there.

My guess is that I need to add some logic to page.tpl.php to not print it on user profiles and then I need to know the variable to add it to user-profile.tpl.php.

Can anyone help me with this?

# Answer
You can do it by disable field display property using `form_alter`

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
  $form['account']['your_field_name']['#access'] = FALSE;
    }
  }

```
> 0 votes

# Answer
1) Create a custom module

2) Put this code:

```
function formalter_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'user_profile_form':
        hide($form['account']['name']);
       //dpm($form['#user']->field_full_name);
        $form['account']['name']["#attributes"]['placeholder']=t('Bussiness  Name');
  }

```
> 0 votes

# Answer
Thanks for the responses. I approached it differently.

I first created a custom page--user.tpl.php file in which I removed the section that prints the title.

I then found the username variable and wrote a little snippet to print it under the business name (except in cases where the business name doesn't exist) in user-profile.tpl.php.

```
<?php

$user_username = $variables['elements']['#account']->name;

if (isset($user_profile['field_business_name']) || array_key_exists('field_business_name', $user_profile)) {

$user_business_name = $user_profile['field_business_name']['#items'][0]['safe_value'];
print "<h1>$user_business_name</h1>";
print "<b>$user_username</b>";
print "<br>";
}

else

print "<h1>$user_username</h1>";
print "<br>";

?>

```
> 0 votes

---
Tags: theming
---


title: multi url allies for same node

text:
# Question
Title: multi url allies for same node
I have set my auto URL allies to something like this "store/\[node:nid\]/\[node:title\]"

having node title in url will make it more human readable and better SEO. the issue is I want to be able to access the node using this url "store/\[node:nid\]" only

here is the question again

my url is "www.site.com/store/1234/title"

I want this url to work as well "www.site.com/store/1234"

and even this "www.site.com/store/1234/new-title"

and even this "www.site.com/store/1234/wrong-title"

cheers cheers

# Answer
> 0 votes
You can use symlink for creating multiple urls you want. I try this and created multiple with pathauto too.

---
Tags: 7, uri, .htaccess
---


# Question
Title: What is the easiest way to upload video and audio content?
I am creating a website archive that will allow users to upload various different types of media content including video, audio, images, documents and text. I want to make it easy for users to upload the media content to the site.

Is it better to upload directly to the website hosting itself or to use a third party video and audio hosting like YouTube and SoundCloud?

Either way how can it be made as easy as possible for the user to upload the media content?

# Answer
> 2 votes
Get a media management suite that integrates with as many third party hosting providers as possible. It means less work for you, less complexity, and less bandwidth on your server for which you have to pay.

Good suite's include, but are not limited to:

Scald

> Scald is a popular and flexible way to handle media in Drupal.
>
> Scald can handle images, video, audio, tweets and even Flash files. Scald works with YouTube, Vimeo, Soundcloud and other many other providers.

and Media

> The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.

For a front end media solution you can look at MediaFront

> The MediaFront module is a front end media solution for Drupal. It employs an innovative and intuitive administration interface that allows the website administrator to completely customize the front end media experience for their users without writing any code.

# Answer
> 1 votes
You can try filedepot module

> The filedepot module is full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.

# Answer
> 1 votes
Some more modules not mentioned yet in any of the previous answers ...

# Modules with a stable D7 release

### Take Control (D6 and D7)

Here is a quote about the Take Control module (from its project page):

> ... is a set of set of modules for Drupal for managing various administrative tasks particularly related to the file system. Beginning with version 2.0, the module has been refactored into a core/add-on architecture, where a core module take\_control provides common routines and settings, whereas the bulk of front-end user interaction comes from add-on modules (e.g. file browser etc).
>
> Currently, there are 2 add-on modules:
>
> 1. **File Browser**: A complete File Browser/File Manager for Drupal. Allows you to manage your Drupal file-system directly through Drupal without needing FTP or your Hosting Control Panel access.
> 2. **Quick Permissions**: Many Drupal administrators are troubled by the: Drupal\_Security\_Do\_Not\_Remove\_See\_SA\_2006\_006 directive in Drupal file-system root's .htaccess file that effectively prevents write access to the file-system folder outside Drupal. This module allows you to take control of the file-system folder by specifying custom permissions on it from Drupal. Additionally, you can specify custom permission / delete any directory/file owned by Drupal using this module.

### Document (D6 and D7)

The Document module is a *Document Management System* for Drupal. Here is a quote about it (from its project page):

> Features:
>
> * Complete integration with Drupal node system. This module adds a custom Node Type, Document. Each Document you create is a Drupal node, and hence enjoys all features available to a node.
> * Support for Document revisions/versioning - This module allows you to maintain multiple versions/revisions of the same document.
> * Views 2 Integration - The custom fields added by the module to the Document node type are accessible in Views, plus the module provides some useful out-of-the box Views.
> * Theming support
> * Searching - The documents being nodes are fully indexable by the Drupal search system. In addition, the module provides its own custom search for Documents.
> * A couple of blocks are available for document search that can be placed flexibly in your theme layout.

### elFinder file manager (D7)

The elFinder module integrates with elFinder, which is a open source AJAX file manager. Here is a quote about it (from its project page):

> Features:
>
> * Integrated with WYSIWYG API capable editors: CKEditor, FCKeditor, TinyMCE, BUEditor (D6), jWYSIWYG (D6), YUI, WYMeditor.
> * Multiple file upload.
> * File copying/moving with Drag & Drop support.
> * Quick file and directory rename.
> * Image resizing.
> * Lightbox-preview.
> * Context menu with generic file/directory operations.
> * Inline text file editing.
> * Favourites directory list.
> * Directory selection history.
> * Working with archives.
> * File descriptions.

### CMIS API (D7)

The CMIS API module aims to provide a generic API for integrating with CMIS compliant Enterprise CMS (ECM) systems.

# Modules with an unstable D7 release or for D6 only

There are a few more modules that might look like a possible fit, though they are, in general, perceived as rather buggy / unstaled, or only support old (D6) Drupal releases so far. Below are some more details about those modules.

### Media Browser Plus (D7, though only a beta version)

There is also the Media Browser Plus module, which is an enhancement module for the Media module, with additions such as:

* Adding tags to media when uploading.
* Searching media.
* Hierarchical taxonomy based organization e.g. “folders".
* Mirroring folder taxonomy to filesystem"
* Drag & Drop to move files between folders.
* Multi selection of files.
* Bulk operations on files.
* Media Basked to download multiple files at once.

### Asset (D7, though only a beta version)

Here is a quote about the Asset module (from its project page):

> ... proposes a new approach to the media management in Drupal, resolving a long-standing problem of reusable media files (images, videos, documents, etc) that evolved into the problem of reusable media content (images/videos/documents/etc with the attached content like description/licence/etc).
>
> The Asset module provides new entity called Media Asset and the set of Media Assets examples (Image, Video, Audio, Document, Image Gallery, Free HTML), which can be enabled optionally.

### Web File Manager (D6)

The 'Web File Manager' module is for D6 only. And issue WebFM for Drupal 7 has status *Closed (Won't fix)*. But there is also an ongoing discussion about a Ground-up rewrite of WebFM.

---
Tags: media, files
---


title: "Click to show" text at pages

text:
# Question
Title: "Click to show" text at pages
How can I implement "click to show" some text data at pages?
Also I need to save log in database about events.

I've found tiny module Field Value Loader (Show field on click).

Any suggestions about how to implement this?

# Answer
Checkout these modules:

**qTip (Stylish jQuery Tooltips):**

> qTips are stylish tooltips that can be configured and styled (more to come in later releases) to fit nearly any website's design. You can look at demo here.

**Field Tooltips:**

> Field Tooltips provides a user interface for adding tooltips to fields. Field Tooltips includes three important features:
>
> 1. A simple administration interface for adding tooltips to fields.
> 2. Support for all field types.
> 3. Support for HTML tooltips.

**Beauty Tips:**

> The Beautytips module provides ballon-help style tooltips for any page element by integrating the BeautyTips jQuery Tooltip plugin by Jeff Robbins with Drupal. It provides an API for adding custom beautytips as well as some built-in features. Admins can enable rollover balloon-help style tooltips for text fields within forms. It also supplies hover tips for Drupal help links and advanced help links.
>
> Most importantly, it allows developers to add their own custom beautytips popups to their site without having to delve into jQuery.
> 1 votes

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


title: Looking for node revision author token

text:
# Question
Title: Looking for node revision author token
According to http://drupal.org/node/252241 a revision author token may be available. However I do not see anything referencing revision:author (variation?) in my list of available tokens. Is there something like this?

# Answer
> 3 votes
For D7, in order to gain access to revision:author tokens, *you have to install* Revisioning *module*. (of course you also need token module)

Then you can see *all the available tokens* by going to Help -\> Token (/admin/help/token)

So after enabling the module, a new token category, named "Revisions", is available. You can see for example **\[revision:revision-author\]** which refers to "The author (or editor) of the revision" and a bunch of others regarding the revision author.

P.S. As per this there seems to be currently a bug regarding \[revision:revision-author:mail\]

Good luck and let me know if you need more help!

# Answer
> 0 votes
This one is for D6 but probably give you a hint: http://api.drupalhelp.net/api/revisioning/revisioning\_tokens.inc/6.4

# Answer
> 0 votes
Have you tried Custom Tokens module ?

> It gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.
>
> Versions 7.x-1.x and previours relied on PHP evaluation to build custom tokens.

The idea is to define your own tokens and use them. Also it works with PHP Filter Module.

Install module goto `admin/structure/token-custom/add` to add a new token. Since you want to get the author from node submission select *Token type node*

# Answer
> 0 votes
When I use tokens together with Rules action "After updating existing content" this token gives me the author of the *updated* node (i.e. the author of the latest revision): **\[site:current-user\]**. (To get an author of the first revision, you can use **\[node:author\]**.)

---
Tags: 7, tokens
---


# Question
Title: Get only one value from a multivalue field in template node
I have a content type which has a multivalue image field. I need to create a template that displays a list of nodes of that type but displays only one value of that multi field, not all of them together.

I know we can do if we use views under 'multiple field settings' which is explained here views 3: select only one value from a multivalue field but I am not using views, Can we do using only template nodes?

* node title1
* first image
* node title2
* second image

etc

Please help.

# Answer
I have fixed myself using following code:

```
                        for($index=0; $index<1; $index++){

                <div class="row speaker-detail-row">
                        <div class="field field-name-field-speakers-image field-type-image">
                                <?php
                                $fields = field_get_items('node', $node, 'field_speakers_image');
                                $speakers_image = field_view_value('node', $node, 'field_speakers_image', $fields[$index]);

                                 if (!empty($fields)) {
                                            print render($speakers_image);
                                        }else {print "Image not found";}
                                ?>
                        </div><!--end field-->

                        <div class="field field-name-field-speaker-name field-type-link-field">
                            <?php
                                $fields = field_get_items('node', $node, 'field_speaker_name');
                                $speaker_name = field_view_value('node', $node, 'field_speaker_name', $fields[$index]);

                                    if ($fields) {
                                    print render($speaker_name);
                                            }
                            ?>
                        </div><!--end field-->

                    </div><!--end row--><br>
                      <?php     }?><!--end for loop-->

```
> 0 votes

# Answer
Assuming you already have a node template for that content type already (if not then you can read more here). Within the template, instead of outputting all content in one print command, you'd break them down into the fields you need. Then you can output the image field and programmatically limit it to the first value, as described in this SE post.
> 0 votes

---
Tags: nodes, entities
---


title: How can I remove duplicate value?

text:
# Question
Title: How can I remove duplicate value?
I have used custom code. I want to remove duplicate value using distinct, how can I do this? My code is like this.

```
$media_query = db_select('node','n');
    $media_query->innerJoin('field_data_field_media_room_type','mtype','mtype.entity_id = n.nid');
    $media_query->fields('n',array('nid'));
    $media_query->fields('mtype',array('field_media_room_type_tid'));
    $media_query->condition('n.type','media_room_page','=');
    $media_query->condition('mtype.field_media_room_type_tid',$media_id,'=');
    $media_res = $media_query->execute();
    while($media_fetch = $media_res->fetchObject()){
     $media_year = '';
        if(isset($media_node->field_year['und'][0]) && $media_node->field_year['und'][0] !=''){
            $media_year = $media_node->field_year['und'][0]['value'];
        }
      echo'<pre>';print_r($media_year);
    }

```

Output like this:

2011

2011

2011

2011

2011

2011

2012

2012

2013

I want to remove duplicate values so how can I remove it?

# Answer
You can try like

```
 $media_query = db_select('node','n')
         ->distinct()->innerJoin('field_data_field_media_room_type','mtype','mtype.entity_id = n.nid');
        ->fields('n',array('nid'));
        ->fields('mtype',array('field_media_room_type_tid'));
        ->condition('n.type','media_room_page','=');
        ->condition('mtype.field_media_room_type_tid',$media_id,'=');
        $media_res = $media_query->execute();
        while($media_fetch = $media_res->fetchObject()){
         $media_year = '';
            if(isset($media_node->field_year['und'][0]) && $media_node->field_year['und'][0] !=''){
                $media_year = $media_node->field_year['und'][0]['value'];
            }
          echo'<pre>';print_r($media_year);
        }

```

or

you can use `Group By` for that particular column.
> 0 votes

# Answer
Add `$media_query->distinct();` in line 2
> 0 votes

---
Tags: forms, hooks
---


# Question
Title: Entity Reference Field: How to filter a View entity reference
Using Drupal 8 I want to create a field that references certain Views that the user should be able to choose from when editing a node. Creating this reference is possible using the reference field type and choosing "View" as the type to reference.

The problem is I also want to filter which views should be selectable. This does not seem to be possible.

When referencing for example nodes, there's an option to select which bundles should be referenceable. Is there any way to do something similar for views, or for config entities in general? Or is there any contrib module available for this? Maybe there'a a hook / plugin I could implement to filter the referenceable views programmatically?

# Answer
> 2 votes
Yes, the options you can select from there are plugins.

As you found out, you can't use views with config entities, but you can implement one yourself.

There are two ways to do that, one is to define your own plugin that you can select there, like `ViewsSelection` does it. Or, it is possible to provide a version of the default plugin (`DefaultSelection`) that is automatically used for a specific entity type, see for example `TermSelection`.

I would however only use the second pattern if it is your own entity type, and otherwise define a separate plugin (you can still extend from `DefaultSelection` and re-use the code there).

---
Tags: views, entities, 8
---


# Question
Title: Does disabling a views features module remove the view from the DB
Inherited a site with 3 features modules, one is just a collection of *`views`*. i disabled it in the features interface. expecting it to disable all the views that were defined in that features module. but nothing happened... the site is huge (full publishing house)

I disabled it because theme hooks were not being applied think this has something to do with the way features is implemented.

I would like to know if once you've imported a `views` only features module it is imported to the db. and i can continue believing that i've broken nothing.

# Answer
Disabling features will not disable all views in that features. Feature is only used to export configurations,views etc to avoid manual work. You need to disable view from its UI page.
> 1 votes

# Answer
Even if you disable that Views feature module, all Views including in there will not be disabled, you have to disable them manually (or use `drush views-disable`). The reason is that , as mentioned (@kannan),in features are tracked settings, configurations and code, like Views code, and there your Views are living, in code, not in the database, that's why you can't see them in your database, so you haven't done something wrong :)

Have you correct implement your hook\_themes (don't forget `drush cc all` after any hook implementation), because there are no many ways (actually there is only one) to implement a feature in Drupal
> 1 votes

---
Tags: 7, views, features
---


title: How do I attach views to nodes?

text:
# Question
Title: How do I attach views to nodes?
I have created a `page` called '**Page1**' of Content type '**Article**' - I have created a `View1` in `Views` and would like to know how to add that view to my page.

***Does Views replace the needs of the 'add content' button on my admin page?***

# Answer
> 4 votes
Create a view with '**Block**' display. After it is created, make it display on the page you want.

How:

* Go you `sitename/admin/structure/views/add`
* Unchecked create a page option
* Check Create a block
* Give the Block title and select your desired display format
* Click Continue & edit
* Setup your view as per you wish
* Click Save
* Go to `sitename/admin/structure/block`
* Look for your new view block "search for block name you give early while creating the view"
* Click configure
* if you don't want your block title replace your Block title with
* Select in which region you would like to have your view
* Go to end of the page, under Show block on specific pages select "only the listed pages"
* enter the url of page you want your view to be available, for example if your page url is `www.your_site/page1`. Than add page1 in the box.

Please note you can add as many pages as you want and you can also use content type of specify in which node type you want your view to be visible.

# Answer
> 2 votes
You con use EVA (Entity Views Attachment)

> it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

The view should be available as a field in the manage presentation of the entity, it is easy to use if you know how to create views

# Answer
> 2 votes
When creating a View "page" or a "block" by default. If you chose to create a "page" you are right, you don't need to "`add content > page`" as this is done automatically and the page will be at `yoursite.com/path` where "path" is whatever you set in the "Page settings" (top of the middle column) Path field. e.g. "`/page1`" in your example

# Answer
> 0 votes
> Does Views replace the needs of the 'add content' button on my admin page?

No, Views is just a powerful tool to query the contents of your database and to show this contents in lists e.g. Views can be used e.g. to combine fields from different content types to create comprehensive collections of information and then show them when certain and configurable rules (like arguments and relationships) are met.

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


# Question
Title: Which module hook to use for CRUD operations on custom table?
I have used `hook_schema()` in my module to create a custom table in the Drupal database - the data is unrelated to anything in Drupal.

I would like administrators to be able to insert, update etc. records in this custom table. I had thought to use the function `hook_form()` for this, but upon closer inspection this hook relates back to nodes. My custom table has no relation to nodes.

Is there a different function I should be using?

# Answer
You don't need to call any special hooks. You just need to create menu items for `insert/edit/delete/list` of data.

Here is an example module that create basic crud using custom table.

If you want to create listing with views instead of custom listing callback function you will need to use `view_api` and `hook_views_data` in your module for that.
> 1 votes

---
Tags: 7, forms, database, hooks
---


# Question
Title: Clean urls working everywhere except my custom module
I'm attempting to create a custom drupal module, but I can't get clean urls to work. Clean urls have been enabled and are working everywhere else on the site.

I can access my module page using "?q=" but if I remove that and try to access it with the clean url I get a "page not found" error.

I've tried clearing the cache and rebuilding the menus using devel. I've also tried disabling and re-enabling my module.

Here's the code I have in my .module file.

```
/**
 * @file
 * This example demonstrates how a module can display a page at a given URL.
 */

/**
 * Implements hook_menu().
 */
function page_example_menu() {
  $items['examples/page_example/simple'] = array(
    'title' => 'Simple - no arguments',
    'page callback' => 'page_example_simple',
    'access arguments' => array('access simple page'),
  );

  return $items;
}

/**
 * Constructs a simple example page.
 *
 * @return array
 *    The render array for the simple example page.
 */
function page_example_simple() {
  return array('#markup' => '<p>' . t('Simple page: The quick brown fox jumps over the lazy dog.') . '</p>');
}

```

# Answer
> 0 votes
Turns out the issue was in my company's custom configuration. Certain pages are routed via Drupal while others are handled by a legacy system. All I had to do was add my module's path to our config and everything works now.

---
Tags: 7, uri
---


title: Render a button in a block

text:
# Question
Title: Render a button in a block
I want to display a button on the homepage. The best solution i've thought about was to render it in a block. The code is the following :

```
  $button['my_tickets'] =array(
    '#type'       => 'link',
    '#title'      => t('My tickets'),
    '#href' => '',
    '#class' => 'btn btn-default',
    '#id' => '',
    '#options' => array(
      'html' => true,
    )
  );

```

And here's the theme :

```
  function My_module_theme() {
    return array(
      'my_module_my_button' => array(
        'variables' => array('vars' => NULL),
        'template' => PATH_TO_TEMPLATE,
      ),
    );
  }

```

**Problem** : The link isn't rendered with the classes inside the "a" tag. How can I do that ?

# Answer
I think the classes should be added in the attributes array:

```
 $button['my_tickets'] =array(
    '#type'       => 'link',
    '#title'      => t('My tickets'),
    '#href' => '',
    '#attributes' => array('class' => array('btn', 'btn-default')),
    '#id' => '',
    '#options' => array(
      'html' => true,
    )
  );

```
> 2 votes

# Answer
You should use the following code instead

```
$link = array(
  '#theme' => 'link',
  '#text' => 'Click Here',
  '#path' => $path,
  '#options' => array(
    'attributes' => array('class' => array('cool-class'), 'id' => 'cool-id'),
      //REQUIRED:
      'html' => true,
   ),
);

```
> 1 votes

# Answer
That seems like a slightly complex way of making a button, Why not just add to your **page** or **page-front** template: `<a href="your-link-destination" class="btn btn-default">My tickets</a>`
> 0 votes

---
Tags: forms, blocks, theming
---


# Question
Title: $base_url not working when in anchor link to theme folder
e.g. this:

```
<a href="<?php echo $front_page; ?>" title="<?php echo t('Home');?>" rel="home" id="logo">
        <img src="http://localhost/jamesbondblog/sites/all/themes/jamestheme/images/logo.jpg">
</a>

```

is working.

But this is not:

```
<a href="<?php echo $front_page; ?>" title="<?php echo t('Home');?>" rel="home" id="logo">
        <img src="<?php echo $base_url; ?>/sites/all/themes/jamestheme/images/logo.jpg">
</a>

```

Can someone explain why?

I am using Drupal 7 and this code is in page.tpl.php

# Answer
what about  `global $base_path;` ?
> 2 votes

# Answer
Try this...

In your themes template...

```
function YOURTHEME_preprocess_page(&$variables) {
   global $base_url;
   $variables['base_url'] = $base_url;
}

```

In page template...

```
$base_url;

```
> 2 votes

# Answer
**SOLVED (with an error message in admin :(**

Instead of `<?php echo $base_url; ?>`

you need to use `<?php global $base_url; echo $base_url; ?>`

But it keeps saying in my modules this error message:

```
Notice: Undefined variable: base_url in include() (line 9 of C:\wamp\www\jamesbondblog\sites\all\themes\jamestheme\page.tpl.php).

```

Thanks in advance for a fix to get rid of this error message.
> 0 votes

# Answer
You can use `$GLOBALS['base_url']` instead, for example:

```
<img src="<?= $GLOBALS['base_url'] ?>/sites/all/themes/foo/images/logo.jpg">

```
> 0 votes

---
Tags: uri
---


title: adding a description to view accordion

text:
# Question
Title: adding a description to view accordion
I am using a view with the format Views Accordion.
So far, I have a View like so:

> award1
> -person1
> -person2
> ...
> award\_n
> -person\_n
> -person\_n+1

Where award is the "header" or "trigger" of the accordion action. This works just as intended. I'm trying to extend this further to look something like:

> award1
> This is a description of award1. I'm summarizing award1 here.
> -person1
> -person2
> ...
> award\_n
> This is a description of award\_n. I'm summarizing award\_n here.
> -person\_n
> -person\_n+1

The problem is when i use views accordion with a description like above i get the not so desired result:

> award1
> This is a description of award1. I'm summarizing award1 here.
> -person1
> This is a description of award1. I'm summarizing award1 here.
> -person2

Where the description and the person are overlapping and/or pushing the content out of the accordion effect. I've thought about using Javascript to insert the description after the award div, but i feel like that is a hacky approach to the solution. Is there a better way to do this?

# Answer
Following up on Volker's comment, I created a new person with the name "award\_name description" and assigned the proper award to the person just created.

In Views Accordion settings I checked the box "Add views row classes Add the default row classes like views-row-1 to the output."

Style the views-row-1 class to make the description pretty.

I have the setting "Add striping (odd/even), first/last row classes", so i had to edit the CSS to swap even and odd so the description has a white background.

Hope this helps someone with a similar problem!
> 1 votes

---
Tags: views, navigation
---


# Question
Title: Using multiple templates in a Drupal 8 module
I have produced a simple Drupal module which provides a **wrapper** for a JavaScript library. I'm working on a separate module which will produce several pages of examples of the library and wrapper in action. These pages will each contain a two sections, the library, and description text and miscellaneous `HTML`.

What is the best technique to do this the **Drupal 8** way? I can imagine two strategies:

* Each page will be a separate function within my controller. The function can first add two entries to the output array, the first will contain the data for the library, and the second the raw HTML and text.
* In the second technique, I would place all the HTML and text in a twig template. Then I would add all the data for the library in the controller and add a reference to this new theme template as a second entry in the output array. I like the idea of this second strategy, but I don't know how to accomplish it. I've look at code for several Drupal 8 projects and read a few tutorials, and I haven't seen an example of this. The hook\_theme function always contains a single return statement. How would I add a switch or if statement within `hook_theme` to determine which twig template to return.

If there is a third option that is even better, let me know.

# Answer
> 4 votes
hook\_theme() returns a *list* of templates that will then be cached in the registry. You don't need conditions there, in fact, you can not, since it will be called only once.

Just return multiple templates and then reference them in your render arrays, like you already have to when using a single one.

---
Tags: 8
---


# Question
Title: How can I include Guzzle as a library in a distribution?
I'm working on Open Atrium 2 and we'd like to include Guzzle with the initial install so that we can build some integration features on top of it.

Usually, including a library just means adding the library to the drush make file, but Guzzle is more complicated because:

1. it has a few dependencies.
2. it's meant to be installed by Composer or Pear, not by direct download.
3. it's not on the packaging whitelist on Drupal.org, but I can request that it be added since the license doesn't conflict.

So how can I make this happen? Is there a pre-bundled-and-ready-to-use package somewhere that includes all dependencies, in which case I can just request that that be whitelisted for Drupal.org and use that? Or is installing Guzzle tricker than just including a bunch of files that can be placed in `sites/all/libraries`?

Any ideas?

# Answer
> 1 votes
I disabled composer system wide on my machine and create a make file and it works fine installing Drupal 7 core plus the following modules: composer, composer\_autoload & guzzle.

This is the content of platform.make

```
$Id$

; API

api = 2

; Core

core = 7.x

; Drupal project.

projects[drupal][type] = core
projects[drupal][version] = 7.x
projects[drupal][download][type] = git
projects[drupal][download][branch] = 7.x

; Modules

projects[composer] = 1.x-dev
projects[] = composer_autoload
projects[] = guzzle

```

# Answer
> 1 votes
Use Composer Manager which would allow you to install PHP libraries managed via Composer and their dependencies on a per-project basis.

So (as per module's README.md):

> If a module contains a `composer.json` file, running `composer
>  install` in its root directory will download all requirements and dependencies to `vendor/` directories with their own autoloaders.

The Guzzle challenge is explained in README.md:

> To highlight the challenges, let's say `module_a` requires `"guzzle/http": "3.7.*"` and `module_b` requires `"guzzle/service":
>  ">=3.7.0"`. At the time of this post, running `composer install` in each module's directory will result in version 3.7.4 of `guzzle/http` being installed in `module_a`'s `vendor/` directory and version 3.8.1 of `guzzle/service` being installed in `module_b`'s `vendor/` directory.
>
> Because `guzzle/service` depends on `guzzle/http`, you now have duplicate installs of `guzzle/http`. Furthermore, each installation uses different versions of the `guzzle/http` component (3.7.4 for `module_a` and 3.8.1 for `module_b`). If `module_a`'s autoloader is registered first then you have a situation where version 3.8.1 of `\Guzzle\Service\Client` extends version 3.7.4 of `\Guzzle\Http\Client`.

So by using the Composer Manager's Solution, it finds all `composer.json` files in each enabled module's root directory and gracefully merge them into a consolidated `composer.json` file (which prevents code duplication and version mismatches).

> For the use case above, Composer will resolve both `guzzle/http` and `guzzle/service` to version 3.7.4 which is a more consistent, reliable environment.

---

So to answer the question: yes, you can include that in a Drupal installation in `sites/all/vendor`, e.g.

* `sites/all/vendor/composer`
* `sites/all/vendor/guzzlehttp`

---
Tags: 7, theming, distributions
---


# Question
Title: How do I initialise store in-app-purchase?
I am experimenting with DrupalGap and it's great what it already provides out of the box. One feature that module is missing is in-app-purchasing (where payments go via Apple).

Cordova provides a great cross-platform plugin with some good documentation.

This is a full example, and this a minimal example.

```
document.addEventListener('deviceready', initializeStore, false);

function initializeStore() {

// Let's set a pretty high verbosity level, so that we see a lot of stuff
// in the console (reassuring us that something is happening).
store.verbosity = store.INFO;

// We register a dummy product. It's ok, it shouldn't
// prevent the store "ready" event from firing.
store.register({
    id:    "com.example.app.inappid1",
    alias: "100 coins",
    type:  store.CONSUMABLE
});

// When every goes as expected, it's time to celebrate!
// The "ready" event should be welcomed with music and fireworks,
// go ask your boss about it! (just in case)
store.ready(function() {
    console.log("\\o/ STORE READY \\o/");
});

// After we've done our setup, we tell the store to do
// it's first refresh. Nothing will happen if we do not call store.refresh()
store.refresh();
}

```

**How can I add the document.Eventlistener and the initalization function within DrupalGap?**

The cordova plugin is installed, the products are set up in iTunes and the provisioning profiles with in-app-purchasing feature are created. I have created a custom module with a menu link in DrupalGap where the user can make his in-app-purchases.

**UPDATE:**

This code works (Thanks, Tyler) and connects to the iTunesConnect store and pulls the requested/registered products.

You don't need a sandbox user to pull the products.

You do need to submit Apple the 3 legal documents even if you only use a development provisioning profile. It takes a few hours until the docs are submitted.

Here is another useful link (when your product is invalid): http://troybrant.net/blog/2010/01/invalid-product-ids/

```
/**
 * Implements hook_deviceready().
 */
function my_module_deviceready() {
// Let's set a pretty high verbosity level, so that we see a lot of stuff in the console (reassuring us that something is happening).
//store.verbosity = store.INFO;
store.verbosity = store.DEBUG; // even higher

// We register/request a product:
store.register({
id: "130points", // this is id of your product in iTunesConnect
alias: "130points_alias",
type: store.CONSUMABLE
});
// When every goes as expected, it's time to celebrate!
// The "ready" event should be welcomed with music and fireworks,
// go ask your boss about it! (just in case)
store.ready(function() {
console.log("\\o/ STORE READY \\o/");
});
// When any product gets updated, refresh the HTML.
store.when("product").updated(function (product_item) {
console.log("product_item: " + JSON.stringify(product_item)); // this is the response from iTunesConnect
});
// After we've done our setup, we tell the store to do it's first refresh. Nothing will happen if we do not call
store.refresh();
return true; // Let DrupalGap know it is OK to continue.
}

```

# Answer
In a DrupalGap Custom Module, you'll use hook\_deviceready():

```
/**
 * Implements hook_deviceready().
 */
function my_module_deviceready() {
  // Place your initializeStore function's code here...

  return true; // Let DrupalGap know it is OK to continue.
}

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to properly inject mutable config to the controller?
Apparently by default `ControllerBase::config()` returns `\Drupal\Core\Config\ImmutableConfig` object. How can I instantiate the controller class to make it use `\Drupal\Core\Config\Config` instead (which is mutable)?

I know I can do this inside the controller:

```
$config = \Drupal::service('config.factory')->getEditable('loremipsum');

```

However this is not the nicest solution. Besides, is there any reason for using `ImmutableConfig` by default?

# Answer
> 9 votes
There are two other ways to inject dependencies into a controller, and a third alternative.

### 1. Implement ContainerInjectionInterface

This does technically add a dependency to the container. In a unit test, the container would need to be set with `\Drupal::setContainer()` with a mock object of the config factory and config object.

\`

```
  public static function create(\Symfony\Component\DependencyInjection\ContainerInterface $container) {
    return new static($container->get('config.factory'));
  }

  public function __construct(\Drupal\Core\Config\ConfigFactoryInterface $config_factory) {
    $config = $this->config_factory->getEditable('loremipsum');
  }

```

\`

### 2. Make the controller a service.

This is recommended by all of the Symfony developers that I have asked, and none have been concerned by any performance impact of making all of Drupal's routes use services.

This is subjective, and there is some contention about the practice.

### 3. Use a Form class that extends ConfigFormBase instead.

But, why would a controller want MutableConfig instead of ImmutableConfig? A Form class extending ConfigFormBase instead. A form is probably the best place to modify configuration values such as a class that extends ConfigFormBase.

---
Tags: 8
---


title: use solr for /search

text:
# Question
Title: use solr for /search
In my site (camperlife.it) I have installed sorl + search api solr and all works for sections where solr is active (like /aree-di-sosta-italia.html). Now I want to substitute /search (search modules) with search api + solr.

Is there a module/way to do it (simple) or I need to create a view for this?

# Answer
> 1 votes
I'd just disable the core search module for performance reasons and create a view with Search API views unless you're already using panels and you can integrate a much richer solution, for example the one described in: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels

# Answer
> 1 votes
An alternative to @pcambra's response is to the use the Search API Pages module. As the d.o. page describes;

> This module is for creating simple search pages for the Search API project, not using Views or any other modules. They can be used when a view would be unnecessarily slow or complex, or for quickly testing out functionality. They also provide search blocks for starting a search from anywhere on the site.

Like pcambra, I'd disable native search if I have my site SOLR-indexed.

---
Tags: 7, search
---


# Question
Title: Why would custom module code fail when called from drush but work fine when invoked from cron button in admin/config/system/cron?
Background: I have developed a custom module to process a CSV file of user data imported from an external system. The module updates the standard Drupal user fields and also their Profile 2 fields. I have tested this via pressing the cron button on admin/config/system/cron and it works fine. However, ultimately I don't want to run this with cron but instead at a single specific time regular time. I want to invoke it via Jenkins issuing a drush command. So I implemented a drush command and issued this and got the following (names have been changed in case of an issues making public). Here's what I see when I issued the drush command (my development environment details follow the output):

```
$ drush mysync
WD user: PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'name' at row 1: INSERT INTO {users} (uid, name, pass, mail, created, status,  [error]
init, data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
:db_insert_placeholder_6, :db_insert_placeholder_7); Array
(
    [:db_insert_placeholder_0] => 17328
    [:db_insert_placeholder_1] => RequestTimeTooSmywebsiteedThe difference between the request time and the current time is too
large.20151222T173152Z2015-12-22T17:50:06Z9000007C6B68377122D467B3WpFicMSuociMXhAz4zJ4aydh6THmo7Q5gcBRkVdY86d962a3J+F+wx93sgHOdFQIUZYpg4pLE=
    [:db_insert_placeholder_2] => $S$D9dNnB8ROhS9.EZudAfxp/dvkbD1f4HswTAzRJ1q4KbaldtmzwzR
    [:db_insert_placeholder_3] =>
    [:db_insert_placeholder_4] => 1450805510
    [:db_insert_placeholder_5] => 1
    [:db_insert_placeholder_6] =>
    [:db_insert_placeholder_7] => a:2:{s:7:"contact";i:1;s:17:"mimemail_textonly";i:0;}
)
 in drupal_write_record() (line 7316 of /var/www/mywebsite.dev/includes/common.inc).
exception 'PDOException' with message 'SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'name' at row 1' in                                            [error]
/var/www/mywebsite.dev/includes/database/database.inc:2171
Stack trace:
#0 /var/www/mywebsite.dev/includes/database/database.inc(2171): PDOStatement->execute(Array)
#1 /var/www/mywebsite.dev/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)
#2 /var/www/mywebsite.dev/includes/database/mysql/query.inc(36): DatabaseConnection->query('INSERT INTO {us...', Array, Array)
#3 /var/www/mywebsite.dev/includes/common.inc(7316): InsertQuery_mysql->execute()
#4 /var/www/mywebsite.dev/modules/user/user.module(582): drupal_write_record('users', Object(stdClass))
#5 /var/www/mywebsite.dev/sites/all/modules/custom/mywebsite_externalsystem_integration/mywebsite_externalsystem_integration.module(564): user_save('', Array)
#6 /var/www/mywebsite.dev/sites/all/modules/custom/mywebsite_externalsystem_integration/mywebsite_externalsystem_integration.module(239): _mywebsite_externalsystem_integration_create_new_user(Array)
#7 /var/www/mywebsite.dev/sites/all/modules/custom/mywebsite_externalsystem_integration/mywebsite_externalsystem_integration.module(26): _mywebsite_externalsystem_integration_update_and_create_user_records(Array)
#8 /var/www/mywebsite.dev/sites/all/modules/custom/mywebsite_externalsystem_integration/mywebsite_externalsystem_integration.drush.inc(17): _mywebsite_externalsystem_integration_sync()
#9 [internal function]: drush_mywebsite_externalsystem_integration_externalsystem_sync_command()
#10 /usr/share/drush/includes/command.inc(359): call_user_func_array('drush_mywebsite_ag...', Array)
#11 /usr/share/drush/includes/command.inc(210): _drush_invoke_hooks(Array, Array)
#12 [internal function]: drush_command()
#13 /usr/share/drush/includes/command.inc(178): call_user_func_array('drush_command', Array)
#14 /usr/share/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#15 /usr/share/drush/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#16 /usr/share/drush/drush.php(11): drush_main()
#17 {main}

```

My environment:

* Ubuntu 14.04 Linux VM provisioned via puphpet.com manifest using Vagrant running on Mac OS X El Capitan
* PHP version: PHP 5.6.16-2+deb.sury.org~trusty+1 (cli)
* I have compared the php.ini files for Apache (Web) and for CLI (that drush uses) - see screenshot (the file names have been renamed and moved to a position where my host comparison tool, Beyond Compare can compare them in the shared file system of the VM):

* I did some research and a plausible reason for the error is that the UTF character set is different, e.g. it was UTF-8 on apache (where it worked and perhaps UTF-16 on drush cli where it fails with the truncation - because twice the width, however, they are both the same:

I just don't understand why this code would work when run within Drupal via the web, but not in drush. The database attempted to be written to is the same, the data I'm attempting to write is the same, it must be some kind of environmental difference, but apart from php.ini I don't know what it could be. Please advise.

# Answer
> 2 votes
Since you're having MySQL error, you should rather check `my.cnf`, not `php.ini`, unless PHP CLI and Apache are using different instances of MySQL (via `mysql.sock`).

However your problem is something else.

You you look closely into the error:

> Data too long for column 'name' at row 1

it complains that your `name` column is too long.

Now check your db placeholders:

`uid`:

```
[:db_insert_placeholder_0] => 17328

```

`name`:

```
[:db_insert_placeholder_1] => RequestTimeTooSmywebsiteedThe difference between the request time and the current time is too

```

that means you've problem with the username, as above value is not valid username, secondly it's too long.

So you've to double check the code in:

```
mywebsite_externalsystem_integration.module:564: user_save('', Array)

```

and its `Array` (especially value of `name`).

The way how you call it:

```
#5 mywebsite_externalsystem_integration.module(564): user_save('', Array)
#6 mywebsite_externalsystem_integration.module(239): _mywebsite_externalsystem_integration_create_new_user(Array)
#7 mywebsite_externalsystem_integration.module(26): _mywebsite_externalsystem_integration_update_and_create_user_records(Array)
#8 mywebsite_externalsystem_integration.drush.inc(17): _mywebsite_externalsystem_integration_sync()

```

doesn't seems you're running cron task from your code (but executing custom `drush` command), so nothing to do with it, that's why it's not happening during your `cron.php`.

So to summarize it, this is a bug of your custom code which you need to find and fix it.

---

Check: `user_save()` API for the valid syntax, where:

> `$edit`: An array of fields and values to save. For example array('name' =\> 'My name').

---

Going more deeply, the following error (changed based on my assumption):

> RequestTimeTooSkewed: The difference between the request time and the current time is too large.

sounds like the error of Amazon S3 service (possibly you're using Storage API module). So I assuming your code doesn't have failing scenario and populating the error message, instead of the username (connecting issues?).

So the only difference between Web and drush is how the code implements the user import. If you're using some specific credentials or performing HTTP requests, make sure you're loading the right variables, site profile, using the right host, proxy settings, etc. Plus print some debugs (`-v`/`-d`). For example:

```
drush -vd -l http://mywebsite.dev mysync

```

and check your watchdog messages (`drush ws --tail`).

Some people suggests that your local box is out of sync with the current time, so try to correct it.

So please double check that you followed installation instruction of the module correctly, as below:

> This service requires an account with the external service provider. Please refer to the online documentation for additional help: https://www.drupal.org/node/656716

See: Amazon S3 at Drupal.org

So possible solution is to run as root the following commands:

```
ntpdate ntp.ubuntu.com
echo "ntpdate ntp.ubuntu.com" >> /etc/cron.daily/ntpdate && chmod 755 /etc/cron.daily/ntpdate

```

depending on your Linux distribution.

---
Tags: 7, drush
---


title: Reindex a select group of nodes

text:
# Question
Title: Reindex a select group of nodes
I am maintaining a site that I did not build. It was discovered that some 300 nodes of type "custom" had incorrect url aliases. There are a total of 7961 nodes of type "custom" in the site at this moment.

```
$ drush sql-query "SELECT COUNT(nid) FROM node WHERE type LIKE 'custom';"

```

I have found the list of solr drush commands, and I see that `solr-delete-index` is able to remove a specific content type and then `solr-mark-all` could be used to indicate they should all be reindexed. My question is, **how can I reindex only the 300 bad ones on this live site**. I do have their nids in a separate csv file already, made from a custom sql query.

Just to be clear:

* the site is live and important it stays that way
* there is only a small portion of the content type that needs reindexed
* I have all the permissions and access, no need to ask if I can get somewhere. Assume I can.
* I have the means to identify the nodes to reindex and pipe them to various things and languages. I would even `xargs` a custom drush script if you have a means for doing this to a single node.

# Answer
In case you don't find a better way (doesn't look like there's an existing Drush command), here's a pretty simple solution cobbled together from various functions in the module:

```
$solr = apachesolr_get_solr();
$nids = array(1, 2, 3, 4, ...);
foreach ($nids as $nid) {
  $solr->deleteById(apachesolr_document_id($nid));
  db_update('apachesolr_search_node')
    ->condition('nid', $nid)
    ->fields(array('changed' => REQUEST_TIME, 'status' => 1))
    ->execute();
}
apachesolr_index_set_last_updated(REQUEST_TIME);

```

Untested, use with caution!
> 1 votes

---
Tags: 7, search
---


title: views NO RESULTS BEHAVIOR i18n

text:
# Question
Title: views NO RESULTS BEHAVIOR i18n
Is there a way to show different no results behaviors for different languages in views 3.

# Answer
Please check this link as there is no way translate the views you just can filter the content of specific language of logged-in user. for enabling translation you check out the Internationalization Views module.

> Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet. **Requires Internationalization 6.x-1.5 or newer**.
> 1 votes

# Answer
Use a current version of i18nviews and ensure that the text format used for the text area is selected as translatable in `/admin/config/regional/i18n/strings`
> 1 votes

---
Tags: views
---


title: Inconsistent "UND" value in node fields

text:
# Question
Title: Inconsistent "UND" value in node fields
I'm manually printing my node fields on its template (node--TYPE.tpl.php). Something like:

```
<div class="row">
    <div class="press-year col-md-12">
        <h2><?php print $year; ?></h2>
    </div>
</div>

```

And my hook\_preprocess\_node() looks something like:

```
function MY_MODULE_preprocess_node(&$vars) {
    switch ($vars['type']) {
        case "my_type":
           if (isset($vars["field_year"]["und"][0])) {
              $vars["year"] = $vars["field_year"]["und"][0]["value"];
          }
        break;
    }
}

```

The output is fine to all fields; however, when I view the node as administrator, no output is printed. I listed all the variables from the hook to see what was happening with the following code.

```
function MY_MODULE_preprocess_node(&$vars) {
    var_dump($vars);
    ....
}

```

I'm getting all fields without the "UND" value, `$vars["field_year"][0]["value"]` instead of `$vars["field_year"]["und"][0]["value"]`.

Do you have any clue why this happens?

# Answer
I was having the same problem with D7. The solution for me was to use field\_get\_items(...) for reading the node data.

```
$year_items = field_get_items('node', $variables['node'], 'field_year');
$year = $year_items[0]['value'] + 1;

```

I found the post on Rendering Drupal 7 fields (the right way) very helpful. It does seem strange that we shouldn't use the $variables provided to the preprocessor and template to read and modify the template variables. I must be missing something.
> 1 votes

---
Tags: nodes, theming
---


# Question
Title: How to get author_picture URL from a template?
How to get **author\_picture** URL from a template ? I know that I can use `{{ author_picture }`} to display the picture; however, all I need is the URL and not the picture. I'm trying to get this URL from the template **node--article.html.twig**

Here is a similar question but this is different because is base on the field\_image. Getting the image URL from a field\_image on a node and all I'm trying to get is the author picture.

# Answer
### URL FORMATTER module

> This module add a url formatter for image field. Then you can output image url directly.

Once enabled, go to your user manage fields, and change the picture field formatter to url.

```
{{ author_picture }}  // will display url instead of picture

```

If you are using views, views will give you an option to change the format to url.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to insert html tag "id" in an image field in a view
I need to add ***id tag*** to an image which is a field of a `view`. Currently it seems only possible to add a class name.

`<img typeof="foaf:Image" ...` must become =\> `<img id="xxx" typeof="foaf:Image" ...`

# Answer
Searching for typeof="foaf:image" I found that was set by rdf module preprocess\_image, not in views. Therefore I added a preprocess function

```
function MYTHEME_preprocess_image(&variables){
  // compute first MY_UNIQUE_ID
  $variables['attributes']['id'] = array('MY_UNIQUE_ID');
}

```

now it works.
> 1 votes

---
Tags: 7, views, media
---


title: How to fix "Undefined index"

text:
# Question
Title: How to fix "Undefined index"
I'm working on displaying information about users on their profile pages.

I want to display a field; if this field is not completed then I display a text message, else, I display its value.

I've written this code:

```
<?php
     $username = $user_profile['field_username'];

     if($username == "") {
       echo 'Please enter a user';
     } else {
       print render ($user_profile['field_username']);
     }
?>

```

I get this error:

> Undefined index : field\_username

But the code is working properly.

# Answer
With the following line of your code:

```
$username = $user_profile['field_username'];

```

It always gets executed and check index field\_username. So in case if the index doesn't exist it throws error.

If you replace your code with the following

```
if(empty($user_profile['field_username'])) {
  echo 'Please enter an user';
} else {
  print render ($user_profile['field_username']);
}

```

It will not always check field\_username index but only if it is not empty.
> 2 votes

# Answer
The error:

> Undefined index : field\_username

informing you that you've **Undefined index** in your array.

It is similar to:

> PHP: Notice: Undefined variable

which says that you've **Undefined variable**.

Either way, it is just a **notice**, so the code always would work in that kind of error without affecting any functionality. These kind of messages are displayed on the screen, to help programmers to track the potential code issues.

> Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.php.net

---

In your case the notice in the following code:

```
$username = $user_profile['field_username'];

```

means that PHP couldn't find `field_username` key inside the `$user_profile` array. This could mean several things, such as typos, missing field name, loading empty object or the one without that field, etc.

You can of course disable that kind of errors, but the real problem is that your code isn't written well and it takes some time and experience to follow the coding standards which helps you to avoid such issues.

To avoid the notice, your code can be simplified to one-line of code:

```
echo !empty($user_profile['field_username']) ? render($user_profile['field_username']) : t('Please enter a user');

```

If you've more questions about your code quality, you can always ask at Code Review Stack Exchange.

For more reading, check: PHP: “Notice: Undefined variable” and “Notice: Undefined index” at SO
> 1 votes

---
Tags: entities, users
---


# Question
Title: What is the benefit of Node Blocks module versus adding content to blocks in body field?
What is the benefit of Node Blocks module versus adding content to blocks in body field?

It seems like the functionality is identical?

Either create content, and use it as a block.

Or create a block and add content to it.

# Answer
Nodeblock

> This module allows you to specify content type(s) as being a block. This \> allows \> the content managers of the site to **edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.**

Also, based on above I imagine that you don't need to assign the block a region and a "display only on url". (I could be wrong, never used this module).
> 1 votes

---
Tags: nodes
---