# Question
Title: Unable to send email local configuration problem
I'm getting strange email errors on User Registration, when a user creates an account on my website, it emails them a link to activate their account, however, its started showing errors at the top of the email as shown below. I had everything working fine, emails going out, now i get these errors and Im not sure what I have changed to cause this. I did install the Honeypot module and Captua module last night (also have User Registration Password), but Im sure I tested afterwards and it was working fine. Any ideas? I have changed the email addresses below to make them anonymous.

On 8 Feb 2016, at 13:23, Mail Delivery System wrote:

A message that you sent was rejected by the local scanning code that checks incoming messages on this system. The following error was given:

local configuration problem

------ This is a copy of your message, including all the headers. ------

Received: from 707134 by linweb.ahost.me with local (Exim 4.80.1) (envelope-from ) id 1aSlmr-0003aW-L4 for yyy@gmail.com; Mon, 08 Feb 2016 13:23:29 +0000 To: yyy@gmail.com Subject: Account details for testuser at zzz Club MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes Content-Transfer-Encoding: 8Bit X-Mailer: Drupal Sender: xxx@icloud.com From: xxx@icloud.com Message-Id: Date: Mon, 08 Feb 2016 13:23:29 +0000

testuser,

Thank you for registering at zzz Club. You may now log in and verify your account by …..

# Answer
> 0 votes
This was resolved by setting up a 'anything@mydomain.co.uk' with my host, and setting this to my email address under Configuration/Site Information, and also under the settings for the Trigger rule I set to send an email when a user is created.

---
Tags: users, emails
---


# Question
Title: No emails being sent when using User Registration Password set up
When a new user registers with my website it displays "Thank you for applying for an account. Your account is currently pending approval by the site administrator. In the meantime, a welcome message with further instructions has been sent to your e-mail address."

However, no email is sent from the site at all.

I have my settings so that approval is required from the administrator before the user can be activated. Also, they set their password up on the registration screen.

Im using v1.4 of the **User Registration Password module**, and Drupal 7.41

Could someone let me know why no emails go to the administrator or the users ? Emails were being sent without the module installed, but I really want users to set their password up front.

# Answer
This all works perfectly now, i needed to use an email address that belongs to my domain i.e. anything@mydomain.co.uk otherwise it gets blocked, therefore use this email in Configuration/Site Information and also in the Trigger rule I created to alert me when a new user is created. Thank you for guiding me towards using the Dev version.
> 0 votes

---
Tags: 7, users
---


title: Product Attributes Commerce

text:
# Question
Title: Product Attributes Commerce
I am moving my site from Ubercart to Commerce. I currently have some products set up with attributes that can be selected by a customer, please see this URL for an example http://www.wild-sage.co.uk/products/soap-box

How would I go about setting this up using Commerce?

# Answer
> 0 votes
Instead of dropdowns, you could use checkboxes and line item fields using Commerce custom products module.

All fields are supported as customer-facing line item fields, except some entity reference fields that use views to display their options. Note, the only limitation here would be that your fields would need to be able to react to the specific product.

Customizable products are like content types and define fields per bundle. So you would need a bundle per unique set of requirements. There is no limit, but it would probably be easier to model the "selection criteria" using fields on the products and then create a hook\_form\_alter() that would change the options available to select.

---

UPDATE: Code Example

**Assumption 1**: You've created a custom line item bundle

**Assumption 2**: You've created two fields. The first for the line item options (this would include all possibilities) and the second would be for the product (this would include any possibilities that match what that kind of product should have, doesn't need to be a complete list, but it would need to be the same ids/values of the first field).

**Assumption 3**: The workflow would look like this:

> select the soaps you would want to show PER product

Now, on the product display you would see this:

```
<?php
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    $product = $form_state['default_product'];
    $show_these = $product->field_include_these_soaps['und'];
    $all_soap_options = $form['line_item_fields']['field_soaps']['und']['#options'];
    $only_show = array();
    foreach ($show_these as $key => $value) {
      $real_key = $value['value'];
      $only_show[$real_key] = $all_soap_options[$real_key];
    }
    $form['line_item_fields']['field_soaps']['und']['#options'] = $only_show;
  }
}
?>

```

---
Tags: commerce
---


# Question
Title: Using Panelizer, how can I add a new menu item properly
I want to add a menu item *the right way* See "Edit IV Block" in the picture below.

That is the *wrong* way to do it.

The code is here: http://api.drupalecommerce.org/api/panels/panels!plugins!display\_renderers!panels\_renderer\_editor.class.php/function/panels\_renderer\_editor%3A%3Aget\_pane\_links/7.x

If you search for drupal\_alter('get\_pane\_links', $links, $pane, $content\_type); you can see that the get\_pane\_links hook is supposed to fire, but for some reason it does not fire.

My question is, it seems like drupal\_alter('get\_pane\_links') is the correct way to add menu items, but I've tried adding functions in other modules and they don't get called. I modified the code to do

```
echo 'before';
drupal_alter('get_pane_links', $links, $pane, $content_type);
echo 'after';

```

And no dice. What is the correct way to add a menu item or how to I implement this hook?

# Answer
> 0 votes
Cleared the cache and then it worked. Found this by doing a $modules = module\_implements('get\_pane\_links\_alter');

---
Tags: 7, panels
---


title: "Page not found" on custom module

text:
# Question
Title: "Page not found" on custom module
I did a custom module, but i can't see the page with the URL : Page not found. I can install the module and activiate, but i can't go on the page.

This is the code :

```
hello_world.hello_world:
  path: '/helloworld'
  defaults:
    _controller: 'Drupal\hello_world\Controller\HelloWorldController::helloWorld'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

```

---

```
name: Hello World
core: 8.x
type: module
package: Tutos
description: Mini module test Drupal 8

```

---

```
<?php
/**
 * @file
* Contains \Drupal\hello_world\Controller\HelloWorldController.
*/

namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for hello_world module routes.
 */
class HelloWorldController extends ControllerBase {

  /**
   * Return the 'Hello World' page.
   *
   * @return string
   *   A render array containing our 'Hello World' page content.
   */
  public function helloWorld() {
    $output = array();

    $output['hello_world'] = array(
        '#markup' => $this->t('Hello World!'),
    );
    return $output;
  }
}

```

# Answer
You may need a leading \ for the controller definition.
> -2 votes

---
Tags: 8
---


# Question
Title: How do I amend roles for the Administer Users by Role module?
I'm using the Administer Users by Role module. I have a role set up as *Publisher* which has all the boxes ticked under the "*Administer Users by Role*" option (under People/Permissions as shown in the picture below):

The Publisher can create/edit users. I have created a menu option for the Publisher user, which has a path of admin/people/edit so they can see all the users, and add a user too.

My problem is that when the Publisher amends or creates an account, they cannot see the Role of the user they are amending, so they only have the option to create an authenticated user or amend an existing user, they cannot amend the **role** for that user.

However, as administrator I am able to see the role option and set accordingly.

Can anyone advise how to allow this for my Publisher role?

# Answer
> 2 votes
A possible scenario to implement what you're looking for is like so:

* Use the Flag module to allow a Publisher (any other roles also?) to flag users to indicate that they "*want to amend the role for that user*" (say you label such flag as "*Amend User*").
* Then use the Rules module to react to (Rules Event) "A user gets flagged with the *Amend User* flag", combined with a Rules Action to "grant a role to the flagged user" (which could be multiple roles also if needed).
* If you need more granularity to be able to do so for multiple roles (like role A for user X, role B for user Y and role A and B for user Z), then just use multiple flags (1 for each role individually).

True, this would require 2 more modules, but pretty sure you'll find lots of other use-cases for these amazing modules (which should be part of pretty much every Drupal site).

---
Tags: users
---


# Question
Title: How can I remove a property from an entity in Drupal 7
I have a custom entity that was create a long time ago. Now we want to update the schema to remove a property (not a field) that was defined in the original schema.

I've reviewed the Drupal API for managing schema for custom entities and I don't see anything that allows me to remove the column during a hook\_update\_N function.

Am I missing something obvious here?

# Answer
You're looking for `db_drop_field()`. Although it's called a "field" here, it's essentially the remove-a-column-from-the-DB-table function.

Example from `filter_update_7005()`:

```
// Drop the roles field from the {filter_format} table.
db_drop_field('filter_format', 'roles');

```
> 4 votes

---
Tags: entities, database
---


# Question
Title: Unexpected class in ControllerResolver.php on line 151
I'm working with Drupal 8 for the first time, though fairly well experienced in 7.

I have a site working on a localhost environment just fine, and I am attempting to get it working on Go Daddy (I know they are not well regarded, but right now I need this to work.)

The entire code-tree on the localhost and server are identical. They both connect to the SAME mysql database, hosted on GoDaddy. The database is fine.

When I try to load the site from the GoDaddy host, I get the following error.

> Parse error: syntax error, unexpected 'class' (T\_CLASS), expecting identifier (T\_STRING) or variable (T\_VARIABLE) or '{' or '$' in /home/content/01/9224501/html/mysite/drupal8/core/lib/Drupal/Core/Controller/ControllerResolver.php on line 151

So far, from googling the error, it seems to result from a failed database connection. I'm not sure why the same code would connect to the same database just fine from one place and not from another.

The db connect code from settings.php is here:

```
$databases['default']['default'] = array (
  'database' => 'mydb',
  'username' => 'mydb',
  'password' => 'mydbpwd',
  'prefix' => '',
  'host' => 'mydb.db.9224501.hostedresource.com',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

For what it's worth, this is the code in core that generates the error.

```
protected function doGetArguments(Request $request, $controller, array $parameters) {
$attributes = $request->attributes->all();
$raw_parameters = $request->attributes->has('_raw_variables') ? $request->attributes->get('_raw_variables') : [];
$arguments = array();
foreach ($parameters as $param) {
  if (array_key_exists($param->name, $attributes)) {
    $arguments[] = $attributes[$param->name];
  }
  elseif (array_key_exists($param->name, $raw_parameters)) {
    $arguments[] = $attributes[$param->name];
  }
  elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
    $arguments[] = $request;
  }
  elseif ($param->getClass() && $param->getClass()->name === ServerRequestInterface::class) {
    $arguments[] = $this->httpMessageFactory->createRequest($request);
  }
  elseif ($param->getClass() && ($param->getClass()->name == RouteMatchInterface::class || is_subclass_of($param->getClass()->name, RouteMatchInterface::class))) {
    $arguments[] = RouteMatch::createFromRequest($request);
  }
  elseif ($param->isDefaultValueAvailable()) {
    $arguments[] = $param->getDefaultValue();
  }
  else {
    if (is_array($controller)) {
      $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
    }
    elseif (is_object($controller)) {
      $repr = get_class($controller);
    }
    else {
      $repr = $controller;
    }

    throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument (because there is no default value or because there is a non optional argument after this one).', $repr, $param->name));
  }
}
return $arguments;

```

}

Line 151 is the 3rd elseif statement.

A similar error that I already solved was a result of GoDaddy defaulting to PHP 5.3, which was not supported by Drupal 8. I upped it to 5.4.19, which is the only other option they offer.

My localhost is running PHP 5.5.9. I hope this is not the problem because there won't be anything I can do about it.

# Answer
> 3 votes
> My localhost is running PHP 5.5.9. I hope this is not the problem because there won't be anything I can do about it.

Well there *is* something you can do - change your hosting provider :)

The error is indeed caused by your version of PHP - it's too old. It doesn't understand the newer method of class name resolution, introduced in 5.5. A quick search through core reveals 350+ uses, and I think there is/was an issue around somewhere to convert any uses of static strings as class names to the new way, so it's not something you could realistically work around with patches.

The PHP requirements do list 5.5.9 as a minimum version (until Drupal 8.7.0), so trying to install on anything lower than that is doomed to failure unfortunately.

---
Tags: 8
---


# Question
Title: CCK field migration reproducibly results in server error on node display
I am trying to migrate my CCK types to Fields using CCK module in D7, using content\_migrate, following the documentation. After migrating all fields of a certain content types, I got a server reset when trying to view any node of this content type.

See also https://www.drupal.org/node/2665208

In Chrome the message is "No data received ERR\_EMPTY\_RESPONSE", Firefox says "Secure Connection Failed The connection to the server was reset while the page was loading". The server log is completely empty for loading this page, so I guess php dies pretty early.

I migrated all fields one by one and tracked it down to a text field that was using an **optionwidgets\_button** widget in D6.

Edit: We found a second broken field. This field does not cause a server reset but a 'The website encountered an unexpected error' from Drupal upon display of any node where this field is set. This field is of type user\_reference.

This is the output of from the migration process of the offending field:

* Changed field type: The 'field\_myfield' field uses a 'optionwidgets\_buttons' widget. The field type will be changed from 'text' to 'list\_text'.

Rolling back the field suppresses the error; re-migrating this field fully reproduces the error.

no pending dbupdates, Postgres 8.4, PHP 5.3

# Answer
We have now identified the source of the error. The content-migrate process seems to sometimes generate invalid display settings for fields. We have now seen this for two different fields. To identify the offending field, we did the following to debug:

* if possible, (you getting at least a drupal error) get a call stack, so that the offending field type and field name can be searched for (grep for 'field')
* to repair offending settings: go to `admin/structure/types/manage/<data type>/display`
* set each field `<hidden>` in the **Label** column (yes that is odd, but I guess this setting is enough to trigger generating fresh display settings)
* Save
* set each field back to original Label settings
* Save

If you want to find the culprit without stack trace, one could switch each field off, and reload the content.

I am not sure about the reason for why this works, but I suspect serialized data. Drupal uses a lot of serialized strings to store settings in the database, and the deserialization might not be robust against corrupted settings. I don't think this is really a bug in the migration code, but corrupted settings can occur at any time.

So I guess it might be a good idea to re-generate settings, in any case of a display error of custom content.
> 1 votes

---
Tags: 7, migrations, entities, debugging
---


title: Error when importing View

text:
# Question
Title: Error when importing View
I am trying to import View from one Drupal 7 Environment (from local to pantheon one) and got this error:

```
- Field handler views_entity_commerce_order.operations_dropbutton is not available
- Unable to import view.

```

Any ideas what is going on here ?

# Answer
> 0 votes
I was able to find a workaround by setting this option in View Import:

`Bypass view validation`

# Answer
> 1 votes
Create a field with machine name 'views\_entity\_commerce\_order' in the pantheon one and then import your view.

# Answer
> 0 votes
Arun has provided the correct answer above but may not be providing enough information for people who are new to Drupal, new comers simply may not know how to "create a machine field name" so hopefully this will help. The whole point of creating a View is to display some sort of list or collection of a given content type, this is usually a custom content type but it doesn't have to be. If you try to import the View before you have added all the fields to the content type you are creating the View for, you will get an error similar to the one Michal got. You should always create (or import) the View after you've finished creating your custom content type or finished modifying an existing one, and make absolutely sure you use the same field names you used in your development environment or the View Import will fail.

---
Tags: 7, views
---


# Question
Title: how do i add a login menu to superfish menu module?
I thought i would be able to add the default User Login menu to a Superfish block, but it doesn't appear in the drop down list to be able to select when configuring the Superfish block.

Can anyone advise how to create a login menu for superfish that disappears when users are logged in. I have my Main Menu in Superfish 1 block, and my User Menu (contains logout) in my Superfish 2 block (works perfectly as only appears when logged in), and wanted a Superfish 3 for User Login (to only appear when logged out).

Perhaps there is an easier way to do this, so open to suggestions?

# Answer
> 0 votes
I merely added an extra option to my main menu called 'Member Login' path user/login , then once you login this automatically disappears and I get my User Menu appear in my Superfish2 block with has my logout and other options that are only permitted by authenticated users. Thanks for advise on other menus.

# Answer
> 0 votes
Instead of using SuperFish, you should consider using:

### TB Mega Menu

> TB Mega Menu allows you to create a mega menu with an innovative back-end user interface and synchronized with Drupal core menu.
>
> * Synchronized with Drupal core menu, auto updated if there’s any change with - - - Drupal core menu
> * Bootstrap framework
> * Responsive ready
> * Multiple built-in styles designed with years of theming experience
> * Visual and friendly user interface - what you see is what you get
> * Custom style for each element of your mega menu, just input extra css class name
> * Multiple built-in CSS3 animated effects
> * Work independently with themes

Speaking from experience, I know you can add the login block to TB Mega Menu

Here is a Video Tutorial

---
Tags: routes, users, navigation
---


title: Getting a menu delivered via REST

text:
# Question
Title: Getting a menu delivered via REST
I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu\_name}.

I can successfully return this example json using this function when I hit the URL.

```
public function get(EntityInterface $entity) {
  $result = array();
  for ($i = 0; $i < 10; $i++) {
    $temp = array(
      'title' => 'Test ' . $i,
      'href' => '#/' . $i
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

```

I cannot figure out how to load the menu based on `$entity`. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?\_format=hal\_json) `$entity`'s value is `'main'` which is the machine name of the main menu.

I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.

How do I get menu item titles and paths based on the menu machine name?

**EDIT**

Ok, sort of figured it out.

```
public function get($entity) {
  $menu_name = $entity;
  $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
  $renderable = \Drupal::menuTree()->build($tree);
  $result = array();

  foreach (end($renderable) as $key => $val) {
    $temp = array(
      'menu_item' => $val,
      'route' => $key
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

```

Right now that will output:

```
[
  {
    "menu_item":{
      "is_expanded":false,
      "is_collapsed":false,
      "in_active_trail":false,
      "attributes":"",
      "title":"Home",
      "url":{

      },
      "below":[

      ],
      "original_link":{

      }
    },
    "route":"standard.front_page"
  },
  {
    "menu_item":{
      "is_expanded":false,
      "is_collapsed":false,
      "in_active_trail":false,
      "attributes":"",
      "title":"Communities",
      "url":{

      },
      "below":[

      ],
      "original_link":{

      }
    },
    "route":"menu_link_content:139d0413-dc50-4772-8200-bc6c92571fa7"
  }
]

```

any idea why `url` or `original_link` are empty?

# Answer
This was the correct answer:

```
public function get($entity) {
  $menu_name = $entity;
  $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
  $result = array();

  foreach ($tree as $element) {
    $link = $element->link;
    array_push($result, array(
        'title' => $link->getTitle(),
        'url' => $link->getUrlObject()->getInternalPath(),
        'weight' => $link->getWeight()
      )
    );
  }
  return new ResourceResponse(json_encode($result));
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: how do I make Drupal Zen sub theme mobile friendly?
I have changed over to using the Zen theme (instead of Omega) on my drupal site, I have a Superfish menu configured with default settings for SF Small Screen plugin to enable on browser width (screen width 768px which is default). It worked perfectly on Omega where i had exactly the same settings, but now with my Zen sub theme, the menu doesn't change to a mobile friendly version when i reduce the browser width on safari. I have my site installed on localhost and looking at view source it shows:

```
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width">

```

Yet using the same site with omega theme it shows:

```
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" >

```

Am i missing a setting on Zen to enable mobile responsive?

I have ticked all these settings on my zen sub theme:

Add HTML5 and responsive scripts and meta tags to every page. Add Respond.js JavaScript to add basic CSS3 media query support to IE 6-8. Add HTML5 shim JavaScript to add support to IE 6-8. Add meta tags to support responsive design on mobile devices.

Can anyone help?

# Answer
I have managed to resolve the problem now. I had upgraded the super fish module automtically via the Status screen, but not upgraded the Superfish library. Once I did that so they were both on the latest versions, and flushed cache it works again. I must have spent 2 or 3 hours googling to resolve this problem. I was thrown off course because I had switched themes from Omega to Zen which gave me a bit of a bum steer. School boy error really, must always check latest versions of module and any related library .
> 0 votes

# Answer
I have just checked the Superfish project status and there are bug reports that Superfish breaks with jQuery versions 1.9 and above. Check what version of jQuery is loading and check if there are any Javascript errors in your browser console.

If that is the problem, you may have to wait for the next version update, or roll back to jQuery 1.8 for the time being.

Superfish jQuery 1.9 Bug Report
> 0 votes

---
Tags: theming, navigation
---


# Question
Title: Views - Test if field is visible via PHP
I am developing a custom theme for a specific view. I need to iterate and render each row and field, How can i do that?

Some code:

```
foreach($view->rows as idx => $row)
{
    foreach($view->field as $name => $handler)
    {
        //I need to check if the field is hidden from
        //display here
        $view->render_field($name, idx);
    }
}

```

I am going through with the debugger and use `$handler` array options, but within that I could not find any field that is visible or not.

Can anybody help?

# Answer
Data that you are looking for is located at `$field->handler->options['exclude']`. But it is tricky to get to.

When you mark the field as excluded, its data becomes inaccessible at the field's level in your View's template.

`$row` object also does not have any indication that the field was excluded via Views UI. `$row` contains only the value data from each field. You can confirm that by doing dsm($row); in your View template file (if you have devel module installed).

If you are overriding you View's template on the `"Row style output"` level, than the only object you can use to reach `options['exclude']` from already excluded fields is `$views`.

You could do something like this at the top of your .tpl file:

```
foreach ($view->field as $view_field)
    {
        //check if field is excluded
         if ($view_field->options['exclude'] == 1) {
             // field is exluded - do something
             print $view_field->field.' is excluded from this view'; // print name of excluded field
             print $row->field_field_yourfieldname[0]['raw']['safe_value'];
        }
    }

```

so, if the field is excluded - it is going to be excluded in each row, according to that you can assign some markup or text to a variable and then print it anywhere down the template.
> 1 votes

# Answer
To iterate the each row and field, you have to override the view template. To override view template, go to the particular view.

On the right side, there is `Theme` field in the `Advance section`.

Click on the theme field, there is a various type of template to override. Click on the `Row style output`. A popup will open. Copy the entire code and place the code in `template` directory of your theme and give it a name as there are suggested and then save it.

Now you can do any kind of changes for this particular view.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Illegal choice error in views exposed filter select list
My question is related to Drupal 7 Views Exposed Filter - How to Select all Taxonomy terms Upon adding new terms? however I have a different problem. I want to filter a view by users of specific roles and for that i have added the user field in views filter and exposed it.

The problem is that if i check "select all" in "options" and leave "Limit list to selected items" unchecked, the select shows "--Any--" as default selection and also includes any users added later but throws "An illegal choice has been detected. Please contact the site administrator" and does not load any views.

On the other hand, if i check "Limit list to selected items" in options it shows no error but then it will only load the selected users in options and not any user added later. The field "check\_user" has a field collection relationship. How to solve this? Is this a bug or misconfiguration?

Using views 3.8 and Drupal 7.32

\[EDIT\]

I managed to remove the error by **deselecting** the "select all" option and checking all the users, this way the select list filter include the checked users in exposed filter and also any user added later. The select filter also provided "--Any--" option but when I first load the view, the first user in the list is automatically select instead of "--Any--". How to default the select filter to "--Any--"?

# Answer
> 4 votes
Don't choose `select all` option (it is a simple javascript effect to choose the values) or don't select any user from list. If you just choose expose the filter option it will display all the users list automatically.

# Answer
> 2 votes
That error is documented in the following thread https://www.drupal.org/node/1177882#comment-8891105. This solution worked for me:

```
$form['your-views-exposed-filter-field-name-here']['#validated'] = true;

```

---
Tags: 7, views
---


# Question
Title: Exposed filters with dropdown selections
I have a project where I've created a View with some basic information, showing for example Year, Manufacturer, Product Type. They are all custom text fields. I can expose a filter on them which lets me manually enter in a search, for example, 2008 for year and it correctly shows me all the entries for 2008.

Is there any way to have these fields available as a dropdown selection based on the content saved within each node, eg so that the Year field shows 2001, 2002, 2003 ..... 2012 etc, or Product Type shows "Table, Chair, Lamp etc" that the user can choose from? I'm fairly new to using Views and struggling to find an answer.

I'm using Drupal 7 and Views 3.3.

# Answer
> 4 votes
The problem here is that the fields are custom text fields. If the "product type" field was of the type "List (text)" instead it would be a drop down in Views when exposed.

Maybe the product type would be good to have as taxonomy terms instead? Then product types could easy be added to the vocabulary as the site grows. The field in your content type would then be a "Term reference" to the Taxonomy vocabulary product type. If the product types rarely or never change you could stick with "List (text)"

I would probably make the field year into a date field or taxomomy, or list (integer).

I hope you see where I am trying to go here, the fields needs to be of the correct type for Views to be able to interpret the fields correctly and "automatically" give you dropdowns when the filters are exposed etc.

# Answer
> 2 votes
If you would like to write a module for this task, you could solve the problem as follows. I adapted this code from here.

Create a module directory in `sites/all/themes/modules` and name it `custom_exposed_year_filter`.

Create a file `custom_exposed_year_filter.info` containing the following:

```
; custom_exposed_year_filter.info
name = Custom Exposed Year Filter
description = Sorts exposed years filter into a dropdown instead of a textfield
core = 7.x
files[] = custom_exposed_year_filter.module

```

Then, create a file named `custom_exposed_year_filter.module` and insert this code:

```
<?php
// custom_exposed_year_filter.module

function custom_exposed_year_filter_form_views_exposed_form_alter(&$form, &$form_state) {
    $field_id = 'field_reference_year_start';

    // Only alter forms with the necessary field
    if (isset($form[$field_id . '_value'])) {
        // Build a query to get all node ids having the specified field
        $query = new EntityFieldQuery();
        $results = $query->entityCondition('entity_type', 'node')
                ->fieldCondition($field_id, 'value', 'NULL', '!=')
                ->fieldOrderBy($field_id, 'value', 'ASC')
                ->execute();

        // Attach the field values to the nodes
        $nodes = $results['node'];
        field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

        // Add a default so the filter is optional
        $options = array('' => '<select>');

        // Buld the options array based on the query results, overwriting duplicate entries
        foreach ($nodes as $node) {
            $value = $node->{"$field_id"}['und'][0]['value'];
            $options[$value] = $value;
        }

        // Alter the field
        $form[$field_id . '_value']['#type'] = 'select';
        $form[$field_id . '_value']['#options'] = $options;
        $form[$field_id . '_value']['#size'] = 1;
    }
}

```

Lastly, adjust the following line so it matches the name of the field that you would like to filter for:

```
$field_id = 'field_your_field_name';

```

Then, clear the cache, enable your new module in Drupal, create a filter for your field, and check the 'exposed' box to make the filter available to visitors.

Should you need to turn multiple filters into dropdowns, you might adapt the code above or just create multiple modules for each field.

You might run into performance problems if you have a very large number of items in your view. It works like a charm for me, though.

# Answer
> 2 votes
I had a list of manufacturers from several countries and I wanted to add an exposed filter with all countries found in that manufacturers list. I followed a similar approach in anthonygore's solution above (thanks mate!) but with a `hook_views_exposed_form_alter` in `template.php`:

```
function your-theme_form_views_exposed_form_alter(&$form, &$form_state){

if ($form['#id'] == 'your-form-id') {

// query distinct field values for all nodes in content type

$query = db_select("field_data_your-exposed-views-filter-field}", 'f');
$options = $query
  ->fields('f', array('your-exposed-views-filter-field_value'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'fornecedor')
  ->orderBy('your-exposed-views-filter-field_value', $direction = 'ASC')
  ->distinct()
  ->execute()->fetchCol();
  }

// Create an assoc array with equal keys and values from the query array

$result = array_combine($options, $options);

// Add the option "All" to the array

$result = array_merge(array('All' => '- Any -'), $result);

// Convert the textfield exposed filter to a select list

$form['your-exposed-views-filter-field']['#type'] = 'select';
$form['your-exposed-views-filter-field']['#size'] = 'null';

// Update the form options with the query array

$form['your-exposed-views-filter-field']['#options'] = $result;

// Important! Remove "An illegal choice has been detected. Please contact the site administrator." error. More info at https://www.drupal.org/node/1177882#comment-8891105
$form['your-exposed-views-filter-field']['#validated'] = true;

}

```

# Answer
> 0 votes
I had a problem where I need to filter blog posts by created date, but the date field in Views would only show a range e.g. -10 years to 0 years.

The problem with this is that would show years where their were no blog posts e.g. lets say there were no posts in 2007, you'd still have it as an option.

The solution to filter out unneeded years is as follows:

1. In the exposed filter form there will be a field for date e.g. `$form['date_value']`. It should have a processing callback, in my case it was `$form['date_value']['value']['#process'][0] = 'date_select_element_process'`.
2. Make an alter hook on the callback e.g. `mymodule_date_select_process_alter(&$element, $form_state, $context)`
3. Query your nodes with `EntityFieldQuery()` to figure out which years are in use by your existing nodes
4. Filter your list of dates accordingly e.g. `unset($element['year']['options'][2007]);`

Here's an example implementation

```
/**
 * Implements hook_date_select_process_alter().
 */
function mymodule_date_select_process_alter(&$element, $form_state, $context) {

  if (!empty($context['form']['#id'])) {

    // Check to ensure we're modifying the correct exposed form
    if ($context['form']['#id'] == "views-exposed-form-blog-page-1") {

      // Query the blog nodes to see which dates we have
      $field_id = 'field_date';
      $query = new EntityFieldQuery();
      $results = $query
        ->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'blog')
        ->fieldCondition($field_id, 'value', 'NULL', '!=')
        ->fieldOrderBy($field_id, 'value', 'ASC')
        ->execute();

      // Attach the field values to the nodes
      $nodes = $results['node'];
      field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

      // Build the options array based on the query results
      $options = array('' => "-Year");

      foreach ($nodes as $node) {
        $value = $node->{"$field_id"}['und'][0]['value'];
        $date = DateTime::createFromFormat("Y-m-d H:i:s", $value);
        $year = $date->format("Y");
        $options[$year] = $year;
      }

      // Add the filtered options back to the element
      $element['year']['#options'] = $options;
    }
  }
}

```

# Answer
> -1 votes
Found a solution. Worked for me.Check it here. http://bryanbraun.com/2013/08/06/drupal-tutorials-exposed-filters-with-views

---
Tags: 7, views
---


# Question
Title: How to send an eMail notification when a specific field of a node or user has been changed?
When a node (or user profile) is modified, is it possible to send an email notification only when a specified field is modified?

With the node I have no problem, but I cannot get it to work for a specific field.

# Answer
You can use the Rules module for this. Here are some details about how to do so:

* **Rules Event**: Before saving content.
* **Rules Condition**: Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.
* **Rules Condition**: Send an eMail (which is typically implemented as a separate "Rules Component" (that is invoked as the Rules Action), whereas you pass the values like node id, current user, maybe author, etc. Within the Rules Component, you then compose the actual eMail (template) that you want to be eMailed. For an example of such a Rules component, have a look at my answer to "How can I set a reminder for a specific user to be triggered on a specific date?" (which includes such component in Rules export format also).

Should be straight forward to "develop" such rule, no (PHP) coding at all involved (only site building using admin UI).
> 3 votes

# Answer
Have a look at hook\_user\_update. This hook is called when a user account (user profile?) is updated.

You might also want to look at hook\_node\_update. You will not be able to use the `hook_node_update` to be notified when your user accounts are updated, but on this page there is a comment about `$node->original` having the values of the `$node` before the update.

I have not tested this myself (should be a trivial excursive), but you may be lucky and find $account-\>original (or something similar) stores the original values of the user account.

It is then a simple matter of testing the old field value against the new one to see if a change occurred, and you can take appropriate action - like sending a mail.
> 0 votes

---
Tags: nodes, entities, rules, emails
---


# Question
Title: How to create a view of nodes of which a user is a member?
How do I create a view of Nodes that a logged in user is a member of? Is this enforced in Relationships or Contextual Filters? That is, can you explain *how* group membership is enforced via relationships and contextual filters?

# Answer
Organic Groups are providing a set a views already configured and ready to use. What you are looking for is one of these views, specifically this view: `OG User groups` of `Type: OG membership`.

You may create a clone of this view (is a good practice to keep the original view intact, mainly for reference) under `admin/structure/views` and set it (fields, filters etc) according to your needs. You may also explore the `relationships` and `contextual filters` and see how are set. Note that the type is OG membership. A handy thing to add to your view is the `(un) subscribe link` from/to group. This is found in fields as:`Content: Group` with formatter '`OG subscribe link`' .

Lastly, keep in mind that the OG's: `OG User groups` view is a `content pane` , not a `page`. This means that if you want to place your group's `page` under a menu you'll have to create a `view page` with a path.

Organic Groups module also provides an API and set of functions. The documentation page page also constitutes a great reference.

Hope that helps!
> 2 votes

# Answer
Organic Groups provises a default view for this called "OG User Groups". You can use that as a base and adapt it accordingly.
> 3 votes

---
Tags: views, organic-groups
---


# Question
Title: How to change the way a Content Type is displayed depending on user?
I'm currently trying to create a Massively Multi Onlineplayergame (see tribalwars.net) in Drupal while learning it. To do this I want to be able to change the way a content type is displayed depending on what user is looking at it.

Say for example, if it's the current owner of the "town" I want the user to be able to edit it. While if it's not the owner I want the user to be able to send troops there.

I've been looking at events but there doesn't seem to be any event that allows me to do that sort of thing. Will I have to define a content type programmatically or is there any other way to do it?

# Answer
Have a look at Display Modes, View Modes, and Form Modes, especially what is written about ***View modes*** within "View modes and view displays", which is like so:

> View modes as a concept predate Drupal 8. They were present in Drupal 7. Drupal 6 had the concept of “build modes.” View modes exist to allow Drupal site building tools like Entity Reference fields to request a given entity be rendered in a certain way. For instance, if ‘song’ and ‘artist’ are each node types and song contains a reference field to artist. The full display of the song may need to render the ‘teaser’ for the artist. In this example ‘teaser’ is a view mode used by the artist node and ‘full’ is the view mode used by the song.

Then continue towards that present in Drupal 7 link, which further explains **View modes**, and includes this:

> Contributed modules can be leveraged to add View modes to entities via the UI without writing code.
>
> The Display Suite module makes it possible to add more view modes to your entities.
>
> The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities.

Then head over to the Entity View Modes project page ... Guess what: that module is now included in D8 core ...
> 3 votes

---
Tags: views, nodes, 8, users
---


# Question
Title: Changing Commerce Credit Card option to read something else
I have two radio options in my form for payment: the first says 'credit card' and the second says 'cheque' (I'm using the PayPal wpp and Cheque modules). The Cheque option is easy enough to change to say something else ('send me an invoice') and I changed that in the store \> config \> cheque settings.

But, does anyone know how or where to change the text for the 'Credit Card' option. I want to add more information about how we process it to the label itself.

# Answer
> 3 votes
Alter the form that has the `form_id` of `commerce_checkout_form_review`:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
 $form['commerce_payment']['payment_method']['#options']['commerce_payment_example|commerce_payment_commerce_payment_example'] = t('AWESOME PAYMENT');
}

```

The `#options` array will hold a list of payment methods that are keyed by the `payment_method` followed by a pipe (`|`) and then an `instance_id`. Just update the title accordingly.

---
Tags: commerce
---


# Question
Title: How to add a variable to a twig field template?
On a node page I would like to add the node title to the output alongside another another field (the example field).

I have created a new `field--field-example.html.twig` but am unable to access the node title variable as it is not available in the field template.

I need to add the variables into the theme preprocess: `themename.theme`.

How do I add the variable in `themename.theme` and what would be the corresponding entry in the `field--field-example.html.twig` ?

# Answer
Since you asked about passing the node title as a variable via the .theme file, you could use template\_preprocess\_field to do something like this:

```
  function themename_preprocess_field(&$variables, $hook) {
    if ($variables['element']['#field_name'] == 'field_example') {
      $variables['node_title'] = $variables['element']['#object']->getTitle();
    }
  }

```

then in your `field--field-example.html.twig` you could simply just use `{{node_title}}` to render the node title.

Also see 4k4's answer below.
> 15 votes

# Answer
There is a node object available in the variables of the field template, so you don't need a preprocess function.

To get the title from the node in a field template:

```
{{ element['#object'].label }}

```
> 11 votes

---
Tags: theming, 8
---


title: Custom version of DateFormatter service

text:
# Question
Title: Custom version of DateFormatter service
I want to create a slightly different version of the `formatInterval` function. Normally I do this:

```
echo \Drupal::service('date.formatter')->formatInterval($seconds);

```

I want the final string to say not "1 hour 40 minutes", but "1h 40m" instead, so I was thinking about making a subclass of the core's `DateFormatter` class, and just change the protected `$units` property to define what I want.

How do I do this elegantly in a custom module, "the Drupal way"?

# Answer
> 3 votes
The full story can be found at Altering existing services, providing dynamic services, but essentially you need to add a service provider to your module, e.g. (mostly copied from the d.o page above):

```
namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the date formatter service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides date.formatter class for custom interval formatting.
    $definition = $container->getDefinition('date.formatter');
    $definition->setClass(DateFormatter::class);
  }
}

```

(assuming your replacement class is `\Drupal\my_module\DateFormatter`)

---
Tags: 8, symfony-services
---


# Question
Title: Access submitted form data in custom callback before hook_mail_alter()
I wan't to alter contact form recipient according to what user chose in one of the dropdown fields of my Contact form.

I implemented `hook_form_FORM_ID_alter()` in order to add custom submit callback like this

```
 $form['actions']['submit']['#submit'][] = 'my_custom_callback';

```

to get submitted data.

I thought I could use `State API` in `my_custom_callback()` to store received data temporally and use it's value in `hook_mail_alter()` but it looks like `hook_mail_alter()` is called before my custom callback.

This is what the order of callbacks looks like:

1. Default Submit callback of Contact form;
2. `hook_mail_alter()`;
3. `my_custom_callback`.

I wander if there is any way to change this order to this:

1. `my_custom_callback`;
2. Default Submit callback of Contact form;
3. `hook_mail_alter()`.

# Answer
Why do you need a submit callback at all? The built contact message is available in hook\_mail\_alter(), you can just access the submitted data there?

This is from a custom project where we did something similar:

```
/**
 * Implements hook_mail_alter().
 */
function yourmodule_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_message->bundle() != 'feedback') {
      return;
    }

    $recipient_address = $contact_message->get('yourfield')->value;
    if (\Drupal::service('email.validator')->isValid($recipient_address)) {
      $message['to'] = $recipient_address;
    }
  }
}

```
> 1 votes

# Answer
I would store the relevant values for sending the mail in a temporary table when my\_custom\_callback is executed, and then process the data in this table using a cron job or batch job. Batch would probably be better - gives you the tools to lock records, etc. You could run the batch using a cron job :)
> 0 votes

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


title: Drupal 8 One-off Custom Page for Theme

text:
# Question
Title: Drupal 8 One-off Custom Page for Theme
I'd like to create a one-off custom page which will contain several text fields.

The layout for the page will be custom, placing the text fields in various locations next to design elements, diagrams and maps. I'd like the site editors to be able to update the text fields/labels, including language versions.

I'm generally familiar with the render API, page and node templates, and I do know that I could create a dedicated content type (node, content entity) with all the fields required and then a page template (Drupal 8 custom page template) to render the node (and its language versions).

Just wondering if it makes sense to create a complete content type for what will effectively be a one-off (albeit important) node/page.

Thoughts? Suggestions?

# Answer
> 1 votes
You might want to have a look at the Paragraphs project. It basically allows you to create different building blocks (Image with text, Diagram with description, ...) and then you can piece them together in the edit form pretty easily.

Check out the demo module that's part of the project for a quick start. You'll still have to actually implement the design for each building block but once you have that, you can easily change how you've combined them and move parts around, add new ones.. create multiple pages that each uses those building blocks differently.

---
Tags: 8
---


title: Webform description allowing HTML

text:
# Question
Title: Webform description allowing HTML
I'd like to allow HTML in my webform field descriptions. I don't need an editor of some sorts; just the basics like and tags and stuff. How can I edit my webform to allow these tags in the description field?

# Answer
It looks like the module Webform HTML Textarea might do what you're wanting. It allows you to use the site's input methods (Filtered text, plain text, etc.). So you could make a limited one for your users with only the options you need (bold, italic, underline, etc.).
> 0 votes

---
Tags: entities, webforms
---


# Question
Title: Commerce - Discount on three or more products in order
I am moving my site from Ubercart to Commerce and would like to replicate a discount that I have set up in Ubercart. I have an Ubercart coupon that automatically adjusts the price for a product if there are three or more applicable products in the order. I have spent all day looking at Commerce Coupons and Commerce Discounts but have not found a way to do this yet Is this possible?

# Answer
> 4 votes
You may want to look at these modules that provide some extra conditions:

# Answer
> 0 votes
If anyone is looking to do this I achieved it using Commerce Discount Product Category and Commerce Rules Extra. I set up a product category and tagged the products I wanted to include in the discount. Created a discount for that product category and then edited the rule to in include Total quantity of selected product comparison

---
Tags: 7, commerce
---


# Question
Title: Importing large amount of data slow process with cron and queue
I am currently importing large amount of data into Drupal and I am using the hook\_cron with the queue API and so far everything is working. Data is been imported as nodes and the relationship between them is created and the views are displaying the data properly.

The problem I am having is how long it is the process taking to do the import of the data. I tried using the "Ultimate Cron" to see if a parallel processing of the cron job will speed things up, but I had no luck.

I have my queue full of pending data to be process and I can think of a way to speed it up. I read about creating multiple queues, but I haven't try that.

The server is a pretty decent server and the server load is less than 2% all the time, swap is empty and I am only using 800MB of 16 GB of RAM.

# Answer
> 1 votes
I think it will be good to use multiple queues and separate php non blocking (shell\_exec) process to read each queue, the idea is to call a php script to run in background which will pick a queue data and create nodes or whatever.

---
Tags: 7, database, importing-exporting
---


title: Feeds Import Alter for Multiple Fields

text:
# Question
Title: Feeds Import Alter for Multiple Fields
I am trying to setup a Feed Import from CSV. There is an images field in the content type which can have unlimited values. These images are in a folder and named in the following format:

```
[identifier_from_csv]_01_large.jpg
[identifier_from_csv]_02_large.jpg
[identifier_from_csv]_03_large.jpg

```

Each project has a variable number of images. I would like to be able to read from the file system and import as many images it has located there. I've tried to research into this and from what I can see the Feeds Tamper module I would still have to know how many images there are and have them all listed in a field.

How can I setup an import that would automatically read in as many images as there are located in the file import directory? I'm assuming there is a hook I could use and loop through there checking the file system, I'm not sure where/how to implement that.

# Answer
> 0 votes
I ended up solving this myself. My main question I guess was really about a feeds tamper plugin that can insert multiple values. Turns out it's pretty easy, just return an array and I think set the 'multi' value on the plugin. I ended up copying the "explode" plugin and modifying it for my needs. Here is the result. It's got some hardcoded values which I'm sure could be coded into the form settings. I kept it simple for my purposes.

```
$plugin = array(
    'form' => 'my_feeds_tamper_image_import_form',
    'callback' => 'my_feeds_tamper_image_import_callback',
    'validate' => 'my_feeds_tamper_image_import_validate',
    'name' => 'My Image Import',
    'multi' => 'direct',
    'category' => 'List',
);

function my_feeds_tamper_image_import_form($importer, $element_key, $settings) {
    $form = array();
    return $form;
}

function my_feeds_tamper_image_import_validate(&$settings) {

}

function my_feeds_tamper_image_import_callback($result, $item_key, $element_key, &$field, $settings, $source) {
    $out = array();
    $index = 1;
    $fileExists = true;

    do {
        $filename = "public://import/" . $field . "_" . str_pad($index, 2, "0", STR_PAD_LEFT) . "_lg.jpg";

        if( file_exists($filename) ) {
            $out[] = $filename;
            $index++;
        }
        else {
            $fileExists = false;
        }

    } while($fileExists);

    $field = $out;
}

```

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


title: How do I translate a view page title?

text:
# Question
Title: How do I translate a view page title?
Is there a way to translate a view page title in Drupal 8? How can I achieve it, if it is possible?

# Answer
Install the Multilingual modules in admin/modules

Go to admin/config/regional/language and add the new language

Go to edit your View and click in Translate

Then click in edit

And go to edit the title
> 33 votes

---
Tags: views, 8, i18n-l10n
---


# Question
Title: How to programmatically assign user roles
I am assigning a role to user by this code:

```
$user = user_load($user->uid);
$role = user_role_load_by_name("10-dis");
$user->roles = $user->roles + array($role->rid => $role->name);
user_save($user);

```

I need to replace this role with a new role, means I need to change user role according to some condition. How can I programmatically reassign user role?

# Answer
Drupal core `user.module` provides a simple function to add/remove roles to/from a user. See `user_multiple_role_edit()`.

```
$uid = 12345; // The user ID of the account you want to change.
$role_id = 4; // The numeric role ID you want to add.
$role_id_rm = 3; // The numeric role ID you want to remove.

user_multiple_role_edit(array($uid), 'add_role', $role_id);
user_multiple_role_edit(array($uid), 'remove_role', $role_id_rm);

```
> 13 votes

# Answer
To remove a role from a user you can use this function:

```
/**
 * Remove a role from a user.
 *
 * @param $user
 *   User object or user ID.
 * @param $role_name
 *   String value of role to be removed.
 */
function custom_remove_role_from_user($user, $role_name) {

  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }

  // Only remove the role if the user already has it.
  $key = array_search($role_name, $user->roles);
  if ($key == TRUE) {

    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {

      // Make a copy of the roles array, without the deleted one.
      $new_roles = array();

      foreach($user->roles as $id => $name) {
        if ($id != $rid) {
          $new_roles[$id] = $name;
        }
      }

      user_save($user, array('roles' => $new_roles));
    }
  }
}

```

To add a role to a user you can use this function:

```
/**
 * Add a role to a user.
 *
 * @param $user
 *   User object or user ID.
 * @param $role_name
 *   String value of role to be added.
 *
 * @see http_://drupal.org/node/28379#comment-4277052
 * @see http_://api.drupal.org/api/drupal/modules--user--user.module/function/user_save
 */
function custom_add_role_to_user($user, $role_name) {

  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }

  // If the user doesn't already have the role, add the role to that user.
  $key = array_search($role_name, $user->roles);
  if ($key == FALSE) {

    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {

      $new_role[$rid] = $role_name;
      $all_roles = $user->roles + $new_role; // Add new role to existing roles.
      user_save($user, array('roles' => $all_roles));
    }
  }
}

```

**Reference**: Programmatically adding and removing roles to users in Drupal
> 3 votes

# Answer
Take the following helper function provided with the necessary arguments to replace a user's role:

```
/**
 * Helper function to replace a user's role.
 *
 * @param int $role_to_replace
 * @param int $role_to_replace_by
 * @param int $uid
 *
 * @throws \Exception
 */
function replace_role($role_to_replace, $role_to_replace_by, $uid) {

  $role_to_replace = (int) $role_to_replace;
  $role_to_replace_by = (int) $role_to_replace_by;
  $uid = (int) $uid;

  // Load user by user ID.
  $user = user_load($uid);

  if (array_key_exists($role_to_replace, $user->roles)) {

    // Remove old role.
    unset($user->roles[$role_to_replace]);

    // Load new role by role ID.
    $role = user_role_load($role_to_replace_by);

    // Add new role.
    $user->roles = $user->roles + [$role->rid => $role->name];

    // Save.
    user_save($user);
  }
}

```

The function call will look like:

```
replace_role(7, 11, 4024);

```

So above example will replace role with role ID 7 to role with role ID 11 for user with user ID 4024.
> 2 votes

---
Tags: 7, users
---


# Question
Title: How to deploy a module locally for testing?
I'm currently developing my first custom module for Drupal 7 and am having a hard time finding documentation about the available local deployment strategies.

I have a custom module project, consisting of my modules sources, a gulp file and some other things of less interest (README, .editorconfig, ...). When I make a change on my source code, my gulp builder automatically deploy the changes to my local Drupal installation (the document root), in the folder where my custom module is installed.

Now, I would like to test my changes, and that's where I'm stuck: changes that are part of the install hooks of the module (adding fields, custom nodes, and so on) don't appear on the website. I have to disable my module, uninstall it, resinstall it and enable it to see those changes. This is a very long and painful process.

Even using drush commands to achieve this, the disable, uninstall, install and enable process is very long, meaning I'm losing a lot of time waiting for Drupal to manage my module, even for the tiniest source code change.

And of course, in any case, I have to recreate every content I had previsouly created to test my module.

Is there a strategy to allow near-realtime deploy and testing when developing a custom module ? How are you guys dealing with this ? Is there at least a drush command to replay the install hooks of my module ?

Thanks by advance.

# Answer
> 1 votes
I do not think there will be a way to reduce time of reverting the database changes. However you can get a shortcut command to re-install a module.

Checkout answer by @MPD Quick Uninstall/Reinstall of a Custom Module, so you will need devel module to bind all those commands in one, also devel is good for development purpose.

# Answer
> 1 votes
In many cases you can develop and test your code outside the install/uninstall hooks, and when you know it's working you simply add it to the hooks and run it once or twice.

You can also use Backup & Migrate and do a quick db restore.

---
Tags: drush, deployment
---


# Question
Title: Allowing Automatic Logins from a Range of IP Addresses
I'd like to implement the following functionality in my site:

Give an entire organization access to our Drupal 7 site from a specific range of IP addresses.

The way it would hopefully work is this: users in the organization, from any of the computers in their organization (in the ip range) would be able to go to our site and be automatically logged in.

Other users with individual accounts in our system should not be restricted from logging into our site.

Anyone know how to accomplish this?

# Answer
### IP Login

> This module allows users to login automatically via their IP (v4) address ranges or wildcards instead of having to enter a username and password - plus many other features.
> 3 votes

---
Tags: users
---


title: How to debug a server reset or WSOD?

text:
# Question
Title: How to debug a server reset or WSOD?
We have recently observed that we can put Drupal in an inconsistent state where it responds with a server reset or WSOD, where no data is sent. This by simply having some faulty configuration (See CCK field migration reproducibly results in server error )

We have started to doubt the robustness of the our Drupal instance (and even Drupal in general if it is so easy to push off the tracks), so we want to look into this event further and understand exactly why, because in any case even a cryptic error message would be preferred over just dying.

How to debug such a situation, properly? There is no output whatsoever, neither in the logs nor to the browser. We have enabled the devel module debug outptu an krumo output, but it dies before this. We have also tried to catch sql queries using pg\_top, nothing.

What do?

# Answer
> 1 votes
To debug more on WSOD, you can always go to Server (Apache2/httpd) error logs or if accessible Recent logs Messages (Admin =\> Reports =\> Recent Log Messages) in Drupal.

You can find more details about WSOD and debugging it on below link: Blank pages or "white screen of death" (WSOD)

Hope this helps.

---
Tags: debugging, wsod
---


# Question
Title: CSRF validation failed issue on custom services!
I have created a custom services API to save order records in database. I have checked on POSTMAN and it is working fine. But when i request from apps it gives me "CSRF validation failed" issue.

Am i missing something?

# Answer
> 5 votes
In the POSTMAN you must be sending X-CSRF-Token with the API call, while you might be missing the same while doing API call from APP. X-CSRF-Token is required when you have session authentication enabled, for a quick test disable session authentication from your service configuration page at drupal admin end and then try doing the API call.

However the proper fix would be to have another API in place which gives you X-CSRF-Token and then do your API call along with X-CSRF-Token.

# Answer
> 7 votes
You can check workflow steps

**First** Time for login

* POST /services/session/token to retrieve CSRF Token POST
* myendpoint/system/connect with X-CSRF-Token header IF not Logged In
* Try Log in /myendpoint/user/login Log in Success and keep
* session\_name=sessionid in Cookie Varible

**Future Launches**

* POST /services/session/token to retrieve CSRF Token
* POST myendpoint/system/connect with X-CSRF-Token header along with previousely saved session\_name=sessionid as Cookie Header

Don't request for new CSRF token use the returned one for previous request. You will find it in a key named token in the result returned. Just request a new csrfCSRF token for the first time only.

Here is an example of a user profile request:

```
{
  "method": "POST",
  "url": "http://HOSTNAME/SERVICE_PATH/user/profile",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive",
    "X-CSRF-Token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
    "Cookie": "SESSb4d5ba755bb4eb727d982993490e6681=waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I"
  }
}

```

---
Tags: 7, services
---


# Question
Title: How do I display images from a field in a View as grid?
I have a view that displays images from an image field of a specific node and I want to display those images in a grid but Views groups them together so the whole node is put into the grid cell instead of each image separately.

How can I make such View?

# Answer
> 3 votes
You can edit image field in view and uncheck "**Display all values in the same row**" checkbox under "**MULTIPLE FIELD SETTINGS**" fieldset. This will tell view to render each image in node as single row. See screenshot below for field settings:

---
Tags: views, 8
---


# Question
Title: add billing information in Drupal Commerce Programatically
I am developing api access point for drupal commerce, from that access point user can upload his/her billing information during checkout process. Here is my code, but it can not add user full name in billing information. Any suggestion is greatly appreciated.

Thanks

```
  function commerce_services_bill_ship_create($data, $flatten_fields) {
    $status; $message;
    $orderId; $uid;

    $orderId =$data["orderId"];
    $uid = $data["uid"];
    $fullname = $data['fullname'];

    $order = commerce_cart_order_load($uid);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper->commerce_customer_billing->commerce_customer_address->name_line = $fullname;
    $order_wrapper->commerce_customer_billing->commerce_customer_address->thoroughfare = "No.1, ABC street";

    $order_wrapper->commerce_customer_billing->commerce_customer_address->locality = "New York";
     try{
        // Save the order.
        commerce_order_save ($order);
        $status = 1;
        $message = "order update successfully.";
    }catch(Exception $ex){
        $status = 0;
        $message = "order can't update successfully.";
    }
    $reply= (array('status' => $status,'message' => $message));

    return $reply;
 }

```

# Answer
To add billing information in checkout process first we have to create a profile object and assign it to the order. This code works for me

For adding new profile for billing information

```
function commerce_services_bill_ship_create($data, $flatten_fields) {
$status; $message;
$orderId; $uid;

$orderId =$data["orderId"];
$fullname = $data['fullname'];
$city = $data["city"];
$address = $data["address"];

//load order that you want to add billing information
$order = commerce_cart_order_load($uid);

// We'll assume that the current user will be the customer of our order
global $user;

$profile = commerce_customer_profile_new('billing', $user->uid);
$profile->commerce_customer_address = array(LANGUAGE_NONE => array(0 => addressfield_default_values()));

//for updating existing profile, uncomment the line below and comment commerce_customer_profile_new()
//$profile = commerce_customer_profile_load($profile_id); //

//add fullname
$profile -> commerce_customer_address['und'][0]['name_line'] = $fullname;

//add address
$profile->commerce_customer_address['und'][0]['thoroughfare'] = $address;

//add city
$profile->commerce_customer_address['und'][0]['locality'] = $city;

// You sould pass the entire $profile object as parameter.
commerce_customer_profile_save($profile);

//assign profile_id to the order
$order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'] = $profile->profile_id;

try{
    // Now you can save the order.
    commerce_order_save($order);
    $status = 1;
    $message = "order update successfully.";
}catch(Exception $ex){
    $status = 0;
    $message = "order can't update successfully.";
}

$reply= (array('status' => $status,'message' => $message));

return $reply;
}

```

Reference site - Programatically Create Order with Customer Profile , Creating Customer Profiles Programmatically
> 1 votes

# Answer
You are saving the order, which would have the state that it held before you made it into a wrapper. You need to save the `$order_wrapper`:

```
$order_wrapper->save();

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How to reset/save $_SESSION variables in forms for each user?
I need to add captcha to *user login* form after 3 failed logins.

To do so I built the following module, and used `$_SESSION['failed_login']` to keep track of the number of the failed logins.

This module works well, but when I close the browser and test a failed login again, the number that is stored via `watchdog` will not reset again from `1`, it continues increasingly.

```
<?php

function failed_login_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['#validate'][] = 'failed_login_myloginhandler';
    }
}

function failed_login_myloginhandler(&$form, &$form_state) {
    global $user;
    if (!$user->uid) {
        if(!$_SESSION['failed_login'])
            $_SESSION['failed_login'] = 0;
        $_SESSION['failed_login']++;
        watchdog("error", $_SESSION['failed_login']);
    }
}

```

What is the problem? Why it is not reset from `1` again? How can I have this temporary variable for each user who is trying to login?

# Answer
By default Drupal's sessions are kept for about 23 days. You can modify this in settings.php. Look for gc\_maxlifetime and cookie\_lifetime to reduce it to 0 so sessions are destroyed when the browser is closed.

This will effect logged in users too so when they close the browser they will also be logged out.

On a side note if you were unaware drupal already have flood control and will block IPs for multiple failed login attempts
> 3 votes

---
Tags: 7, forms, users, sessions
---


# Question
Title: How to get the field and value of a content type in drupal 8?
I wanted to create a module that fetch the entire data from my custom content type to generate a json file. So I used the function

`$values = \Drupal\Core\Entity\ContentEntityBase::get('field_name');`

to read the field and its values of a content type. Any way to dynamically fetch all the fields and its values. Any solution? Thanks in advance..:D

# Answer
You can get all the field definitions for a content type using getFieldDefinitions from the Entity Field Manager service. The definitions are indexed by field name, so you can iterate on the keys of the returned array for any of the nodes in your site.

An example would be the following:

```
<?php
  // Get the definitions
  $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'my_custom_content');

  // Load a node for which you want to get the field values
  $my_node = \Drupal\node\Entity\Node::load($my_nid);

  // Iterate through the definitions
  foreach (array_keys($definitions) as $field_name) {
    // Get the values for your node
    // Use getValue() if you want to get an array instead of text.
    $values[$field_name] = $my_node->get($field_name)->value;
  }

```
> 6 votes

---
Tags: nodes, 8, users
---


# Question
Title: How to get a conditional dependency to work?
I have 2 fields in my content type 'test':

1. 'Photos Gallery' -field type is image
2. 'Enable' checkbox to Enable gallery (field type boolean)

**Required output**: When 'Enable'-field is checked, the node should not allow us to save with empty photos in the 'Photos Gallery' field and we should be able to save if 'Enable' is unchecked.

I tried the **Conditional Fields module** and given condition like 'Gallery Photos is required when Enable is checked.', where 'Gallery photos' is dependent and 'Enable' is dependee field.

**Current output**: In the node edit page , when 'Enable' is checked, asterisk (\*) can be seen near 'Gallery Photos' , but without adding photos if i save, it is allowing me to save, without any error.

What additional settings I need to do, apart from dependency settings?

**Note**: I'm also interested in possible alternative solutions to get this to work (instead of using Conditional Fields).

# Answer
As an alternative solution to using the conditional fields module (cfr your comment in your question), you can use the Rules module for this. Here are some details (the pseudo code) about how to do so:

* **Rules Event**: Before saving content.
* **Rules Conditions**:

1. Check for "entity has field" (for field = Enable)
    2. Check for "entity has field" (for field = Photos Gallery)
    3. Compare the value of the "*Enable*" field, for both the original value (before editing the field) and the (new) updated value, to verify if they enabled (checked) this field.
    4. Check if field "*Photos Gallery*" is empty.
* **Rules Action**: display an error message to explain that your validation failed. For an example of how to display an error message using rules, refer to my answer to "How to make the permissions of a module more granular?" (which actually includes 2 actions, you only want the `drupal_message` part of it (probably not the redirect to somewhere else).

To understand the need for those Rules Conditions "1." and "2.", have a look at my answer to "How to check in a rules condition if an image field has value?"

Should be straight forward to "develop" such rule, no (PHP) coding at all involved (only site building using admin UI).

# Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.
> 4 votes

---
Tags: 7, entities
---


# Question
Title: Display data from web service using views
I need to query data from a web service and display it in a view without storing the data in Drupal database. I am using WSData module for this purpose but I am unable to figure out how and when the webservice is getting invoked. My web service doesn't have any parameters passed and it returns a list of items. I would like to display the list as a table using views.

It would be of great help if I can get any samples or references.

# Answer
> -1 votes
You can take a look at https://www.drupal.org/project/wsdata

This module allows you to bypass the default data storage location for fields and entities and instead load the data from a web service.

This is useful when your primary data source is in another system but you want to display/use this data in your Drupal site without the hassle of syncing or importing data.

---
Tags: 7, views, database
---


# Question
Title: How to make Drupal highlight the same menu item for 2 different nodes (URLs)
When defining the menu item, I can only choose a unique URL for language. But I want that a bunch of pages, one of them the referenced by the menu item, highlight that menu item (Products) so I know I am in that section of the page. For example:

```
www.example.com/products
www.example.com/search-product
www.example.com/product-detail

```

all would have to highlight the menu-item := products, that which references the first URL above.

I have tried with the following code but I am not sure if there is a faster and more direct approach, it seems too convoluted to me to theme() nothing to keep the above desired effect

**Code:**

```
   print theme('links__system_main_menu', array(
        'links' => $main_menu,
        'attributes' => array(

        ),
        'heading' => array(
          'text' => t('Main menu'),
          'level' => 'h2',

        ),
      ));

function theme_links__system_main_menu($variables) {
  $html = "<ul>";
  foreach ($variables['links'] as $link) {

  // HERE I would change $link['href'] to merge the 3 links
  //together and make that this item is hilited when I am in one of the 3
  //links. Of course, the href link will direct to the first one, but
  //the hilite will make the user to know that she is in this section.

    $html .= "<li>".l($link['title'], $link['href'], $link)."</li>";
  }
  $html .= "  </ul>";
  $html .= "";

   return $html;
}

```

Another coded approach:

```
 $a = menu_tree_output( menu_tree_page_data("main-menu") );
 print "<ul>";
foreach($a as $key => $value){
 active = "";
   if($value["#href"] == current_path() || ( drupal_is_front_page() && $value["#href"] == "<front>" ) ){
     // HERE I would change $link['href'] to merge the 3 links
    //together and make that this item is hilited when I am in one of the 3
    //links. Of course, the href link will direct to the first one, but
    //the hilite will make the user to know that she is in this section.

    $active = 'class="active"';
   }
        if($value["#href"] == "<front>"){
            $url = "";
        }else{
            $url = drupal_get_path_alias($value["#href"]);
        } // if
        if($value["#title"] != "") print '<li><a ' . $active . ' href="' . $base_url . "/" . $language->language . "/" . $url . '">' . $value["#title"] . "</a></li>";
    } // foreach
     print "</ul>";

```

# Answer
Recently I've the same needs in my site and the fastest and painless approach was doing in CSS instead create preprocess functions.

This was done in Drupal 8, but works independently of what you are using.

First make sure that you have a class or id named with your path in any place of your HTML, and then, just use it to style your link with same 'active' class. Something like this...

**HTML:**

```
<body class="path-product-detail">
  <header>
    <nav class="main-menu">
      <ul>
        <li><a href="/home">Home</a></li>
        <li><a href="/products">Products</a></li>
        <li><a href="/contact">Contact</a></li>
      </ul>
    <nav>
  </header>
  ...
</body>

```

**CSS:**

```
.main-menu .active,
.path-product-detail .main-menu a[href="/products"] {
  color: #fff;
  background-color: #c9093e;
}

```

**Try in JSFiddle:**
https://jsfiddle.net/t4vny2df/1/

**Edit 1: Detailed explanation**
First of all, in your `html.tpl.php` template **make sure that the current path is printed as a class**, this will be dynamically specified, **all the magic is right here in this class** (in Drupal 7, by default, seems the class is page-'currentPath' according docs).

Your HTML must print current path in body element.

```
<body class="page-currentPath ...">
...
</body>

```

Now, based in this class just use the right CSS selectors to highlight the menu item. I'm going to use the **'products' html code example**.

```
.main-menu /*Note 1*/ .active /*Note 2*/,
.page-product-detail /*Note 3*/ .main-menu a[href="/products"] /*Note 4*/,
.page-search-product /*Note 5*/ .main-menu a[href="/products"] /*Note 4*/{
  color: #fff;
  background-color: #c9093e;
}

```

First, in CSS we can use a combination of selectors do get the right element and we can use 'comma' to specify another selector to the same style (`a, p{color: #000} /*Element 'a' and element 'p' will be color black*/`)

**Note 1** \- Considering your menu with a class 'main-menu'.
**Note 2** \- Considering that you are using a 'active' class for current path.
**Note 3** \- If body has a class 'page-product-detail' this selector will be considered.
**Note 4** \- This selector will get the menu item that you want highlight and doesn't have a 'active' class, because you are not in '/products' page.
**Note 5** \- If body has a class 'page-search-product' this selector will be considered.

For more pages just add another line with your 'page selector'. Any questions just leave a comment and I explain.
> 1 votes

---
Tags: routes, theming
---


# Question
Title: How to send uploaded file as a link in entityform submission
I am using entityform for getting the user details. The entityform also contains a file field where user uploads resume. After the submission user gets the submitted form via email.

How to send the link of the uploaded file in an email to user.

Thank you.

# Answer
How are you sending the mail?

You can try using https://www.drupal.org/project/mimemail and just insert the image in your mail
> 0 votes

---
Tags: entities
---


# Question
Title: node_object_prepare causes profile page for non-admin users
When I'm calling node\_object\_prepare in a module to create a user profile type node Drupal 6 kicks the user out unless they have admin permissions.

How can I make node\_object\_prepare run regardless of the users role?

thank you, George

# Answer
I solved this by ripping the guts out of the node\_object\_prepare function, pasting it into the module and editing it appropriately so it served my purpose.
> 0 votes

---
Tags: nodes, 6
---


title: Alter content of search api views

text:
# Question
Title: Alter content of search api views
I've used drupal7, Search API 7.x-1.16, Search views 7.x-1.16, Solr search 7.x-1.9, Apache Solr search 7.x-1.7.

I am listing contents of some content type. Now i want to trim description field only if the content belongs to some content type. How to do this using **theme\_preprocess\_views\_view\_fields**?

# Answer
Is there a reason you want to use the ***theme\_preprocess\_views\_view\_fields*** hook?

Why not add the attribute **Content: type** to your View fields (see image), and then check the content type within a View template:

Then your code in ***views-view-fields--\[my\_view\]--\[my\_display\].tpl.php*** could look something like this:

```
<?php
  //check content type
  if($fields['content_type']->content == 'My content type') {
    //trim description by 200 chars (respecting full words)
    $pos = strpos($fields['field_my_description]->content, ' ', 200);
    substr($fields['field_my_description]->content, 0, $pos);
  }
?>

<h3><?php print $fields['title']->content; ?></h3>
<div class="my-description">
  <?php print $fields['field_my_description']->content; ?>
</div>

```

I haven't tested or tried the above code, but the proof of concept should be enough to help you along.

Using a Views template instead of a hook is also easier for site builders / themers to debug or change.
> 1 votes

---
Tags: views
---


title: How to modify sort order using PHP?

text:
# Question
Title: How to modify sort order using PHP?
I want to re-order the results of a View using some arbitrary PHP ( the sort is not possible in SQL ). I believe I could use either \_views\_pre\_render(&$view) or hook\_views\_post\_execute(&$view) to alter the order of the results. However the $view-\>result array only contains the number of results that the pager is set to, not the whole result set.

Is there some other method I can hook into the result generation process and alter the order of results using PHP ?

# Answer
> 3 votes
Views will always only return the results for the current page of results.

That is a benefit of paging, since you aren't retrieving all the data if users may only want to see some results.

If you want to sort after the results come from the database then you have to turn paging off and return all results. Then you can sort all the results and display them as you like.

**\[EDIT\]**

You mention in your comment potentially using hook\_views\_query\_alter() to alter the paging out of the query but (without having actually tried) I don't think that would work without removing the paging all together, because PagerDefault::execute() does its thing to the SQL after you are altering.

If you want to pursue that idea though, what might potentially work though is you doing Query alteration (tagging) by adding an alter tag in hook\_views\_query\_alter() and then implementing hook\_query\_TAG\_alter(), which would run on the preExecute(), which should be after the pager has acted.

For example:

```
/**
 * Implements hook_views_query_alter().
 */
function MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    // Add a query alteration tag so that we can alter the completed query before execution.
    $query->addTag('CUSTOM_TAG_NAME');
  }
}

/**
 * Implements hook_query_TAG_alter().
 *
 * Alter queries with the CUSTOM_TAG_NAME tag.
 */
function MODULE_NAME_query_CUSTOM_TAG_NAME_alter(QueryAlterableInterface $query) {
  // Alter the $query object here.
}

```

---
Tags: views
---


# Question
Title: How to get correct language code during installation?
I am programmatically creating some content during installation of my profile and I need to set the language for this content, otherwise it will be in English(which my site is not) and there will be issues with visibility of fields.

What is the proper way to get the language code in which the site is being installed? The language manager service is returning English, which is incorrect.

# Answer
Looks like getting it directly from config is working just fine:

```
\Drupal::config('system.site')->get('langcode')

```
> 2 votes

---
Tags: 8, i18n-l10n, installation-profiles
---


# Question
Title: Is there a Drupal 8 alternative for Inline Entity Form (to create an item while adding a reference)?
I have a Family content type and a Person content type. A Family has an Entity Reference field to one or more Persons.

The normal workflow requires me to first create the Persons, then create the Family and then add the Persons to the Family, but I want to create the Family first and create persons while adding them.

This is achieved in Drupal 7 with the Inline Entity Form. Is there something like that for Drupal 8? Any alternative?

# Answer
> 5 votes
You can use the alpha version and the dev version of the Inline Entity Form

# Answer
> 4 votes
@webflo created an inline entity form port, I haven't tried it yet: https://github.com/webflo/inline\_entity\_form

# Answer
> 3 votes
There is another promising alternative is the Entity Browser module:

> Goal of this module is to provide a generic entity browser/picker/selector. It can be used in any context where one needs to select few entities and do something with them.
>
> Possible use cases:
>
> * powerfull entity reference widget,
> * embedding entities into wysiwyg,
> * you name it!

---
Tags: entities, 8
---


# Question
Title: How to create commerce product content using date repeat entity module?
I am using date repeat entity module in a content type say Movies to successfully clone the nodes.I also have a commerce product reference field in that content type which is working fine when I am not using repeat date. I want to be able to create a new commerce product content for each node in the series when using repeat date.(while creating the Movies node I can see product fields like SKU,product title etc.)

For example, I am creating a new Movies having start as 1st Jan 2016 and end date as 2nd Jan 2016.I want to repeat this event for every Friday till 31st Jan. Now there will be 5 nodes created automatically. how do i create a new commerce product content for each of these nodes?

Thanks.

# Answer
> 0 votes
I'm not too familiar with Date repeat entity module, but why don't you try implementing ***hook\_node\_insert()*** in a custom module, to handle creating a new product every time a a new node is created:

```
/**
 * Implements hook_node_insert().
 */
function my_module_node_insert($node) {

  //check type and that no product set previously
  if($node->type == 'my_type') {

    //create product
    $cp = commerce_product_new('product');
    $cp->is_new = TRUE;
    $cp->revision_id = NULL;
    $cp->uid = 1;
    $cp->status = 1;
    $cp->created = $cp->changed = time();
    $cp->sku = 'My SKU';
    $cp->title = 'My Product';
    $cp->language = LANGUAGE_NONE;
    $cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
      'amount' => 1000, //$10.00
      'currency_code' => 'USD',
    )));

    //save new product
    commerce_product_save($cp);

    //set reference field
    $node->field_product['und'][0]['product_id'] = $cp->product_id;

    //update node
    node_save($node);
  }
}

```

I haven't tested this code, but this would be the general approach I would try.

This would only work if the Date repeat module invoked this hook though.

---
Tags: commerce, entities
---


title: CKEditor Toolbar Configuration

text:
# Question
Title: CKEditor Toolbar Configuration
I would like to use CKEditor on my Drupal website. But the toolbar is not showing up when I go to edit appearance on any profile (full or advanced). Although, when I add or edit any type of content, the toolbar is shown correctly and I don't have any problems there. Just when I try to configure the toolbar.

I took a picture so that you can see exactly what I have:

I also have these errors:

It seems that the problem might have something to do with JQueryUI according to the errors I have. I use JQueryUpdate to manage my JQuery version (which is 1.10). I tried uninstalling CKEditor, clearing caches but it's not doing anything. I use Drupal 7.41.

I know that this question has already been posted on this website, but after having read the answers it got I still have my problem so, sorry for the duplicate...

Thanks a lot for your answers :)

# Answer
> 1 votes
Ok I've just found the error. It seems that when I extracted my compressed version of my website, it renamed every folder in lowercase. So Drupal couldn't find jqueryUI folder, because it was renamed jqueryui.

---
Tags: javascript, wysiwyg
---


# Question
Title: How to update my module's dev branch on Drupal.org
I have a module on Drupal.org and I only have a dev branch. This is how I added my dev branch by tagging with 7.x-1.x-dev:

```
git commit -m 'Creating module'
git push origin 7.x-1.x
git tag 7.x-1.x-dev
git push --tags

```

Now I made some more changes and would like to have my dev branch updated with the latest code. I delete the tag and recreate the tag:

```
git tag -d 7.x-1.x-dev
git push origin :7.x-1.x-dev
git commit -m 'Adding new feature'
git push origin 7.x-1.x
git tag 7.x-1.x-dev
git push --tags

```

I did this and I don't see my files get updated on Drupal.org. Am I doing something wrong?

# Answer
No need to deal with tags for the dev branch. Tags are only required for stable releases.

Since you have already added your dev branch you just have to add your files, commit them and push them, like this:

1. git add path/to/files
2. git commit -m "Commit message"
3. git push origin 7.x-1.x

Then you just wait for drupal.org to reroll a new dev version. It takes up to 12 hours to see a new dev version on the project page.

You should be able to see your commits though if you click the **View commits** link in the development sidebar block.
> 7 votes

---
Tags: version-control, community-official-site
---


title: Node author and body as plain text

text:
# Question
Title: Node author and body as plain text
I need go get the node author as plain text and the same goes for the body field. So that means **NO** html markup. I cant find the right answer on google for drupal fields.

```
<?php print $name); ?>

```

gives it with html...

# Answer
> 0 votes
By the time that a `print $name` is available, you are already in a template or other late stage theme item, correct? This means the parts have already been passed through render methods to add all that html.

When I had a project that created pdf reports for download and printing, removing these items was important. I added a helper function to my site module. (every one of my sites receives a site\_\[name\].module, but you could add this to your template.php if you want to keep this all in the theme)

```
define('UNWANTED_REPORT_TAGS', 'span/h1/h2/h3/h4/div/strong');
/*
 * helper function for removing html from report contents
 * Strip only selcted tags in THEME_preprocess_node function below
 * strip defined constant tags if none given
 * Growth order of O(n) where n is the number of tags, so defaults to O(7)
 */
function module_strip_only($str, $tags = NULL, $keep = TRUE) {
  if ($tags == NULL) {
    // load the defaults
    $tags = explode('/', UNWANTED_REPORT_TAGS);
  }
  if (!is_array($tags)) {
    // we were passed a string, check format and parse
    $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
    if (end($tags) == '') {
      array_pop($tags);
    }
  }
  foreach ($tags as $tag) {
    // tag by tag, strip our given string
    if( $keep ) {
      $str = preg_replace('#</?' . $tag . '[^>]*>#is', '', $str);
    } else {
      // we want the usual text, drop tags and what they wrap
      $cleaning = TRUE;
      while( $cleaning ) {
        // regex probably doesnt work here
        $clipFrom = strpos( $str, '<' . $tag );
        $clipTo = strpos( $str, '</' . $tag , $clipFrom );
        $clipTo = strpos( $str, '>' , $clipTo ); // find end of closing tag
        $str = substr($str, 0, $clipFrom) . substr( $str, $clipTo );
        if( substr_count ( $str, '<'. $tag) < 1 ) {
          $cleaning = FALSE;
        }
      }
    }
  }
  return $str;
}

```

The function will need an appropriate name for you, of course. Then in your template file your line would be `<?php print html_strip_only($name); ?>`

If you just want to strip all `<>` sets from the string, you can do that like this. `<?php print preg_replace('</?[^>]*>', '', $name); ?>` and I am dont think that `/` needs escaped, but if it does then it would be `\/`. The online test tools want it escaped.

```
$pattern = '/<\\/?[^>]*>/';
$replacement = '';
$subject = '<p class="updated icon-clock">Updated: 1/14/2016</p><h3 class="field-label"> Related businesses  </h3>';
echo preg_replace($pattern, $replacement, $subject, -1 );

```

---
Tags: theming
---


# Question
Title: Apache Solr Search proper syntax in url?
Can anyone provide some info on how to properly execute a filtered apache sold search through the url? So far I've figured out that

```
?fq[]=bundle:type

```

will return a results filtered by that bundle type. I've also noticed that

```
?f[0]=machine_name:value

```

will return results if that particular facet has been configured. What I want to figure out, though, is how to use the url to send any filter request. For example, if I want to write a url that would return results based on a particular taxonomy term, how would I enter that? Furthermore, can any field be used to filter a search?

# Answer
> 0 votes
You should integrate Updated Apachesolr module. Write some custom menu hook to invoke your custom function.

```
 $query = apachesolr_current_query();
 $params_query = $query->getParams();

```

The above two statements will help us to check our solr queryString that we have triggered from our application.

```
/**
 * Implementation of hook_search_execute().
 */
function Custom_Function($keys = NULL, $conditions = NULL) {

  $filters = isset($conditions['fq']) ? $conditions['fq'] : array();
  $solrsort = isset($_GET['solrsort']) ? $_GET['solrsort'] : '';

  $response = NULL;
    $filt = array();
  // add custom filters if you want to add few custom filters in certain conditions.
   if($_GET['some key'] == 'some condition') {
        $filt[] = array('name' => 'entity_type', 'value' => 'trend_tips');
      }else{
        $filt[] = array('name' => 'im_16_field_category', 'value' => $_GET['category']);
      }
  $filters = $filt;
  $results = apachesolr_search_run('apachesolr', array('q' => $keys, 'fq' => $filters), $solrsort, 'search/' . arg(1), pager_find_page());

    // Set name for search results
    $query = apachesolr_current_query();

    $params_query = $query->getParams();

    if (module_hook($module, 'search_page')) {
      return module_invoke($module, 'search_page', $results);
    }
 }
/**
 * Implementation of hook_apachesolr_query_prepare().
 */
function CustomeModule_apachesolr_query_prepare(&$current_query) {

  // add query filters for Style tips and trends
  $current_query->addParam('fl', 'tm_image,tm_url,content');
  $current_query->addParam('qf', 'tm_title');
  $current_query->addParam('qf', 'tm_short_content');
  $current_query->addParam('qf', 'tm_perex');
  $current_query->addParam('mm', '1<-90%'); // if you write more then 1 word to search, solr search as 'OR'
  $current_query->addParam('bf', 'recip(rord(created),4,5759,5759)^5.0'); // remove time dependency on search results

  // remove following content types (product and page) from search
    $current_query->addFilter('entity_type', 'product', true);
    $current_query->addFilter('bundle', 'page', true);
    $current_query->addFilter('tid', "63", true);
    $current_query->addFilter('tid', "64", true);

  $current_query->addParam('facet.field', 'bundle');
  // add a new facet type for filter trends and tips on search results

}

```

Please let me know if the above codebase helped to get some grip.

Thanks

# Answer
> 0 votes
It might help you using something like the Pretty Paths module https://www.drupal.org/project/facetapi\_pretty\_paths

It will be much easier to construct the urls you want.

---
Tags: search
---