# Question
Title: Create Drupal 7 page specific tpl files without using node ID's
i know you can crate custom tpl files for a specific page by doing the following:

html--node-999.tpl.php

But this doesnt work well if the node-id is going to change when switching environments or migrating stuff. What is the file naming convention for drupal 7 tpl's that are URL Path specific?

# Answer
Happened upon this old question that didn't have a completely legit answer.

In short, you can set up templates based on path by using the formulae...

```
page--[front|internal/path].tpl.php

```

Put simply, if you want a specific page template for a custom page with a url of `support`, you would create a template named

```
page--support.tpl.php

```

or `support/contact` would be

```
page--support--contact.tpl.php

```

Of course you can and probably should use the `node--[type|nodeid].tpl.php` pattern if you are dealing with node pages. But creating a template based on path is definitely possible.
> 1 votes

# Answer
There is no **page--\[path\].tpl.php** or **node--\[path\].tpl.php** template name schema that will let you create a url-specific template, but you can do it through a pre-process function.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to convert Json data directly into xml - standardized way?
I'm having a Json:

```
[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]

```

And I want it to convert into XML:

```
<?xml version="1.0" encoding="ISO-8859-1"?>
<Us>
    <U1>
        <S>a</S>
        <D>b</D>
    </U1>
    <U1>
        <S>s1</S>
        <D>m1</D>
    </U1>
</Us>

```

I know the php way, first decoding json using `Json_decode()` and a bunch of `foreach loop` that finally generate XML.

But I want in Drupal way. There is a module `serialization` in core of Drupal 8. But don't know how can I take the services from that module in my custom one.

Also, I got a link, How to get it done using symfony, but again it seems like Drupal 8 standards are lacking somewhere by me.

What's the right approach to achieve this in Drupal way.

# Answer
> 1 votes
The Serializer component is a tool in your Drupal toolbox that should be used when you need to serialize and deserialize data from and to Drupal data such as entities. Unfortunately you cannot deserialize into a \StdClass without implementing your own normalizer.

Inject the `serializer` service into your class, and use the `serialize` method to normalize the non-Drupal decoded JSON array into XML.

```
// Inject this instead of using \Drupal
$serializer = \Drupal::get('serializer');
// Use json_decode or @4k4's example above and use associative arrays instead of object.
$json = json_decode('[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]', TRUE);
// Unfortunately it seems that for an array serializer xml_root_node_name won't work so wrap $json in the root name.
$data = ['US' => $json];
// Serialize into XML.
$xml = $serializer->serialize(
  $data,
  'xml',
  ['xml_root_node_name' => 'US']);

```

---
Tags: 8
---


title: Show custom banner per page

text:
# Question
Title: Show custom banner per page
Admin user wants to be able to upload image banners and select on which pages/nodes/views/panels to show it when visited (as a wide screen image banner above title).

It means when creating the banner node and uploading the image, there should be some field or list of pages to select from. But e.g. Views pages has no NIDs.

I kind of came up with a solution with Panels, where you just add field for your Article content type and upload the banner and then display it via Panels, so it would show above Title, etc. But it works only on node pages, but not Views pages. And that's still very limited, it means you need to add the banner field to every content type and still no solution for Views pages.

Is it possible somehow to have some type of a field that would autocomplete the path/node nid/view path when entering keywords and would be also separated by comma for multiple paths/pages and then render it via Views using contextual filters and output the view display via Panels?

# Answer
> 0 votes
There are a few ways of going about this... and I have literally done dozens of formulas for it since Drupal 6.

The way I usually go about this is with Bean (Drupal 7). Create a new Bean that will represent your banner, add some fields - then let the admin create the bean. Since it is based on blocks, you can set content type visibility or path visibility, and if you add Context (if you need that muscle) you get a lot more options.

Another way to do it, which is hard to describe in a comment, is to setup an entity type for banners (since they are **not** content), add the fields you need, and then on the node level, add an entity reference field. Create a view that displays the entity type in a view mode of your choosing, and base it on the ER relationship value. As you said, this won't solve Views pages, which is why you might want to stick with the block route. This formula is a little similar, as it entails relating whatever banner entity the user wants to the given node, and, you can set a default value to one banner if you need that option.

Yet another way to do it is to put a Field Collection representing banner components (title, link, image), and hide the Field Collection from the node rendering. Create a View, feed it the node id contextual filter, and have it render the node in a 'Banner' view mode, which will only hold the field collection. Then just theme that level of templates, and you're good to go.

The first way (with Bean) seems like your best option, whereas the second two put the creation aspect in the node form, but you lose a way to set them on non node pages (since the Views arg will fail). Blocks won't care what the page is made up of, as long as the path or visibility rule matches.

# Answer
> 0 votes
For now, solved by adding a image field for banner for the content type and then attaching the view block to node (to by pass view-nodes) via panels (with visibility rules).

So now, user can edit banners in all pages, because they are all nodes + views attached below them.

No one-page-settings-with-all-banners (like in screenshot) though.

But it works.

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


# Question
Title: What is the replacement of drupal_match_path()?
What is the replacement of `drupal_match_path()` in Drupal 8? The following function is removed from Drupal 8. How can I achieve same functionality in Drupal 8?

```
function drupal_match_path($path, $patterns) {
  $regexps = &drupal_static(__FUNCTION__);

  if (!isset($regexps[$patterns])) {
    // Convert path settings to a regular expression.
    // Therefore replace newlines with a logical or, /* with asterisks and the <front> with the frontpage.
    $to_replace = array(
      '/(\r\n?|\n)/', // newlines
      '/\\\\\*/', // asterisks
      '/(^|\|)\\\\<front\\\\>($|\|)/', // <front>
    );
    $replacements = array(
      '|',
      '.*',
      '\1' . preg_quote(config('system.site')->get('page.front'), '/') . '\2',
    );
    $patterns_quoted = preg_quote($patterns, '/');
    $regexps[$patterns] = '/^(' . preg_replace($to_replace, $replacements, $patterns_quoted) . ')$/';
  }
  return (bool) preg_match($regexps[$patterns], $path);
}

```

# Answer
> 8 votes
New PathMatcher service reports that the path.matcher service was introduced to deprecate most procedural functions in the path.inc file with its methods.
In particular, the equivalent of `$path_matches = drupal_match_path($path, $patterns);` is the following code.

```
$path_matches = \Drupal::service('path.matcher')->matchPath($path, $patterns);

```

The same service is used to check if the currently viewed page is the front page.

```
$is_front = \Drupal::service('path.matcher')->isFrontPage();

```

As usual, injecting the dependency is preferred over calling `\Drupal::service()`.

---
Tags: path-aliases
---


# Question
Title: Panel Page with Node Views, Flags and Rules Integration
I created a page where users can submit friendly games. Other users can show their interest by flagging (Flag A) these games.

The author of the game can see all prospects in another view (View 3 integrated in View 2 with Views field).

The author than can choose which prospect for a friendly game he accepts. He does this by flagging the prospects flag with an accept flag (flag B).

The accepted prospect than gets an email confirming the friendly game.

How is it possible for me to send emails to all prospects who did not get accepted?

I tried Rules (on flagging event) and Rules Link.

How do I tell Rules what friendly game node this is all about?

Hello, thank you for your ongoing help! I created a list of friendly games with relationships and contextual filters that display these users.

When I use "Load a list of entity objects from a VBO View." or "entity ids" drupal throws error messages at me.

Warning: Invalid argument supplied for foreach() in \_views\_bulk\_operations\_get\_field()

Another really strange error for this rule is "Illegal choice blog in type element." The view does not display blog types... I'll try to figure this whole mess out.

Another problem in my opinion would be that in my view is a contextual filter that gets the NID of the friendly game by the view it is integrated in by "views field module". So how does the view know what users it should display if I loop it with a rule? Wouldn't it just loop through all users that flagged any friendly game who are not flagged?

# Answer
If you can create a view (using the Views module) of those users that correspond to all those "prospects who did not get accepted" for a given game node, then you can ***process the results of a VBO enabled view via Rules***, using a rule that looks like so:

* Rules Event: After flagging the prospects flag with an accept flag (flag B).
* Rules Actions:
    + Load the VBO list of the users in your View.
    + Add a loop to perform a Rules Action "Send an eMail", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
> 0 votes

---
Tags: views, rules, panels, flags
---


# Question
Title: How to show SUM of values from referenced entity fields in a View?
Okay, I've a two content types "A" and "B". "A" is a parent and have a field referenced(Entity Reference) to the child content type "B". Now I've created a View(Table) with a list of "A". And I want to add a field to show the SUM of field values from the referenced type "B". How to do this? Is it possible to solve with a Rules?

# Answer
> 0 votes
1. Under Relationships, add a relationship for the desired field. "Entity Referenced". Not "Entity Referencing".
2. Under Fields, add the field you want to sum. Add the relationship in the field settings.
3. Under advanced, enable *Use Aggregation*.
4. Under fields, click Aggregation Settings next to the field and choose "Sum".

# Answer
> 0 votes
Okay, I've managed to find a solution via components. But to make component work fine in a loop with a entity referenced fields, add a "Entity is a bundle" condition. Because "Entity is a type" or "Content is a type" doesn't work for me.

---
Tags: entities
---


# Question
Title: Add class to views row if image fields has content
I have views which has multiple image fields. In some cases all those image fields are empty, but some cases one of them has content.

When image field has content I want to have extra class .has-image for views row.

There is image fields: image\_field\_1, image\_field\_2 and image\_field\_3

It can be done programmatically, but I'm lost how to check those fields. I know this much:

```
function YOURTHEME_preprocess_views_view_unformatted(&$vars){

```

**SOLUTION**

There can not be used `$vars['classes_array'][$id][]` because `$classes_array[$id]` is not an array.

Here is code for working solution.

```
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image) || !empty($row->field_field_image_2) || !empty($row->field_field_image_3)) {
      $vars['classes_array'][$id] .= ' has_field';
    }
    else {
      $vars['classes_array'][$id] .= ' has_no_field';
    }
  }
}

```

# Answer
When you use the preprocess function you find the result in

```
$vars['view']->result

```

and the corresponding classes array under

```
$vars['classes_array']

```

where in results and in classes array the corresponding rows have the same key.

You can do now something like this in your preprocess function:

```
foreach ($vars['view']->result as $rid => $row) {
  if (isset($row->YOUR_FIELD) && !empty($row->YOUR_FIELD)) {
    $vars['classes_array'][$rid][] = 'has_field';
  }
  else {
    $vars['classes_array'][$rid][] = 'has_no_field';
  }
}

```

It is untested and just a little scribble but maybe it helps you.
> 2 votes

# Answer
An alternative solution to using a preprocess function (because I wanted to override this in a module not the theme and didn't want to delve into the possibility of overriding the theme registry), I did the following:

1. created a custom version of the view's theme template **Style Output**: `views-view-unformatted.tpl.php`, by removing the div wrapper within the foreach loop
2. created a custom version of **Row style** output: `views-view-fields.tpl.php` by wrapping the fields with a div there and adding class names based on the field data in `$row->field_YOUR_FIELDNAME[0]['raw']['value']`

I had a boolean field I was checking, so you may want to log (with watchdog) or print out `$row->field_YOUR_FIELDNAME[0]` and see what's available.
> 0 votes

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


# Question
Title: How can I make sure a javascript cookie is set before page load?
I am setting a simple javascript cookie and checking it before firing a jquery ui dialog

```
(function ($) {
  Drupal.behaviors.setPopupConfig = {
   attach: function (context, settings) {
   if ($.cookie('modalServed') == null) {
    $.cookie('modalServed', 'yes');
    // build and show the dialog

```

I am adding the javascript with drupal\_add\_js in a hook\_entity\_load() in a module. In testing I've noticed that if I have a link element in the modal with a destination set to another place in the site with a potential modal dialog, the second dialog will fire before the cookie is set in the browser, which is not the intended behavior. I've tried adding weight and scope options to the drupal\_add\_js call, but it doesn't solve the problem. Is there another way to make sure the modal js only fires after the cookie is set?

# Answer
The solution in this case was to set a path on the jquery.cookie

```
$.cookie('modalServed', 'yes', {path: '/'});

```
> 1 votes

---
Tags: javascript, hooks, cookies
---


# Question
Title: How to select a Taxonomy term in a Pane's settings and send it as an argument to Views?
I have a taxonomy vocabulary *Help* with several terms, representing different topics. I also have a Panel page where I would like to add Panes that contain all nodes with a certain *Help* term. My idea was to create a content View that accepts filtering on a provided *Help* term. Next, I would simply add this View to my Panel page and select the desired *Help* term from a list in the Pane's settings.

I more or less succeeded: my View has a relation *Content: Taxonomy terms in node* (where I selected the *Help* vocabulary) and a contextual filter *Taxonomy term: name* (where I set up an appropriate validation criterium *Term name*). This works fine, but I have to manually type the term name in my Pane's settings. That is not so efficient, because the term names might change in the future.

Is it possible to pick the desired term name from a list?

# Answer
Maybe my initial request has a valid answer, but it is easier to forget about the contextual filter and only keep a relationship *Content: Taxonomy terms in node* to select the correct vocabulary. Next, filter on *Taxonomy Term: Term* and select the previously added relationship. Now you can select the required term from a list! Of course, you can duplicate the Views block as many times as needed and only override the taxonomy term. Finally, these blocks can be used in a Panel or elsewhere.
> 1 votes

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


title: Create unordered list in render array

text:
# Question
Title: Create unordered list in render array
I'm attempting to create an unordered list using a render array in a custom block in a custom module.

I understand if I wanted to wrap things in div I could always use the 'container' type. Like so

```
    $content = [
        'container'    => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => ['container'],
            ],
            'item 1'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'p',
                '#value'      => 'Item 1',
            ],
            'item 2'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'p',
                '#value'      => 'Item 2',
            ],
        ],
    ];

```

But I'd like to be able to use an unordered list like so

```
    $content = [
        'container'    => [
            '#type'       => 'html_tag',
            '#attributes' => [
                'class'      => ['container'],
            ],
            '#tag' => 'ul',
            'item 1'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'li',
                '#value'      => 'Item 1',
            ],
            'item 2'      => [
                '#type'       => 'html_tag',
                '#tag'        => 'li',
                '#value'      => 'Item 2',
            ],
        ],
    ];

```

What I'd like that to produce is

```
<ul class="container">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

```

But instead it produces

```
<ul class="container"></ul>
<li>Item 1</li>
<li>Item 2</li>

```

Is there a way to create an unordered list using render arrays?

# Answer
> 32 votes
Use the theme 'item\_list':

```
$content = [
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#title' => 'My List',
  '#items' => ['item 1', 'item 2'],
  '#attributes' => ['class' => 'mylist'],
  '#wrapper_attributes' => ['class' => 'container'],
];

```

The wrapper\_attributes are not used in all themes. In core this is `classy` and `bartik`, which is based on classy.

---
Tags: theming, 8, blocks
---


# Question
Title: How to display node number in content items that only show up to administrators on ALL content items?
Evertime I need to node number I need to go to content items and hover over it, memorize and use it after...

Is there a way to have the node number displayed on the content item, but only to administrator.

Is there a module for this? Or would I have to create a custom field with a token and add it to every display...?

# Answer
> 2 votes
> I need it to create links on menu items, to assign blocks to specific nodes, to create links to content items in articles ect...many reasons!

You're going the wrong way about this. Having your urls named `node/1`, `node/2` etc.. looks ugly and it's bad for SEO.

What you need to do is give your Content Types an url alias. You don't want your **How To Use Drupal** article url to be `node/1`. You want it to be `/articles/how-to-use-drupal`

You should use the **Pathauto** module. This module allows you to automatically create an url alias using tokens.

Then when you assign a block, you can use `articles/*` this will make the block show up on all articles urls.

**Pathauto Video Tutorial**

> I knew about path auto, I just thought it was better practice to use node items for links and so on, in case I change the page name later, node number never changes...

You can use the **redirect** module which will auto redirect the old path to the new path if you change the path name. Thus, you don't have to worry about updating links.

To make life easier, I would also recommend

### CKEditor Link - A plugin to easily create links to Drupal internal paths

# Answer
> 0 votes
There's nothing built-in, and without resorting to using PHP in blocks (dangerous) or installing modules, here's the simplest method I can think of...

Paste the following code into your *settings.php* file, and clear Drupal's caches. This will display a message showing the node number on node view pages. It will only trigger for users who have *Administer content* permission.

```
// For content admins, display node number in a message.
function system_node_view($node, $view_mode) {
  if (user_access('administer nodes') && $view_mode == 'full') {
    drupal_set_message("Node number: $node->nid", 'warning');
  }
}

```

Edit: The above is for Drupal 7. For Drupal 8, define the function as `function system_node_view($node, $display, $view_mode)`. I haven't tested that but I think it should work.

---
Tags: nodes
---


# Question
Title: Drush does not work after I sudo su to another user
I have a CentOS 6 server with WHM/cPanel. I installed a global Drush as root using the instructions here (http://docs.drush.org/en/master/install/). Drush works fine for any user I ssh in as. However I typically ssh in as my user and then sudo su to the user I'm working on. When I do that I get these errors. If I ssh in as that user directly drush works fine. How can I make drush work when I su to a different user?

```
PHP Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in phar:///usr/local/bin/drush/includes/startup.inc on line 366
Content-type: text/html; charset=UTF-8

<br />
<b>Warning</b>:  proc_open(): Descriptor item must be either an array or a File-Handle in <b>phar:///usr/local/bin/drush/includes/startup.inc</b> on line <b>366</b><br />
PHP Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in phar:///usr/local/bin/drush/includes/startup.inc on line 367
<br />
<b>Warning</b>:  proc_get_status() expects parameter 1 to be resource, boolean given in <b>phar:///usr/local/bin/drush/includes/startup.inc</b> on line <b>367</b><br />
PHP Warning:  proc_close() expects parameter 1 to be resource, boolean given in phar:///usr/local/bin/drush/includes/startup.inc on line 368
<br />
<b>Warning</b>:  proc_close() expects parameter 1 to be resource, boolean given in <b>phar:///usr/local/bin/drush/includes/startup.inc</b> on line <b>368</b><br />

```

**EDIT**

So I got it to work. If I do `sudo su - newuser` instead of `sudo su newuser` it works.

I think it's related to CLI/CGI. PHP runs as CLI when I su with the - and CGI when I su without the -. Can anyone explain the difference the - makes?

# Answer
> 0 votes
Found the answer here: https://superuser.com/questions/453988/whats-the-difference-between-su-with-and-without-hyphen

> The difference between "-" and "no hyphen" is that the latter keeps your existing environment (variables, etc); the former creates a new environment (with the settings of the actual user, not your own).

---
Tags: drush
---


# Question
Title: How do I wrap the label text of a checkbox with a span tag?
I have noticed that Drupal 7 generates check-boxes with a markup like this:

```
<label ..>
<input type="checkbox">
Label text ..
</label>

```

I want to wrap `Label text ..` inside a span tag, how to do that via the Drupal 7 API?

The result should be:

```
<label ..>
<input type="checkbox">
<span>Label text ..</span>
</label>

```

# Answer
You would either need to override `theme_form_element` in your theme, or, do a `hook_form_alter`, target specific checkbox form elements, and change their `#theme_wrappers` callback to your own theme implementation.

I personally would do the latter, since overriding `theme_form_element` will change the default rendering for any form element in your theme, and that may not be desirable in every scenario.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Is there a way to force drush to enable a module and ignore dependencies?
I'm getting `exception 'Drupal\Core\Config\UnmetDependenciesException' with message`Configuration objects (....) provided by cn\_migrator have unmet dependencies`in .../core/lib/Drupal/Core/Config/UnmetDependenciesException.php:84` when trying to enable a custom migration module. I've checked the dependencies listed in the YAML files and can't see anything missing. I really need to push ahead, but can't find a way to force enabling this module.

# Answer
No, you can't.

But, https://www.drupal.org/node/2655104 was committed today, and it allows you to see what exactly is missing. Try patching your site with that to see the problem.
> 3 votes

---
Tags: 8, drush
---


title: YML For Enabling a Contrib Module

text:
# Question
Title: YML For Enabling a Contrib Module
I am adding a contrib module to a project and I would like the module enabling to happen automatically on deployment. My deployment script pulls the code and runs a config update via drush config-import. What would the YML be to enable the module in the codebase on config update?

# Answer
> 14 votes
To enable a module, you just need a line in `core.extension.yml`. However, you also need all the configuration the module provides. You could copy that over yourself from the config install and optional folder.

But the usual workflow is that at you enable the module manually at some point, using drush or the UI, then optionall customize the configuration and then export the config and deploy that.

---
Tags: 8, configuration
---


# Question
Title: How do I tell Drupal 8 to use my custom module's theme template when rendering an image that is linked?
I'm building a custom module to extend the default image field. It adds additional attributes that relate to the image field on a per content type basis. At this point it will take and store the attributes =\> values and when calling hook\_preprocess\_field() they can be returned (printed) so I can rest assured that they are indeed storing and relating correctly. The final part of the puzzle is to assign my twig template and insert my custom attributes. I thought that hook\_theme() would do the job but so far I have failed and I can't find any suitable documentation on the subject when it comes to fields or image fields.

How do I tell Drupal to use my custom module's template when rendering an image that is linked?

# Answer
Answering my own question. The solution was to use: `hook_theme_registry_alter()`

`/**
 * Implements hook_theme_registry_alter
 */
function MY_MODULE_theme_registry_alter(&$theme_registry) {
 $theme_registry['image_formatter']['path'] = drupal_get_path('module', 'MY_MODULE') . '/templates/field';
}`

In my module I have the templates/field directory with the template `image-formatter.html.twig`, so no other changes were necessary.
> 0 votes

---
Tags: 8
---


# Question
Title: Recursive multilevel taxonomy feeds Drupal 7
I am currently using 2 feeds of module Feeds to load a simple structure of nested taxonomies, with just 2 levels. I use two CSV files, one with the parent taxonomies, and the other with the children (see attached image to see the relationship through a PGUID, parent id). But now the problem is that my client will want no 2 fixed levels, but 3, 4, or more, varying depending on demand. So I do not know how to optimize the load (it is running in a cron in Elyisia cron right now). Must I create a new feed for each level? What happens if the levels differ from day to day? Is there any recursive solution to this - Multilevel Feeds or something ?

**Note:** the handling of the multilevel taxonomies should be done in just a single CSV file.

# Answer
You can solve this by double running an import with only one master CSV and using the **Skip hash check** & **Update existing terms** settings within your importer.

Feeds tracks each imported item in the `feeds_item` table. As entries are imported, it adds the imported `guid` to the table and stores hashed value of the imported row within `hash`. This hash value is checked upon reprocessing so Feeds can skip any unnecessary updating (if the source data hasn't changed it doesn't need reprocessing).

If **Skip hash check** is enabled with **Update existing terms** set to *Update existing terms*, this forces Feeds to update regardless. For your purposes, the first import run will ensure that each feed item is in the `feeds_item` table. On the second import run, the hierarchy integrity will be restored as each pguid will have a valid `guid` reference in the `feeds_item` table.
> 0 votes

---
Tags: taxonomy-terms, feeds
---


title: Field template using Display Suite

text:
# Question
Title: Field template using Display Suite
In Drupal 7 I could go to any entity's "manage display" and choose "expert" or "minimal," etc.

In Drupal 8, I can see a Twig template for expert, and a Plugin for expert (ex.g.) as well. But how do I get the UI where I can choose 'expert'?

If it's no longer in the UI, how do I implement my own Plugin? How can I write twig for just that field? If I'm doing that, why do I need Display Suite anyway (as I'm just using a one-col layout)? Do I?

# Answer
> 4 votes
**Please follow the below steps :**

1. Go to Structure \> Display Suite
2. Under Displays please click on settings tab and enable the checkbox named Enable Field Templates
3. Cheerss..now you can select desired templates.

---
Tags: 8, display-suite
---


# Question
Title: Clean urls - auto path alias - how to remove accents (Á É Ó Í Ñ ) from the urls?
I´m using Drupal 7.9 and pathauto 7.x-1.0-rc2

I want to remove the accents from the paths and replace them with normal letters

```
Á=A
É=E
Ó=O
Í=I
Ñ=N

```

etc.

I'm using a taxonomy field type and node title to build the path:

```
[node:field_provincia]/[node:title]

```

resulting into e.g. *ávila/mérida*

Does pathauto have some kind of hooks that I could use to apply this function?

```
function removeAccents($str)
{
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'Ĳ', 'ĳ', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ŉ', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

```

# Answer
> 18 votes
Have you seen transliteration module ? The project summary says it could be used with pathauto 2.x to use transliteration for URLs.

# Answer
> 14 votes
The simplest way to perform this remains **transliteration** module.

To answer specifically to "*Does pathauto have some kind of hooks that I could use to apply this function*", you can use **hook\_pathauto\_alias\_alter()** :

```
function YOURMODULE_pathauto_alias_alter(&$alias, &$context){
  $alias = removeAccents($alias);
}

function removeAccents($str){
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'Ĳ', 'ĳ', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ŉ', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

```

Just **adapt** `removeAccents()` **to your specific language needs**... You'll find many functions trying to list all kind of accents, see Remove diacritics from a string i.e., but I'm afraid none is universal.

There is also an **elegant way to transliterate, using php iconv function**, which removes most of the diacritics. If you are getting question-marks in output, it might be convenient to setlocale first. In context :

```
function YOURMODULE_pathauto_alias_alter(&$alias, &$context){
  setlocale(LC_CTYPE, 'es_ES');//Spanish Spain i.e
  $alias = iconv('UTF-8', 'ASCII//TRANSLIT', $alias);
}

```

EDIT : after reading some comments, I found useful to add this:

# Answer
> 4 votes
As per Kojo's suggestions and and source from here: https://stackoverflow.com/questions/3371697/replacing-accented-characters-php -- I'm using this code which seems to be working fine:

```
function mymodule_pathauto_alias_alter(&$alias, &$context) {
    removeAccents($alias);
}

function removeAccents(&$str) {
    $unwanted_array = array('Š' => 'S', 'š' => 's', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
        'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U',
        'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c',
        'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o',
        'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y',
        'G' => 'G', 'I' => 'I', 'S' => 'S', 'g' => 'g', 'i' => 'i', 's' => 's', 'ü' => 'u',
        'a' => 'a', 'A' => 'A', '?' => 's', '?' => 'S', '?' => 't', '?' => 'T'
    );
    $str = strtr($str, $unwanted_array);

}

```

I've added Turkish and Romanian chars too as in the post comments.

I don't want to use iconv as suggested by Kojo mainly because locale will need to be set and there is added burden to coin the locale string.

# Answer
> 0 votes
You can use pathauto\_cleanstring() for remove the accents character from URL.

```
function MYMODULE_pathauto_alias_alter(&$alias, &$context) {
  if (isset($context['data']['node'])) {
    // Include the pathauto module.
    module_load_include('module', 'pathauto');
    // Clean up a string segment to be used in an URL alias.
    $alias = pathauto_cleanstring(preg_replace('/\s+/', '', $alias));
  }
}

```

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


# Question
Title: Import legacy site URLs via url_alias table
I have a long table of legacy site URLs (Drupal 6 site) and the new URLs they should redirect to on the new site (Drupal 8). The list is too long to make this an .htaccess fix, and too irregular for an easy rule.

I tried simply inserting the rows into the url\_alias table and have found that they don't work unless I find them in the URL Aliases admin page, edit them and save them. I guess this means that the redirects are stored somewhere else as well as that table. Clearing the cache manually didn't seem to help.

I can't think of a way to do what I need with the various path / redirect modules I've found so far (though I'm really open to trying) and most of the code samples out there are D6 or D7. Is there a way (as a one-off) that I can get Drupal to re-read the entire url\_alias table and make them proper redirects? Or is there another way to get all the redirects in place? Any help much appreciated!

# Answer
For storing aliases use Drupal\Core\Path\AliasStorage:

```
\Drupal::service('path.alias_storage')->save($source, $alias, $langcode);

```

But it should be no problem, if you inserted the rows by hand. Check, if all source paths and aliases have a leading '/'. And that `langcode` is set to a language like `'en'` or `'und'` for undefined.

Then clear the cache. It is enough to invalidate the cache tag 'route\_match':

```
drush ev '\Drupal\Core\Cache\Cache::invalidateTags(['route_match'])'

```
> 0 votes

---
Tags: 8, database, path-aliases, importing-exporting
---


# Question
Title: Question regarding SearchAPI and Index performance/scaling
I have a site that will need to deal with thousands of nodes. it's an internal site, not public facing, with a daily concurrent user base of no less than 80 and no more than 100 users.

I am trying to figure out how to deal with search and indexing. The Big problem is I need facets and whatnot, but I also need instant data retrieval. So users can't wait for indexes to catch up. can one index via SearchAPI near instantly?

On average, there might be 2-300 new nodes created per day, every day, by users, and an additional 5-600 nodes created per day+ through automated imports (Feeds).

I was thinking of just using straight views, and trying to do search filters, but it's not scalable and after a few months to a year it would be quickly unmanageable.

TL:DR: Many many nodes per day need indexed search with facets (SearchAPI and FacetAPI using ElasticSearch). Near instant retrieval required. If a user creates a node, they need to be able to see that node in the index within a few seconds or less.

Alternatively, thinking out loud, could I have it submit the new node to the index on every new node addition?

# Answer
Regarding Search, I would suggest to go with external Search System, like ApacheSolr, Elastic Search, Algolia, etc. This will make sure that database will not be overloaded with content index.

I'm working on a project where we currently have almost 2 Lac nodes and around 30-500 nodes created every day. The number of concurrent users are 1-20 max. We're using ApacheSolr (Solr hosted on different server) with Search API and Search API Solr Module and results are retrieved in less than 1-2 Seconds (The Project is internal of Client's Company so can't share the link here).

> I was thinking of just using straight views, and trying to do search filters, but it's not scalable and after a few months to a year it would be quickly unmanageable.

Using view for rendering search results will not help much in terms of instant results. Preferred way will be writing custom code to query based on keyword and show results based on requirement.

> Alternatively, thinking out loud, could I have it submit the new node to the index on every new node addition?

Indexing of Node after Creation/Updates are managed by module. The search indexing is normally done when running Cron. So setting up your site Cron to run every minute will make sure that the nodes are indexed instantly.

Hope this helps.
> 1 votes

---
Tags: 7, performance, search
---


title: Commerce file description not showing

text:
# Question
Title: Commerce file description not showing
I'm using Commerce License and Commerce Files to sell digital downloads (zip files). Usually this works completely fine, so I'm thinking this might be a bug on my site on not in the modules themselves - but I'm not sure.

On one specific product the file description (and therefore the download link) doesn't appear on the user's file tab.

The orders that needs to download are in 'pre-order' paid state (using Commerce Pre-oder, which isn't a problem on other products on our site.

Here's the pre-order rule in case that's causing this:

```
{ "commerce_preorder_checkout_complete_generate" : {
    "LABEL" : "Generate pre-order pending orders on checkout completion",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "10",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Pre-order" ],
    "REQUIRES" : [ "rules", "commerce_preorder", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_preorder_order" } },
      { "data_is_empty" : { "data" : [ "commerce-order:commerce-preorder-order" ] } }
    ],
    "DO" : [
      { "commerce_preorder_generate_pending_orders" : {
          "USING" : { "commerce_order" : [ "commerce-order" ] },
          "PROVIDE" : { "pending_orders" : { "pending_orders" : "Pending orders" } }
        }
      }
    ]
  }
}

```

Any ideas as to how to investigate the issue?

# Answer
You can check the rules that change the order state into: 'pre-order'. This would be my first guess that the rules are not configured ok. Hope that i helped.
> 0 votes

---
Tags: commerce, files
---


title: Skip required body field validation

text:
# Question
Title: Skip required body field validation
It's possible to skip required body field validation, if it's empty? I can add custom validation on the first place, like:

```
  $form_validate = $form['#validate'][0];
  $form['#validate'][0] = 'remove_body_field_validation';
  $form['#validate'][] = $form_validate;

function remove_body_field_validation($form, &$form_state) {
 $form_state['complete form']['settings']['body_field']['body']['#required'] = FALSE;
}

```

But i think the "required validation" runs before "remove\_body\_field\_validation"?? :-/

# Answer
> 6 votes
Why don't you simply go to Structure -\> Content Types -\> \[Your type\] -\> Manage Fields -\> Body -\> Edit uncheck "Required field"? Since Drupal 7, body behaves as any other field...

If you really need to do this in code, then you do it in form\_alter like this:

```
function [mymodule]_form_alter(&$form, &$form_state, $form_id) {
  // some logic here to filter which form is affected (or use hook_form_FORM_ID_alter)
  $form['body'][LANGUAGE_NONE][0]['#required'] = FALSE;
}

```

Is there any particular reason for you to do it during validation and not on form render? You stated that you need to "skip required body field validation, if it's empty" which is equivalent to turning the "required" completely.

EDIT: I found a way to do this (based on this - https://api.drupal.org/comment/28464#comment-28464):

```
function my_validate($form, &$form_state) {
  $errors = form_get_errors();

  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

    // Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'body][und][0][value') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

    // Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

    // Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');
    }
  }
}

```

# Answer
> 0 votes
To clear previous validation errors, you can clear them in `form_set_error` static variable, e.g. add callback to `#element_validate` to your element and try the following function:

```
function remove_body_field_validation(&$element, &$form_state, $form) {

  if ($element['#field_name'] == 'body') {
    $element['#required'] = FALSE;
    // Clear previous validation errors.
    $errors = &drupal_static('form_set_error', array());
    $err_key = $element['#field_name'] . '][' . LANGUAGE_NONE;
    if (array_key_exists($err_key, $errors)) {
      unset($errors[$err_key]);
    }
    return;
  }

}

```

---
Tags: 7, forms
---


# Question
Title: Using a conditional OR in a view query alter programmatically
I am trying to use an conditional OR in my custom module.

```
hook_views_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)

```

I get it to work with either one of these conditions set, but not together.

```
if (isset($query->alterTags['VIENAME'])) {
  $query->condition('draggableviews_structure.entity_id' , NULL, 'IS NULL');
  $query->condition('draggableviews_structure.view_name', 'view_display_name', '=');
}

```

How do I set an OR value between them, so if either is true?

Thanks

# Answer
You can do this by using `orConditionGroup()`:

```
$query = \Drupal::entityQuery('map');
  $group = $query->orConditionGroup()
    ->condition('attributes.color', 'red')
    ->condition('attributes.color', 'green');
  $entity_ids = $query
    ->condition('attributes.building_type', 'bikeshed')
    ->condition($group)
    ->execute();

```

Example from https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Query!QueryInterface.php/function/QueryInterface%3A%3AorConditionGroup/8.2.x

Edit:

The question has a typo in the hook name, correct is

```
hook_query_views_alter(AlterableInterface $query)

```

which implements hook\_query\_TAG\_alter() for a query tagged by Views.
> 0 votes

---
Tags: 8, views
---


title: How do I create menu programmatically?

text:
# Question
Title: How do I create menu programmatically?
I read through the Drupal 8 menu\_api documentation in drupal.org. The example guide lists an option to create menu links and insert them into an existing menu. How does one create menu itself first and insert the menu links afterwords?

I used the entitytype manager based on the other answer in stackexchange, but going yml way is recommended. Any pointers?

```
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;

\Drupal::entityTypeManager()
->getStorage('menu')
->create([
 'id' => 'test',
 'label' => 'test menu',
'description' => 'test test',
 ])
 ->save();

```

Using routes below to create the links:

```
 test.home:
 title: 'Home'
 url: 'test.url'
 menu_name: test
 weight: 1

```

# Answer
> 1 votes
If you have a feature where you need to create a menu whenever something happens, using the code should be just fine.

I prefer using the static create method on the entity object `\Drupal\menu\Entity\Menu::create`, but the manager is fine as well.

If you are creating menu's on your development environment as part of setting up your drupal site, I would advice using config export/import. If you use drush, you can make it part of the deployment to import configuration so production always reflect the configuration you have saved. I prefer to do things like this, but for small sites it might be a bit overkill.

---
Tags: 8, routes, navigation
---


# Question
Title: Unset required attribute with multiple submit buttons and multistep form
I have a multistep form created with msnf for an content type. I set multiple submit buttons that each one has its own submit callback, and also i want every single button with its validation callback :

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id){
        case "my_form_id" :
          $form['actions']['submit_2'] = array(
                '#type' => 'submit',
                '#name' => 'button_name',
                '#value' => t('Name'),
                '#weight' => 6,
                '#submit' => array('node_form_submit'),
                '#validate' => 'MYMODULE_validate_2'

            );
            // Add submit callback (works fine!)
            array_unshift($form['actions']['submit_2']['#submit'], 'MYMODULE_form_submit_2');
            // rest of code ...
  }
}

```

inside the validation callback i put this test code :

```
function MYMODULE_validate_2($form, &$form_state){
  dpr('test');
  exit;
}

```

Here i have two problems :

1) this validation callback didn't triggered i don't know why ? (the system must show me a dump 'test' and then exit but nothing happen!)

2) I want to disable all the required fields only when i click on this submit\_2 button.

I found sth in this post, but like i said the validation callback is not handled so i can't test the code inside that post.

Thanks in advance.

**EDIT** I was blind :p I must put the callback function inside an array() like this

```
'#validate' => array('MYMODULE_validate_2')

```

sometime i made stupid error :)

Now my problem is only the second one :

* I want to disable all the required fields only when i click on this submit\_2 button.

# Answer
> 1 votes
the solution inside this post works perfectly!

worked for me like this :

```
function MYMODULE_validate_2($form, &$form_state){
    $errors = form_get_errors();
    if ($errors) {
      form_clear_error();

      foreach ($errors as $name => $error_message) {
         unset($errors[$name]);
      }
    }
}

```

# Answer
> 1 votes
You can set the #limit\_validation\_errors property on your submit button to an empty array to bypass validation on all required elements.

# Answer
> 0 votes
Normally you should use `#limit_validation_errors`.

Although for more sophisticated requirements, you can add a custom validation handle by adding into `#element_validate` element for every field which you need, e.g. (Entityforms example):

```
/**
 * Implements hook_field_attach_form().
 */
function FOO_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {

  // Attach these validation handlers only to elements belonging to entityforms.
  if ($type == 'entityform') {
    // Ignore the following fields for validation.
    $ignore = array('fieldset');
    // Attach validation handlers to simple fields.
    _attach_validation_handler_recursive($form, $ignore);
  }

}

/**
 * Recursively attaches a validation handler.
 *
 * @param array $element
 *   Form element to attach a validation hanlder to.
 */
function _attach_validation_handler_recursive(&$element, $ignore = array()) {
  if (!empty($element['#field_name'])
    && !empty($element['#bundle'])
    && !empty($element['#entity_type'])) {
    // Ignore fields that we don't want to process for required validation.
    $field_info = field_info_field($element['#field_name']);
    $instance_info = field_info_instance($element['#entity_type'],
      $element['#field_name'], $element['#bundle']);

      if (!empty($element['#type']) && !in_array($element['#type'], $ignore)) {
        // Required validate handler.
        if ($element['#required'] && !isset($element['address_container'])) {
          if (!empty($element['#element_validate']) && is_array($element['#element_validate']) && !in_array('FOO_validate_required_field', $element['#element_validate'])) {
            $element['#element_validate'][] = 'FOO_validate_required_field';
          }
          else {
            $element['#element_validate'] = array('FOO_validate_required_field');
          }
          $element['#check_empty'] = TRUE;
        }
      }
  }

  $children = element_children($element);
  foreach ($children as $child) {
    $child_element = &$element[$child];
    _attach_validation_handler_recursive($child_element, $ignore);
  }
}

```

and in that callback you can disable `#required` flag for specific fields with certain conditions (like specific triggering element or when field is hidden), e.g.

```
/**
 * Implements callback for #element_validate Form API.
 *
 * Validates required fields for entity form.
 */
function FOO_validate_required_field(&$element, &$form_state, $form
  if (isset($element['#access']) && !$element['#access']) {
    // Ignore hidden elements.
    $element['#required'] = FALSE;
    // Clear previous validation errors for not active elements.
    $errors = &drupal_static('form_set_error', array());
    $err_key = $element['#field_name'] . '][' . LANGUAGE_NONE;
    if (array_key_exists($err_key, $errors)) {
      unset($errors[$err_key]);
    }
    return;
  }

  if (empty($element['#required'])) {
    // Ignore elements that are not required.
    return;
  }
}

```

---
Tags: 7, forms
---


# Question
Title: discount coupon has applied on complete order not specific product in the order
commence ( commence discount ).coupon code is applicable only one product. but As per attached image coupon has redeemed price on all product in the cart.i am explaining in details here.There are two product with name 1.Preventing Sexual Harassment at the Workplace - Certificate Programme with original price ₹3,596.00 2.Intellectual Property: Law and Management - Certificate Programme with original price ₹3,596.00

i have applied 20 % coupon only first product it should be redeemed -₹899.00 but it has redeemed -₹1,798.00 rather than ₹899.00 it means it is redeeming same amount on another product also however i have not applied coupon on 2nd product.

HELP WOULD BE GREAT APPRICATED

# Answer
> 0 votes
In admin/commerce/discounts/manage/ choose discount type to **`product discount`** and add the product(SKU) for which you want to apply discount and save the discount form.

For adding description you can add it in form\_alter()

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout' ) {
    $form['commerce_coupon']['#description'] = t('Enter the coupon code <strong>***100</strong> to avail discount');
  }
}

```

Hope it works.

---
Tags: commerce
---


# Question
Title: How can I disable a form's default validation functions?
I have created my own validate handler:

```
/**
 * Validate handler.
 */
function my_module_validate($form, &$form_state) {
  $values = $form_state['values'];
  if ($values['type'] == 'line') {
    form_set_error('type', t('MY VALIDATION.'));
  }
}

```

which is called from a button element:

```
'preview' => array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#validate' => array('my_module_validate'),
  '#weight' => 8,
),

```

which produces this result on submission of an empty form:

The only validation function that I want to run is my own, from my own handler - the last error message - yet all the default validation functions run as well. How do I disable these?

# Answer
As per function form\_set\_error: "If #limit\_validation\_errors is set on a clicked button, the button must also define a #submit property (may be set to an empty array)." So your preview button should be:

```
'preview' => array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#limit_validation_errors' => array(array('map')),
  '#submit' => array(),
),

```
> 5 votes

# Answer
The FAPI allows you to do this without altering the $\_SESSION messages array by using #limit\_validation\_errors.

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['my_textfield'] = array(
      '#type' => 'textfield',
      '#title' => t('Some title'),
      '#required' => TRUE,
      '#element_validate' => array('my_element_validate'),
    );
    $form['preview'] = array(
      '#type' => 'button',
      '#value' => t('Preview'),
      '#limit_validation_errors' => array(array('my_textfield')),
    );
  }
}

/**
 * My textfield element validate handler.
 */
function my_element_validate($element, &$form_state, $form) {
  // Check the value here.
  if ($element['#value'] == '123') {
    form_error($element, t('123 not allowed!'));
  }
}

```
> 2 votes

# Answer
I have found a way that works:

```
$form_required_marker = array('#theme' => 'form_required_marker');
$required = ' ' . drupal_render($form_required_marker);

'map' => array(
  '#type' => 'select',
  '#title' => t('Map') . $required,
  // '#required' => TRUE,
  '#options' => array(
    '' => t('- Select -'),
    'map1' => t('Map 1'),
    'map2' => t('Map 2'),
  ),
),

```

...then specify a custom validation handler with `#validate`.
> 1 votes

# Answer
You see different validation error, because your validation callback is called after the error happened. One solution is to call `form_clear_error()` to clear previous errors and set the new one. Or unset specific element validation error in your element validate callback, e.g.

```
/**
 * Implements callback for #element_validate Form API.
 */
function my_module_map_validate($element, &$form_state, $form) {
  if (empty($element['#value'])) {
    // Clear previous validation error for this element.
    $errors = &drupal_static('form_set_error', array());
    $err_key = $element['#field_name'] . '][' . LANGUAGE_NONE;
    if (array_key_exists($err_key, $errors)) {
      unset($errors[$err_key]);
    }
    form_error($element, t('xyz'));
    return;
  }
}

```
> 1 votes

# Answer
I've part solved the problem by using this custom function \- but it's not perfect.

It works perfectly on first valiadtion failure, but if I create another validation failure, I get a blank error message and then this error:

> Notice: Undefined offset: 0 in theme\_status\_messages().

Code:

```
/**
 * Validate handler.
 */
function my_module_validate($form, &$form_state) {
  if ($type = $form_state['values']['type']) {
    switch ($type) {
      case 'map':
        $names = array(
          'line_sub_type',
          'margin_top',
          'margin_right',
          'margin_bottom',
          'margin_left',
          'x_axis_label',
          'y_axis_label',
          'date_time_format',
        );
        break;
      case 'line':
        $names = array(
          'map',
          'land_color',
          'boundary_width',
          'color_key',
          'lighter_end',
          'darker_end',
          'units_format',
        );
        break;
      }
    foreach ($names as $name) {
      my_module_form_unset_error($name);
    }
  }
}

/**
 * Clear a form element error.
 */
function my_module_form_unset_error($name) {
  $errors = &drupal_static('form_set_error', array());
  $removed_messages = array();
  if (isset($errors[$name])) {
    $removed_messages[] = $errors[$name];
    unset($errors[$name]);
  }
  $_SESSION['messages']['error'] = array_diff($_SESSION['messages']['error'], $removed_messages);
  if (empty($_SESSION['messages']['error'])) {
    unset ($_SESSION['messages']['error']);
  }
}

```
> 0 votes

# Answer
In hook\_form\_alter() function, you can unset the default validation rules and then specify your validation function as validate handler

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'YOUR FORM ID') {
    unset($form['#validate']);
    $form['#validate'] = array('my_module_validate');
  }
}

```

Please note that this change will completely remove the form validations from all the fields and you need to handle the validation of all the fields individually.
> 0 votes

---
Tags: forms
---


title: Mails are not always send

text:
# Question
Title: Mails are not always send
When a user creates an account, sometimes all the mails are sent, sometimes not all, and sometimes no mails are sent but they are returned on the site-owner mail address. All the mails are considered as spam and i don't know why. On the returned mail i get this (I have no error in Drupal report and logs) :

This is the mail system at host "my host".

I'm sorry to have to inform you that your message could not be delivered to one or more recipients. It's attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can delete your own text from the attached returned message.

```
               The mail system

```

\<"site mail"\>: host gmail-smtp-in.l.google.com\[2a00:1450:4013:c01::1a\] said: 550-5.7.1 \[2001:41d0:d:363d::\] Our system has detected that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and 550-5.7.1 authentication. Please review 550-5.7.1 https://support.google.com/mail/?p=IPv6AuthError for more information 550 5.7.1 . w82si7064886wma.125 - gsmtp (in reply to end of DATA command)

Final-Recipient: rfc822; "targeted email" Action: failed Status: 5.7.1 Remote-MTA: dns; gmail-smtp-in.l.google.com Diagnostic-Code: smtp; 550-5.7.1 \[2001:41d0:d:363d::\] Our system has detected that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and 550-5.7.1 authentication. Please review 550-5.7.1 https://support.google.com/mail/?p=IPv6AuthError for more information 550 5.7.1 . w82si7064886wma.125 - gsmtp

----- *** MAIL RESUME *** ----- ...

What can i do to fix that ?

# Answer
The error message you have provided indicates that you do not have a reverse PTR record in your DNS for the IP address you are using, specifically in this case for IPv6. When you look a specific IP address up it should resolve back to a known hostname which identifies it in DNS. Some mailservers and systems will not accept email from hosts without a valid PTR record. I would imagine that in your case you have some IPv6 records in place, and that your server is connecting to Google's SMTP servers over IPv6 but that you do not have the correct records in place. The error message provides a link to https://support.google.com/mail/?p=IPv6AuthError which should tell you more about this error.

You should also make sure that you have correctly setup SPF for the domain that is used as the from address in your emails, you may need to add an SPF record, or update the existing one for the domain so that your webserver is trusted to send email on behalf of your domain.
> 2 votes

---
Tags: 7, emails
---


# Question
Title: Making a file downloading system with valid input in a custom drupal 8 form
I am trying to create a custom drupal 8 form, that is going to allow user to enter his/her firstname, lastname and email address, and if the user enters these credentials, will be able to download the file that I will upload to cms. This is how my form looks like right now:

```
namespace Drupal\whitepaper\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

class WhitePaperForm extends FormBase {

/**
 * {@inheritdoc}.
 */
public function getFormId() {
  return 'whitepaper_form';
}

/**
 * {@inheritdoc}.
 */
   public function buildForm(array $form, FormStateInterface $form_state) {
  $form['iam'] = array(
   '#type' => 'select',
   '#title'=>t('I am:'),
   '#options' => array(
    'dentist' => t('Dentist'),
    'broker' => t('Broker'),
    'engineer' => t('Engineer'),
   ),
   '#required' => TRUE,
  );
  $form['fname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('First Name:'),
   '#required' => TRUE,
  );
  $form['lname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('Last Name:'),
   '#required' => TRUE,
  );
  $form['email'] = array(
   '#type' => 'email',
   '#title' => $this->t('Your .com email address.'),
   '#required' => TRUE,
  );
  $form['show'] = array(
   '#type' => 'submit',
   '#value' => $this->t('Download Whitepaper'),
  );

  return $form;
}

/**
 * {@inheritdoc}
 */
public function validateForm(array &$form, FormStateInterface $form_state) {

  if (strpos($form_state['values']['email'], '.com') === FALSE ) {
    $this->setFormError('email', $form_state, $this->t('This is not a .com email address.'));
  }
 }

 /**
  * {@inheritdoc}
  */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  drupal_set_message($this->t('Your email address is @email', array('@email' => $form_state['values']['email'])));
 }
}

```

Can anyone help with a block of code that if the inputs are valid, when the user click download paper button, will be able to download? I got really stuck and i guess my point of view is not helpful to solve this problem.Thank you advanced.

# Answer
> 3 votes
you can do this with the $form\_state-\>response($response)

```
  $response = new BinaryFileResponse($file->getFileUri();
  $form_state->setResponse($response);

```

# Answer
> -1 votes
You could add a redirect to your form, like:

```
$form['#redirect'][] = 'path/to/your/file.ext';

```

> In submitForm the form values are valid !

So validateForm has to set errors to prevent the submission of the form.

---
Tags: forms, 8, theming
---


# Question
Title: How to set up Media module with image editor?
I have installed Media module (7.x-2.0-beta2), but I can't find the module or setting for editing images that is in the video Drupal 7: Media Upload with Image Editing.

I want to set up the Media module for editing images as per this video.

Image editor in the media module

# Answer
Take a look at the article "Crop, rotate, and scale embedded images".

You have to install Media crop module. Some details about this module (from its project page):

> Adds cropping, rotating and scaling to the media module's image embed function. Only available for images local to the server (not for remote images), and only when adding media via CKeditor.
> 1 votes

---
Tags: 7, media, wysiwyg
---


title: Taxonomy Term header image

text:
# Question
Title: Taxonomy Term header image
I created a field for taxonomy terms called "Category Image". I am overriding the taxonomy term pages `/taxonomy/term/%` using views. The only way to add the "Category Image" on top of a page is to add the relationship **Content: Taxonomy terms on node** so I can have the category image field that I produce excluded from display and rewrite it on the header.

The problem with this solution is that I have multiple duplicates on my term page's nodes.

Any solution is appreciated.

# Answer
I think https://www.drupal.org/project/taxonomy\_display has the option to render the term in a certain view mode and then render a view below it. You should check it out.
> 0 votes

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


# Question
Title: How to create a button that creates an article with a specific tag?
I'm administrating a public site and there's some other guys who add content, too. We have a page with articles with a certain tag (let's call it `theTag`) which has an address like `the-site.com/taxonomy/term/41`. Now, since other users are not advanced ones (and for general convenience) I'd like to create a button which:

1. adds an article (opens the `the-site.com/node/add/article` or the corresponding overlay) with pre-set `theTag`
2. also I'd like the "is shown on the main page" flag (not sure about the exact name, it's "Помещено на главную страницу" in Russian) unset, so that the article is show only on the `the-site.com/taxonomy/term/41` page, not on the main one
3. the button should obviously be shown only to those who can edit

How to implement that? It sounds like a common feature, but googling didn't help. Since I'm totally new to Drupal internals, I'd appreciate any partial suggestions if you think I'm asking for too much.

PS may be there's some params that I can use in the `the-site.com/node/add/article` url (like, say, `the-site.com/node/add/article?tag=theTag`) so that the corresponding tag is pre-set in the new article form?

# Answer
> 1 votes
Sounds like the Prepopulate module does exactly what you want.

EDIT: From the module's page:

The Prepopulate module allows fields in most forms to be pre-populated from the $\_REQUEST variable.

For example, the following URL,

```
http://www.example.com/node/add/blog?edit[title]=this is the title

```

will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.

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


# Question
Title: How can I render a view in different languages during queue process, using PHP?
I am putting views into emails using a Drupal 7 queue of user ids.

In the queue, I load the view and attempt to render it after switching `$GLOBALS['language']` to the user's language, and then back.

However, only the first view is rendered with the correct language.

The rest are all English.

```
_switch_language($language);
$view = views_get_view($view_name, TRUE);

if (!is_object($view)) {
  _revert_language();
  return FALSE;
}

if (!empty($display_id)) {
  $view->set_display($display_id);
}

_impersonate_user($account);

$view->pre_execute();
$view->hide_admin_links = TRUE;
$output = $view->display_handler->execute();
$view->post_execute();

_revert_user();
_revert_language();

```

Language switching function:

```
function _switch_language($new_language = NULL) {
  global $language;
  $language_original = &drupal_static(__FUNCTION__);

  if (!isset($new_language)) {
    if (isset($language_original) && (!empty($language_original))) {
      $language = array_pop($language_original);
    }
  }
  else {
    $language_original[] = $language;
    if (is_string($new_language)) {
      $languages = language_list();
      if (isset($languages[$new_language])) {
        $language = $languages[$new_language];
      }
    }
  }

  return $language;
}

```

The user switching function is similar, but calls `drupal_save_session()` twice to disable and re-enable session saving.

Any ideas? Thanks. :-)

# Answer
> 0 votes
I do not yet understand why, but `$view->preview($display_id, $args)` allows the language-switching to work.

It is very similar to my view execution code above, but instead of calling `execute()` on `$view->display_handler`, I call `preview()` and that works as desired.

```
$view->pre_execute();
$view->hide_admin_links = TRUE;
$view->preview = TRUE;
$output = $view->display_handler->preview();
$view->post_execute();

```

I generate the view for each `$user->language` and insert that into the email.

Perhaps this will help someone else.

---
Tags: 7, views
---


title: Ajax call while adding node

text:
# Question
Title: Ajax call while adding node
I have created a content type 'Property', has fields 'Property name','Address line1','Address line2','Address line3'.

I don't want to add duplicate properties in database, so that I want an AJAX call while filling above fields and check is there any property available in database or not with current provided values of fields.

If there is any one result, I want to show it on modal.

The only problem is, Where should I write an AJAX code?, And where will the business logic ?.

Is there any way to do this?. kindly suggest me. thank you.

# Answer
You'll need to use a validation function alongside an ajax call to check for validity, you might want to look at other solutions like How to validate and submit a form using AJAX? to get an idea about how this could be done.

If you are using the Addressfield module (D7) you may find some of these problems are already taken care of, or are easier to solve than with a standard set of input fields.
> 0 votes

---
Tags: nodes, ajax
---


title: Correct way to extended Field Settings

text:
# Question
Title: Correct way to extended Field Settings
I'm doing something that works fine but I get the feeling there is a better way.

I have managed to extend the field settings in the field's manage page to add two new checkboxes. The checkboxes in this case, allow the input form field to be rendered with a Bootstap Add-ON for things like `£` signs via my themes template.php

Adding the checkboxes using `hook_field_widget_form_alter` seems ok (although checking for args is a bit rubbish).

It's the 'wangle' I have to do in `hook_widget_validate` to get the settings to be incorporated in to the other field settings and saved to the database that is a bit nasty.

There must be a nicer way to do it than that so the question is ..

*What is the standard (or better than this) way to extend a field's settings without creating a new widget ?*

For reference, here is my code, firstly the added checkboxes :

```
<?php
/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if (arg(5) == 'fields' || arg(4) == 'fields') {
    if (isset($element['value'])) {
      $name = $context['field']['field_name'];
      // PREPEND.
      $val = 0;
      if (isset($form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['pre_on'])) {
        $val = $form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['pre_on'];
      }
      $element['#element_validate'][] = 'village_widget_validate';
      $element['pre_on']              = array(
        '#title'         => t('Render Prefix as Prepend'),
        '#type'          => 'checkbox',
        '#default_value' => $val,
      );
      // APPEND.
      $val = 0;
      if (isset($form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['app_on'])) {
        $val = $form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['app_on'];
      }
      $element['#element_validate'][] = 'village_widget_validate';
      $element['app_on']              = array(
        '#title'         => t('Render Suffix as Append'),
        '#type'          => 'checkbox',
        '#default_value' => $val,
      );
    }
  }
}
?>

```

The silly 'wangle' in the form validation to get the custom added fields to save as proper field instance settings that can be reteived.

```
<?
/**
 * Form validation handler for village_field_widget_form_alter().
 */
function mymodule_widget_validate($element, &$form_state) {
  if (isset($element['pre_on']['#value'])) {
    $form_state['values']['instance']['settings']['pre_on'] = $element['pre_on']['#value'];
  }
  if (isset($element['app_on']['#value'])) {
    $form_state['values']['instance']['settings']['app_on'] = $element['app_on']['#value'];
  }
}
?>

```

And for completeness here is the counterpart in my template.php that checks for the settings and adds some markup.

```
<?php
/**
 * Implements hook_form_element().
 */
function mytheme_form_element(&$variables) {
  // Default suffix.
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';
  // Check for field settings.
  if(isset($element['#field_name'])){
      if (isset($element['#bundle'])) {
      $field_instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
      if(isset($field_instance['settings']['app_on'])){
        // Our Bootstrapped suffix.
        $addoncls .= 'input-prepend ';
        $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix add-on">' . $element['#field_suffix'] . '</span>' : '';
      }
    }
  }
  // Complied element.
  $output .= '<div class="'.$addoncls.'">' . $prefix . $element['#children'] . $suffix . "</div>";
  return $output;
}
?>

```

The only bit of interest is the recalling via.

```
$field_instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
$field_instance['settings']['app_on'];

```

# Answer
> 0 votes
You can add extra field instance settings as part of you custom module using `hook_form_FORM_ID_alter`, e.g.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function FOO_form_field_ui_field_edit_form_alter(&$form, $form_state, $form_id) {
  $field = $form['#field'];

  // @todo: Consider adding extra condition.

  // Inject setting form element to an instance settings form.
  $form['instance']['settings']['pre_on'] = array(
    '#type' => 'checkbox',
    '#title' => t('Render Prefix as Prepend'),
    '#description' => t('Some description'),
    '#default_value' => isset($form['#instance']['settings']['pre_on']) ? $form['#instance']['settings']['pre_on'] : NULL,
  );
}

```

If you don't want to create new module for a single checkbox, consider adding this hook into your `template.php` file as part of your theme.

---
Tags: 7, entities
---


# Question
Title: How to load a variable through different nodeapi's $op?
I have a registration form on which I ask if user want to participate to a certain program ; if he clicks "yes", then i have a conditional field which requires to upload a picture. There are some problems for validating a picture with drupal, so I decided to create my own validation system.

If the user clicks on "yes" but doesn't upload a picture, then there must be an error message. If the user clicks on "no", the user can't upload a picture (thanks to conditional field).

For that, I've written this under a `hook_nodeapi()` function :

```
        if ($op=='validate'){
        if($node->type == 'profile'){
            // check if the user accepted or not
            if ($node->field_prof_firstflash[0]['value']=="Yes"){
                //check if there's an image loaded
                    if ($node->field_prof_img[0]['filesize'] == 0)
                        form_set_error('field_prof_img', t('Please upload a profile picture.'));
                }
            }
        }
    }

```

**The problem comes when a user wants to edit his settings, later. If the user said "Yes" before but eventually wants to turn it off, my preceding code won't work anymore since `$node->field_prof_firstflash[0]['value']` is still set to "Yes"**. Then, I thought about loading a variable when `$op=='prepare'` like :

```
        if ($op =='prepare'){
        $firstflash = $node->field_prof_firstflash[0]['value'];
        $img=$node->field_prof_img[0]['filesize'];

    }
    if ($op=='validate'){
        if($node->type == 'profile'){
            // check if the user accepted or not
            if ($firstflash=="Yes"){
                //check if there's an image loaded
                    if ($img == 0)
                        form_set_error('field_prof_img', t('Please upload a profile picture.'));
                }
            }
        }
    }

```

But of course (this would have been too simple :-) ), `$firstflash` is not loaded when `$op=='validate'`, even with that piece of code...

Does anyone has any idea on how to do that?

# Answer
> 0 votes
At first sight, it looks like you would be better off implementing hook\_form\_alter, adding a custom validation handler. A form validation handler will give you access to the submitted values in $form\_state as well as the previously stored values.

# Answer
> 0 votes
Include the following code (and adapt it of course) in your own custom module, it works perfectly!

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'profile_node_form' || $form_id =='user_register') {
    //dpm($form);
    $form['#after_build'][] = 'MYMODULE_after_build';

  }
}

function MYMODULE_after_build($form, &$form_state) {

  $form['field_prof_firstflash']['#element_validate'] = array('MYMODULE_validate','optionwidgets_validate','dependent_fields_element_validate');
  dpm($form);

  return $form;

}

function MYMODULE_validate($form, &$form_state) {
  $fs=$form_state['values']['field_prof_firstflash']['value'];
    $img=$form_state['values']['field_prof_img'][0]['filesize'];
  if ($fs == "Yes" && $img==0) {
    form_set_error('field_prof_firstflash', "Alert message !");
  }
}

```

Source: original OP edit.

---
Tags: 6, entities, nodes
---


# Question
Title: Cannot access empty property on entity.inc line 277 when trying to access entity add page
I created a new entity type with hook\_entity\_info using this code:

```
/**
 * Implements hook_entity_info().
 */
function custom_payment_entity_info() {
    return array(
        'custom_payment_period' => array(
            'label' => t('Period'),
            'plural label' => t('Periods'),
            'entity class' => 'Entity',
            'controller class' => 'EntityAPIController',
            'base table' => 'custom_payment_periods',
            'revision table' => 'custom_payment_period_revisions',
            'entity keys' => array(
                'id' => 'pid',
                'revision' => 'pvid',
            ),
            'fieldable' => TRUE,
            'static cache' => FALSE,
            'label callback' => 'entity_class_label',
            'uri callback' => 'entity_class_uri',
            'access callback' => 'custom_payment_access',
            'module' => 'custom_payment',
            'views controller class' => 'EntityDefaultViewsController',
            'admin ui' => array(
                'path' => 'admin/config/custom/custom-payment',
                'file' => '/forms/custom_payment.period.form.inc',
                'controller class' => 'EntityDefaultUIController',
                'menu wildcard' => '%period',
            ),
            'bundles' => array(
                'period' => array(
                    'label' => t('Period'),
                    'admin' => array(
                        'path' => 'admin/config/custom/custom-payment',
                        'access arguments' => array('administrator custom payment periods'),
                    )
                )
            )
        )
    );
}

```

But when i try to create new entity through the admin add page i get this error:

> Fatal error: Cannot access empty property in F:\xampp\htdocs\sfn\sites\all\modules\entity\includes\entity.inc on line 277

This is the form function:

```
function custom_payment_period_form($form, &$form_state, $period = NULL) {
    $form['period'] = array(
        '#type' => 'textfield',
        '#title' => t('Period'),
        '#size' => 5,
        '#required' => TRUE,
        '#element_validate' => array('element_validate_integer_positive'),
        '#default_value' => isset($period->period) ? $period->period : ''
    );
    $form['type'] = array(
        '#type' => 'select',
        '#title' => t('Period Type'),
        '#options' => array(
            1 => t('Day'),
            2 => t('Month'),
            3 => t('Year')
        ),
        '#required' => TRUE,
        '#default_value' => isset($period->type) ? $period->type : ''
    );
    $form['price'] = array(
        '#type' => 'textfield',
        '#title' => t('Price'),
        '#size' => 5,
        '#field_suffix' => t('SYP'),
        '#required' => TRUE,
        '#element_validate' => array('element_validate_integer_positive'),
        '#default_value' => isset($period->price) ? $period->price : ''
    );
    $form['weight'] = array(
        '#type' => 'weight',
        '#title' => t('Position'),
        '#default_value' => isset($period->weight) ? $period->weight : ''
    );
    field_attach_form('period', $period, $form, $form_state);
    $form['actions'] = array(
        '#type' => 'actions',
        'submit' => array(
            '#type' => 'submit',
            '#value' => t('Save')
        )
    );
    return $form;
}

```

Can you help me fix this?

---

It's my first time working with entity type creation i followed the entity API documentation and the video entity example found here github.com/Lullabot/entity-api-demos/tree/master/docroot/sites/… i don't know exactly what is messing here.

# Answer
> 0 votes
Your entity keys don't seem to include bundle, label, or language. - @beth

# Answer
> 0 votes
The problem was in two things:

* I had to add a label entity key to fix this error
* I had to remove the `'menu wildcard' => '%period'` from the admin UI array,

because I got an error on edit page because of it and everything worked then as expected. It seems there was a problem creating an entity type without a "label" entity key.

Source: OP comment.

---
Tags: 7, entities
---


# Question
Title: form with taxonomy autocomplete widget throws error upon submit: Invalid argument supplied for foreach()
I have a custom form with this field in it:

```
$form['first']['field_city'] = array(
    '#title' => t('Woonplaats'),
    '#type' => 'textfield',
    '#size' => 25,
    '#autocomplete_path' => 'taxonomy/autocomplete/field_city',
    '#element_validate' => array('taxonomy_autocomplete_validate'),
    '#required' => TRUE,
);

```

I'm trying to use the autocomplete tagging widget to use with an existing taxonomy vocabulary on this form. It works fine tags are loaded when I start typing but if I submit the form I get the following Warning:

```
Warning: Invalid argument supplied for foreach() in taxonomy_autocomplete_validate()

```

resulting in this error and the wsod (white screen of death)

```
   PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 2:
SELECT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, v.machine_name AS vocabulary_machine_name FROM {taxonomy_term_data} base INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid WHERE (base.name LIKE :db_condition_placeholder_0 ESCAPE '\\') AND (base.vid IN ()) ; Array ( [:db_condition_placeholder_0] => Amsterdam )

```

I think I'm missing something in the form decleration or made a mistake somewhere. So what's wrong with it? Thanks!

some suggestion is that the `machine_name` of the field might be wrong. ( the machine name is actually `stad` when I look in the taxonomy in the admin UI).

# Answer
I'm pretty sure this error will be coming from the following loop in taxonomy\_autocomplete\_validate()

```
 // Collect candidate vocabularies.
    $field = field_widget_field($element, $form_state);
    $vocabularies = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
        $vocabularies[$vocabulary->vid] = $vocabulary;
      }
    }

```

which is collecting the vocabularies allowed for the field, check:

1. Field is set to be a term reference
2. Field has at least one allowed vocabulary set
3. field\_city is the correct machine name of the field in question
> 0 votes

# Answer
It works without validation and also by changing the machine name of the taxonomy field using the UI from `stad` to `field_city`:

```
$voca = taxonomy_vocabulary_machine_name_load('field_city');
$form['first']['field_city'][$voca->vid] = array(
    '#type' => 'textfield',
    '#title' => $voca->name,
    '#required' => TRUE,
    '#field_name' => $voca->machine_name,
    // '#language' => 'nl',
    // '#field_parents' => array($voca->machine_name),
    // '#element_validate' => array('taxonomy_autocomplete_validate'),
    // '#default_value' => 'test_default_value',
    '#autocomplete_path' => 'taxonomy/autocomplete/' . $voca->machine_name,
    '#size' => 25,
);

```

Also removing the `#element_validate` prevents the error from showing, so I guess I'll have to write a custom validation for it to really fix it.

Source: OP edit.
> 0 votes

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


title: How to delete a Feature?

text:
# Question
Title: How to delete a Feature?
I created a feature module in site-1.

Then I instaled the feature module in site-2. This features creates a new content type and enable a module. Then I got the new content type and the module enabled.

So far so good.

Now I disabled and uninstall de feature module(drush). I expected the content type to be deleted and the module to be disabled, I mean the content type and the module that the feature created.

But they are still there...

How do I disable a feature and remove all the things that the feature created?

**UPDATE**: Steps I did to disable the feature:

1) drush dis myFeatureModule

2) drush pm-uninstall myFeatureModule

3) in `admin/structure/features` the feature `myFeatureModule`is **disabled**

4) The delete button for the content type (created by this feature) in `admin/structure/types` is missing...

# Answer
> 2 votes
The first thing you will want to do is disable (and uninstall) the feature module. That doesn't always remove everything the module initially created. Once that feature module is uninstalled however you can go in and manually delete the content type and anything else that was left on the site.

Some additional detail can be found at this other question. It provides an example of how the feature module can add an uninstall hook to unlock the content type. Looking at the query used in that example you should be able to run the query manually and unlock the offending content type.

# Answer
> -3 votes
After you disable your feature, you should be able to go to:

sites \> all \> modules \> custom \> features

Find your module in there and just delete the files.

---
Tags: features
---


# Question
Title: Registering User Programatically with only Email Address
My Drupal 7 site utilizes the email\_registration and logintobbagan modules. It works fine to register users with just their e-mail address. However, on a separate page I am using a newsletter subscribe form called 'news\_subscribe' which is of the following form:

```
function news_subscribe_form($form, &$form_state) {
    $user = $GLOBALS['user']->mail;
    $email = "";
    if(!empty($user))
    {
        $email = $user;
    }
    $form['email'] = array(
        '#type' => 'textfield',
        '#title' => t('E-mail'),
        '#required' => TRUE,
        '#default_value' => $email,
        '#size' => 20,
        '#maxlength' => 20,
        '#element_validate' => array('news_subscribe_email_element_validate'),
    );
    $form['id'] = $id;
    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Subscribe!'),
    );
  return $form;
}

```

By default this then submits the data to the drupal databases and saves the values for the given user if they are already registered in our system via hook\_form\_submit().

```
function news_subscriptions_form_submit($form, &$form_state) {
    //Get the values
    $email = $form_state['values']['email'];
    $id = $form_state['build_info']['args'][0];
    $uid = $GLOBALS['user']->uid;

    //Get the database information
    $collection = variable_get('mongo_user_preferences_collection',DEFAULT_USER_PREFERENCES_COLLECTION);
    $savedarrayname = variable_get('mongo_saved_data_array',DEFAULT_SAVED_DATA_ARRAY);

    //Generate the conditions and queries
    $where = array("uid"=>intval($uid));
    $query = array($savedarrayname=>$id);

    //Insert the data into the datbase
    upsertData($where,$query,$collection,$database=NULL);
}

```

If the user is not currently registered in the system I need to first automatically register them and then retrieve their user id. I know that normally I can use a function such as

```
$new_user = array(
  'name' => 'JohnDoe',
  'mail' => 'john.doe@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
);
user_save(NULL, $new_user);

```

However, I want to integrate it with the current setup which requires just an email address, auto generates a password and then sends a mail to the user with a temporary login link where they can change the password. This is the current setup on the user registration form. I have been looking for a hook into the email\_registration module but cannot find one. Can anyone provide some insight?

Basically I am trying to register a user from a non-registration form (if they are not already registered). I then need to retrieve their assigned uid which is used in subsequent post-processing.

# Answer
In your custom submit function you can do the following,

```
$email_entered = $form_state['values']['email'];

$query = db_select('users', 'u');
$query->fields('u', array('uid'));
$query->condition('u.email', $email_entered);
$row_count = $q->countQuery()->execute()->fetchField();

if ($row_count == 0) {
  // User doesn't exist, Save the user.
  $parts = explode("@", $email_entered);
  $account = new stdClass;
  $account->is_new = TRUE;
  $account->name = $parts[0];
  $account->pass = user_hash_password('bar');
  $account->mail = $email_entered;
  $account->init = $email_entered;
  $account->status = TRUE;
  $account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
  $account->timezone = variable_get('date_default_timezone', '');
  user_save($account);
}
else {
  // User exists.
}

```

As you can see there is no way that you can get the name of the user so you have to use the email as the username. This will be stored in `users.name` field. You also might want to mail the password to the user.
> 2 votes

# Answer
> I need to first automatically register them and then retrieve their user id.

If you change:

```
user_save(NULL, $new_user);

```

to:

```
$user = user_save(NULL, $new_user);

```

you will have the `$user` and can access the created users UID by `$user->uid`.

@PontusNilsson
> 1 votes

---
Tags: 7, users, hooks
---


title: webform email field autocomplete

text:
# Question
Title: webform email field autocomplete
I can quite easily add ajax autocomplete properties to a regular textfield using the code below, but it doesn't work when I change the field to type `webform_email`. Is it possible to do?

```
function flower_order_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_68911') {
        //Add autocomplete fields for manager username
        $form['submitted']['name_of_authorising_manager']['#autocomplete_path'] = 'user/autocomplete';
    }
}

```

Here's the dpr output for the relevant field in the form:

```
Array
(
    [#type] => webform_email
    [#title] => Name of authorising manager:
    [#title_display] => inline
    [#default_value] =>
    [#required] => 1
    [#weight] => 4
    [#description] =>
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => email
                )

        )

    [#element_validate] => Array
        (
            [0] => _webform_validate_email
        )

    [#theme_wrappers] => Array
        (
            [0] => webform_element
        )

    [#translatable] => Array
        (
            [0] => title
            [1] => description
        )

    [#webform_component] => Array
        (
            [nid] => 68911
            [cid] => 18
            [pid] => 0
            [form_key] => name_of_authorising_manager
            [name] => Name of authorising manager:
            [type] => email
            [value] =>
            [extra] => Array
                (
                    [title_display] => inline
                    [private] => 0
                    [disabled] => 0
                    [unique] => 0
                    [width] =>
                    [description] =>
                    [attributes] => Array
                        (
                        )

                    [conditional_component] =>
                    [conditional_operator] => =
                    [conditional_values] =>
                )

            [mandatory] => 1
            [weight] => 4
            [page_num] => 1
        )

    [#webform_private] => 0
    [#validated] => 1
    [#webform_validated] =>
)

```

# Answer
> 2 votes
You can only use type of fields which are defined in `hook_element_info`.

List all the type of elements using drush by:

```
drush ev "print_r(array_keys(module_invoke_all('element_info')));"

```

If you don't need to use Webform email, check the Email field module how it's implementing such element type. See: Usage of email field with the form API.

# Answer
> 0 votes
As far as I can see, Webform module provides it's own form elements for email and some other kinds of data, and it simply does not implement autocomplete for them. You need to either implement `hook_webform_component_info` in your custom module to add this functionality, or fill a feature request on webform's issue queue.

---
Tags: 7, webforms, ajax
---


# Question
Title: Sorting options in an entity reference Select list within a form
When I change the input method for an entity reference field from an Autocomplete widget for a Select widget of an admin-side form, I have noticed there are no sorting options available under "Manage form display" and the Select widget is by default sorted by entity ID.

Is there a way to sort the entities in that Select widget by another field (in my case 'title')? I saw a note about this, but that pertains to drupal 7 (and my entity type is custom and not a node extension).

# Answer
To enable this functionality in Drupal 8,

1. Add a view for your entity type.
2. Create an Entity Reference view display with a field and sort option (See comment from @saramm1 above).
3. Edit the Field Settings for the entity reference field and change the "Reference Type" to use a view.
> 5 votes

---
Tags: forms, 8, entities
---