# Question
Title: Cannot set menu link content field values in *links.menu.yml
I added a field to the `menu_link_content` entity, but am unable to set the value of this field in my `my_module.links.menu.yml`.

Here is my `hook_entity_base_field_info`:

```
/**
 * Implements hook_entity_base_field_info_alter().
 */
function my_module_admin_menu_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() != 'menu_link_content') {
    return;
  }

  // Create the base field definition for the allowed roles. This field will
  // reference user entities.
  $fields['my_module_admin_menu__show_role'] = BaseFieldDefinition::create('entity_reference')
    ->setName('my_module_admin_menu__show_role')
    ->setTargetEntityTypeId('menu_link_content')
    ->setLabel(t('Roles able to see the menu link'))
    ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
    ->setSetting('target_type', 'user_role')
    ->setDisplayOptions('form', [
      'type' => 'options_buttons',
      'weight' => 0,
    ]);
}

```

In my `my_module.links.menu.yml`, I provide a menu link like so:

```
my_module_admin_menu.article:
  title: 'Article'
  menu_name: admin-per-user-role
  url: internal:/node/add/article
  parent: my_module_admin_menu.create
  bundle: menu_link_content
  my_module_admin_menu__show_role:
    settings:
      target_type: user_role
      handler: default
    target_id:
      - authenticated

```

The link shows up, but doesn't show the field:

When a link is added via the menu UI, the field is shown:

# Answer
Menu links discovered in \*.links.menu.yml are not menu link content entities and therefore don't contain the field you have added to the entity. If you want to fill this field with data programmatically, create an instance of the entity:

```
$link = MenuLinkContent::create([
  'title' => 'Article',
  'menu_name' => 'main',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'entity:node/1']],
  'custom_field' => 'custom content',
]);
$link->save();

```

---

The content of \*.links.menu.yml seems a bit odd. The title field is the only required value and you can see that the link is discovered and the title is displayed in the screenshot. The other values are optional. Check the documentation about which values you can use in this file https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links

---

The field seems to be for some kind of access control. You shouldn't do this in the menu link. Instead control the permissions of the target. Menu items are only displayed for users who can access the target.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to enable comments on custom entities
I'm using a contributed module that provides a custom entity. I would like to modify that entity and want to enable comments for this entity.

Does anybody know how to enable commens for custom entities?

# Answer
It's not possible to enable comments for custom entities because the structure of comments is made to comment nodes and not entities.
> 0 votes

# Answer
For Drupal 7, this module should do it - https://www.drupal.org/project/comments\_entity

For Drupal 8, comments are available as a field for any entity type.

Summary:

1. Create a new Entity Type
2. Create a new Bundle for that Entity Type
3. Create a new Comment Type and select your Entity Type
4. "Manage Fields" on your new Bundle and add a new "Comments" field.
5. Configure comments as desired in the field settings.

Wrote a blog post about it here: http://www.daggerhart.com/drupal-8-add-comments-custom-entity-type/
> 2 votes

---
Tags: 7, entities, comments
---


# Question
Title: How To get transaction details in commerce checkout complete page
Can anyone please help to get the transaction details in commerce checkout complete page. I could get using hook\_commerce\_checkout\_complete($order). I can show the success/Error transaction and order details in drupal\_set\_message. But Exactly I need show in checkout complete page instead of message box. Please help how to do. Thank you.

# Answer
In general, for Drupal 7, you could do the following:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function  MODULE_form_commerce_checkout_form_complete_alter(&$form, &$form_state, $form_id) {
  $order_id = $form_state['order']->order_id;
  // Use the entity field query to get transaction entities.
  $query->entityCondition('entity_type', 'commerce_payment_transaction')
    ->propertyCondition('order_id', $order_id);
  $result = $query->execute();
  if (!empty($result) && !empty($result['commerce_payment_transaction'])) {
    // Load the Payment Transactions
    $transactions = commerce_payment_transaction_load_multiple(array_keys($result['commerce_payment_transaction']));
    $form['payment_status']['#markup'] = '<h2>' . t('Payment Pending') . '</h2>';
    foreach ($transactions as $transaction) {
      if ($transaction['status'] == "success") {
        $form['payment_status']['#markup'] = '<h2>' . t('Payment Received!') . '</h2>';
        break;
      }
    }
  }
  else {
    $form['payment_status']['#markup'] = '<h2>' . t('Error. No Payment Transactions.') . '</h2>';
  }
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: When an anonymous user hits '/user/login' route, how can I trigger an event?
I want to trigger an event when an anonymous user comes to /user/login. I made an event subscriber, but it only fires one time:

```
namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class LoginSubscriber.
 *
 * @package Drupal\mymodule\EventSubscriber
 */
class LoginSubscriber implements EventSubscriberInterface {

  /**
   * Redirect the user before we let them access a login form.
   */
  public function onLoginRequest(GetResponseEvent $event) {
    $account= \Drupal::currentUser();

    $config = \Drupal::config('mymodule.settings');
    $base_url = \Drupal::request()->getSchemeAndHttpHost();
    $site_key = $config->get('eweb_site_key');

    switch ($config->get('mode')) {
      case 'test':
        $url = $config->get('eweb_base_test');
        break;

      case 'live':
        $url = $config->get('eweb_base_live');
        break;

      default:
        $url = $config->get('eweb_base_test');
        break;
    }

    // User is accessing login page, check for active session
    if ($event->getRequest()->getRequestUri() == '/user/login' && $account->isAnonymous() && $event->getRequest()->query->get('loginFailed') == FALSE) {
      $response = new TrustedRedirectResponse($url . '/StartPage.aspx?Site=' . $site_key . '&URL_success=' . $base_url . '/user/netforum/{token}&URL_failed=' . $base_url . '/user/login?loginFailed=true');
      return $response->send();
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onLoginRequest'];
    return $events;
  }
}

```

The purpose is that the external site will look to see if this user has an active session, if so, it will redirect back to my site with a token and that controller will handle logging in that user with some logic and `user_login_finalize`.

However, it is currently only firing once.

# Answer
I agree with @Berdir, it shouldn't be a problem if the internal page cache stores a response for each query string.

But the issue here is probably that TrustedRedirectResponse is a cacheable response. When you use such a cacheable response you have to add the correct cache metadata for the content of the response, here a context for the query arg:

```
  if ($event->getRequest()->getRequestUri() == '/user/login' && $account->isAnonymous() && $event->getRequest()->query->get('loginFailed') == FALSE) {

    $response = new TrustedRedirectResponse($url . '/StartPage.aspx?Site=' . $site_key . '&URL_success=' . $base_url . '/user/netforum/{token}&URL_failed=' . $base_url . '/user/login?loginFailed=true');

    $cache_metadata = new CacheableMetadata();
    $cache_metadata->setCacheContexts(['url.query_args:loginFailed']);
    // or set max-age = 0 instead
    // $cache_metadata->setCacheMaxAge(0);
    $response->addCacheableDependency($cache_metadata);

    $event->setResponse($response);

    }
  }

```

Then the dynamic page cache will vary by this context. Or add max-age = 0 to disable the dynamic page cache, because caching won't help here much, this is already cached for anonymous users.
> 1 votes

# Answer
Page cache is a middleware and happens outside of event subscribers.

You could implement that logic in JS for example.

But it's not exactly clear to me why it is even a problem that it is only called once. The internal page cache will cache that for the exact URL and will always return a redirect and not a redirect with the login failed query argument. is that a problem?

Not 100% sure about the dynamic page cache, if that caches the request as well (you can easily see that based on the headers and/or the cache\_dynamic\_page\_cache table), then you need to add a cache context for that query argument.
> 0 votes

---
Tags: 8, routes, event-subscribers
---


# Question
Title: Custom permissions for unpublished content
I'm running in to a problem with my drupal 8 site. I want to give access to unpublished content. I found a solution using a hook.

I want to create a custom module these don't seem to work.

I found this for the unpublished problem: "View unpublished content" permission for non-author

It looks like a solid solutions for my problems but I can't get them to work. I can enable the modules created, and it doesn't give any errors.

My view\_unpub.info.yml file:

```
name: View Unpublished
type: module
description: 'View Unpublished Content'
package: SVDS
core: 8.x

```

My view\_unpub.module file:

```
<?php
function view_unpub_permission()
{
    return array(
        'unconditionally view unpublished content' => array(
            'title' => t('Unconditionally View Unpublished Content'),
            'restrict access' => TRUE
        )
    );
}

function view_unpub_node_access($node, $op, $account)
{
// We're only bothered about the 'view' operation at the moment
    if ($op == 'view') {
// If the user has access to our new permission, let 'em at it
        if (user_access('unconditionally view unpublished content', $account)) {
            return NODE_ACCESS_ALLOW;
        }
    }

// For everything else let the system decide.
    return NODE_ACCESS_IGNORE;
}

```

# Answer
> 3 votes
The code you are showing is not completely ported to Drupal 8. In particular:

As example of `hook_node_access()` implementation, see `node_node_access()`, which also shows what replaces `user_access()` in Drupal 8.

```
function node_node_access(NodeInterface $node, $op, $account) {
  $type = $node->bundle();
  switch ($op) {
    case 'create':
      return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
    case 'update':
      if ($account->hasPermission('edit any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    case 'delete':
      if ($account->hasPermission('delete any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    default:

      // No opinion.
      return AccessResult::neutral();
  }

```

The rest of the code seems fine, to me. Check all the files you are using, and see if they need any change to make your modules work in Drupal 8.

---
Tags: 8, users
---


# Question
Title: change fields in content type after creation
I know you "can't" do this, but hoping there might be a way.. Editing the database directly could work if I knew exactly what needed to be edited. Basically I want to change a `file` type to `image` because as `file`I cannot enforce dimensions (this is on a site that was converted from drupal 6 to drupal 7 and already has a fair bit of data)

# Answer
Have you tried to peek inside a database via PhpMyAdmin ? For every field you have **field\_data\_field** and **field\_revision\_field** table, containing several columns depending on the field type. And also some config tables like **field\_config** and **field\_config\_instance**, so many things to be aware of.

This is more an advice than a clear answer, meddling with database may be risky task.

But I do understand if you have large data collections, you might try to risk to hack database to convert to other field type.

Beware that field tables may be referenced by other tables / modules, so backup your db first and test on clone.
> 2 votes

# Answer
I just wrote some code that should handle this for you in my Helper module: http://cgit.drupalcode.org/helper/tree/lib/FieldChangeHelper.php?h=7.x-1.x

```
FieldChangeHelper::changeType('my_file_field_name', 'image');

```

It should work fine for most simple cases and fields, but should be tested thoroughly. It also currently doesn't update any field formatters, so you'll want to review the display configuration for the field after running this.
> 2 votes

# Answer
More of a pointer than a detailed response but another thing you could do is add a new temporary image field, migrate the data from your existing field into the new field, delete the old field, recreate the old field as an image field, migrate the data from the temporary field to the recreated field, delete the temporary field.

For the migration you could write a simple script to do it, or if you aren't big on coding you could try something like feeds or node\_export (which does importing & exporting). These importing modules will do node updates as well as creation.

I'm sure you can do the change manually in the db as you are asking, you just want to be careful you don't miss something.
> 1 votes

# Answer
I just hack the database and found a table named "field\_config" and modified the "type" and "module" column, from "file" to "image". It worked for me. Hope this could help you.
> 0 votes

# Answer
Manually mirror/clone the content type in the UI with new field machine name and/or options, then use Covert Node module (excellent field mapping) on each node, or possibly with the Views Bulk Operation module. To mirror/clone the content type with a module try Content Type Clone, Field Tools or Bundle Copy. D7.
> 0 votes

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


# Question
Title: How do I programmatically enable a view mode?
Let's say I have created a new view mode with DS. How can I activate it programmatically?

I want to achieve this because I'm doing an export with features but, despite the Features module exports DS settings and layouts, it does not *automagically* activate them. I'm planning to active this new display inside an install hook or something like that.

I looked in the tables schema, but I could not tell what activates a view mode.

# Answer
Use following code to enable view mode programmatically in Drupal 7:

```
module_load_include('inc', 'field_ui', 'field_ui.admin');
$bundle_settings = field_bundle_settings('ENTITY TYPE', 'BUNDLE');
$bundle_settings['view_modes']['VIEW MODE']['custom_settings'] = TRUE;
field_bundle_settings('ENTITY TYPE', 'BUNDLE', $bundle_settings);

```

Replace ENTITY TYPE, BUNDLE, VIEW MODE with your values.
> 1 votes

---
Tags: 7, display-suite
---


title: Alternative theming for subdomain

text:
# Question
Title: Alternative theming for subdomain
I would like a different set of twig templates be used for all content that exists on a sub-domain of a website regardless of content type.

eg:

* mysite.com/article (Main site theme)
* sub.mysite.com/article (New templates)

Is there any way to do this?

# Answer
You could add the domain to the template names in a theme name suggestion hook for each template, but if you want to have a complete set of twig templates for each domain it might be easier to create separate themes and switch them. In custom code with a theme negotiator or with this module Domain Theme Switch.
> 1 votes

---
Tags: theming, 8, subsites
---


# Question
Title: How can I bulk update the language for all content?
I have a site that has been duplicated from an english site and has been translated into Italian.

I installed Italian as a language and have set it as default. However, all of the nodes created in the cloned site are still set to "english".

How can I bulk update the language for all content, either programmatically or directly with SQL?

# Answer
Load the nodes entities and set its langcode column

For example:

```
$w_node = entity_load('node', $nid);
$w_node->set('langcode', $data_langcode);
$w_node->save();

```

To do it in bulk, i guesing that you should create a new action to be available in the defaults bluk operations for the admin/content view
> 0 votes

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


title: Disable bootstrap component

text:
# Question
Title: Disable bootstrap component
If I activate bootstrap theme, it overwrites the breadcrumb behavior of easy\_breadcrumb with its own breadcrumb component. Is it possible to disable the component?

# Answer
> 0 votes
It says here https://www.drupal.org/node/2885165 that "Bootstrap includes a custom breadcrumb module bundled with the theme. You'll need to disable them in your theme settings to use easy breadcrumb."

I also would like know exactly what "Disable Bootstrap custom breadcrumb module" exactly means or how to do that.

---
Tags: theming
---


# Question
Title: How to restore a site from a backup done with Backup and Migrate module using Drush
Just that. I've a backup using the backup and migrate module. I've done some changes and now the site is down. I can't restore the site using the admin interface (because it's broken).

Can I use Drush to restore it?

# Answer
Yes, you can restore your backup with Drush.

Here are Backup and Migrate commands for Drush explained: http://www.only10types.com/2011/03/drush-backup-and-migrate-command.html

I think drush bam-restore command is what you are looking for.

> bam-restore Restore the site's database with Backup and Migrate.
>
> Examples: drush bam-restore db manual "LCC-31.03.2011-14.01.59.mysql.gz" - restore the default database using the given dump file, which can be found in the destination called "manual"
>
> Arguments: source - Required. The id of the source (usually a database) to restore the backup to. Use 'drush bam-sources' to get a list of sources. Defaults to 'db' destination - Required. The id of destination to send the backup file to. Use 'drush bam-destinations' to get a list of destinations. Defaults to 'manual' backup id - Required. The id of a backup file restore. Use 'drush bam-backups' to get a list of available backup files.
> 7 votes

# Answer
I can't comment, but for completeness' sake I'd rather add the official bam-backup command help too.

```
$ drush help bam-backup

Backup the site's database using default settings.

Examples:
 drush bam-backup                          Backup the default database to the manual backup directory using the default settings.
 drush bam-backup db scheduled mysettings  Backup the database to the scheduled directory using a settings profile called "mysettings"
 drush bam-backup files                    Backup the files directory to the manual directory using the default settings. The Backup and Migrate Files module is required for files backups.

Arguments:
 source                                    Optional. The id of the source (usually a database) to backup. Use 'drush bam-sources' to get a list of sources. Defaults to 'db'
 destination                               Optional. The id of destination to send the backup file to. Use 'drush bam-destinations' to get a list of destinations. Defaults to 'manual'
 profile                                   Optional. The id of a settings profile to use. Use 'drush bam-profiles' to get a list of available profiles. Defaults to 'default'

Aliases: bb

```
> 0 votes

---
Tags: drush, backups
---


# Question
Title: EventSubscriber called on specific node type or path
I'm trying to set an event that will launch function that loads some data from outside server and print it to javascript div element. I tried many ways but I can't figure out how to make this event be **called only on for a specific node type**.

Code I got so far:

```
class eSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onRespond',27]; //so far it works on respond but on every page
    return $events;
  }

  public function onRespond(FilterResponseEvent $event) {
    //do some stuff
  }

}

```

# Answer
> 1 votes
I managed to do it but I feel it could be done much better.

```
class eSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::TERMINATE][] = ['onRespond',27];
    return $events;
  }

  public function onRespond(PostResponseEvent $event) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();
    $name = $user->getUsername();

    $output = [];
    if (isset($node) && isset($name)) {

      $nodeType = $node->getType();
      $soap_response = new classThatHandleRequests();
      $output = $soap_response -> get_clients_fv($name);
      echo('<script>var JSONarray = ' . print_r($output,1) . ';</script>');
    }
  }
}

```

---
Tags: 8, event-subscribers
---


# Question
Title: How to call fields individually like this in Twig template?
I'm familiar with the Drupal 8 theming API,as well as all of the theme template suggestions available when Twig debug is enabled. I have created content type named (machine name) events .For overriding node.html.twig I have made node--events.html.twig . In this (node--events.html.twig) file I am trying to get individual values like below: {{content.body}} But it returns null . I have also tried {{ node.field\_machine\_name.value }} but It is not working for all the fields .

# Answer
In my node twig template file I have this which works for me:

```

{{ content.field_name|field_label }}
{{ content.field_name|field_value }}

```

This works if the twig\_field\_value module is enabled.
> 1 votes

---
Tags: theming, 8, nodes
---


# Question
Title: How to mark product if it has already been purchased by current user?
I have Drupal Commerce shop, that sells products that by their nature are *most of the time* not useful to buy twice. Exceptions do exist.

So what I want is to show a field or add a class on products page to mark it in very visible way, if current use has at some point bought this product, ie. if this product can be found in current users order history.

I will also want to show this mark in the product listings.

Lastly, I want to tell you that I do have some experience with templates in drupal, but not that much, especially with commerce. I also have Display Suite installed, if the code field way of doing things would be easier.

# Answer
> 1 votes
This really seems like a perfect fit for the Flag module. Excerpt from its project page (bold markup added here):

> ... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
>
> **Flags may be** per-user, meaning that each user can mark an item individually, or **global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.**
>
> In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

Refer to Flag's Community documentation for (way) more details.

You should configure an appropriate (non-global) flag, which you should then use to (automagically) flag products each time a user buys some product. And next time some products are shown to such user, you use that info about "has this product yes or no been flagged by this user already".

To actually flag such products, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

If you'd want to take this even a step further, you could also consider what is described in the accepted answer to "How to add a custom icon or symbol to a flag link?".

---
Tags: 7, commerce
---


# Question
Title: elements are not in the $form after firing callback, in original module_form function the are and displaying
I don't understand this one. I hope it is not something stupid. When the callback is fired, the form elements that need to be rebuilt are not in the $form anymore. This is quite strange, because they are in original module\_form function and displaying.

The form elements are generated through an extra function, that is iteratively called from the module\_form function. -\> is that a problem?

I have tested this without the nested function and without the iteration and then it works fine. does someone has any idea?

```
        function mymodule_form($form, &$form_state) {
      $url1 = arg(1);
// container with the ajax elements
      $form['container']=array (
            '#prefix' => '<div id="kasten-images-div-images">',
            '#suffix' => '</div>',
            '#type' => 'container',
            '#markup' => '',
            );
//container with the element that fire the ajax callback
      $form['container2']=array (
            '#prefix' => '<div id="kasten-images-div-radios">',
            '#suffix' => '</div>',
            );
//iteration generating the ajax elements
      for ($i=0;$i<$url1;$i++){
            $j = $i +1;
            $exist = array_key_exists('values',$form_state);
            if($exist){
                $type_string = 'type'.$j;
                $test[$i]=empty($form_state['values'][$type_string]);
                } else {$test[$i]=true;}
            if($test[$i]){
                //show default ajax element(image) on load form
                $form = display_closet($j,'6',$form);
            }
            else {
                //show chosen element(image) with ajax
                $choice =$form_state['values'][$type_string];
                $form = display_closet($j,$choice,$form);
            }
        }
//iteration generating the elements that fire the ajax callback
        for ($i=0;$i<$url1;$i++){
            $form = display_form_element($i,$form);
        }
//form submit
      $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => 'Ga naar Stap 4',
      );
      return $form;
    }

function mymodule_form_callback_1($form, $form_state){
    return $form['container']['image-field-1'];
}

function display_closet($j,$choice,$form){
    $image_field_string = 'image-field-'.$j;
    $prefix_string = '<div id="kasten-images-div-'.$j.'">';
    $address ='<img src="http://www.mysite.be/sites/default/files/var'.$choice.'.png">';
    $form['container'][$image_field_string]= array (
        '#type' => 'markup',
        '#markup' => '<div class="my-class-2-image"><p>'.$address.'</p></div>',
        '#weight' => '-10',
        '#prefix' => $prefix_string,
        '#suffix' => '</div>',
        );
        return $form;
}

function display_form_element($i,$form){
    $j = $i +1;
    $name = 'type'.$j;
    $imageOptions = array(
      "1" => '<img src="http://www.mysite.be/sites/default/files/var1_small.png" />',
      "2" => '<img src="http://www.mysite.be/sites/default/files/var2_small.png" />',
    );
    $form['container2'][$name] = array(
        '#type' => 'radios',
        '#options' => $imageOptions,
        '#title' => 'Mymodule Kast '.$j.':',
        '#size' => 12,
        '#maxlength' => 10,
        '#required' => TRUE, //make this field required
        '#attributes' => array('class' => array('my-class-1')),
        '#ajax' => array(
              'callback' => 'mymodule_form_callback_'.$j,
              'wrapper' => 'kasten-images-div-'.$j,
              'method' => 'replace',
              'effect' => 'fade',
              ),
    );
    return $form;
}

```

this is a var\_dump of first container on loading the form, elements image-field-{i} are present:

```
    ["container"]=> array(7)
{ ["#prefix"]=> string(35) ""
["#suffix"]=> string(6) ""
["#type"]=> string(9) "container"
["#markup"]=> string(0) ""
["image-field-1"]=> array(5) { ["#type"]=> string(6) "markup" ["#markup"]=> string(110) "" ["#weight"]=> string(3) "-10" ["#prefix"]=> string(30) "" ["#suffix"]=> string(6) "
    " }
["image-field-2"]=> array(5) { ["#type"]=> string(6) "markup" ["#markup"]=> string(110) "" ["#weight"]=> string(3) "-10" ["#prefix"]=> string(30) "
    " ["#suffix"]=> string(6) "" }
["image-field-3"]=> array(5) { ["#type"]=> string(6) "markup" ["#markup"]=> string(110) "
    " ["#weight"]=> string(3) "-10" ["#prefix"]=> string(30) "
    " ["#suffix"]=> string(6) "
    " } }

```

and this is a var\_dump of the container in the callback-function, the image-field-{i} elements are not there anymore ...

```
["container"]=>
array(17) {
["#prefix"]=>
string(35) ""
["#suffix"]=>
string(6) ""
["#type"]=>
string(9) "container"
["#markup"]=>
string(0) ""
["#theme_wrappers"]=>
array(1) {
[0]=>
string(9) "container"
}
["#process"]=>
array(1) {
[0]=>
string(22) "form_process_container"
}
["#defaults_loaded"]=>
bool(true)
["#tree"]=>
bool(false)
["#parents"]=>
array(1) {
[0]=>
string(9) "container"
}
["#array_parents"]=>
array(1) {
[0]=>
string(9) "container"
}
["#weight"]=>
int(0)
["#processed"]=>
bool(true)
["#required"]=>
bool(false)
["#attributes"]=>
array(0) {
}
["#title_display"]=>
string(6) "before"
["#id"]=>
string(17) "edit-container--2"
["#sorted"]=>
bool(true)
}

```

# Answer
> 0 votes
On both functions, you are returning the entire `$form` variable that will override your initial `$form` build on the beginning of your form, is that normal ?

I think you need to return just the element and assign this value into your form directly on the right key of your `$form` array.

Oy maybe you want to pass your form by reference and add some elements directly. Something is missing for sure.

You can use `dpm()` if you have Devel to show the final `$form` structure.

**EDIT:** well I just saw you were passing the full $form, so it may works, the logic behind it is kinda weird for me. But what I said is not totally correct.

# Answer
> 0 votes
After a lot of debugging I have found the answer, quite stupid but now I know, lies in the second line:

```
$url1 = arg(1);

```

This is ok for the form load, but for the ajax, it does not fly, so this variable doesn't get properly set, therefore all iterations don't work, since this variable is in the for statement for the iterations. I solved it by putting this variable in the $\_SESSION variable.

---
Tags: forms, ajax
---


# Question
Title: How to use a token in "Behavior without results" of a view?
I want to retrieve the ID token of the group in "Behavior without result" of a view. How to do ?

It only offers me (site and view).

The token does not work.

The url does not take ID into account:

/group//join

# Answer
> 0 votes
You have to check the checkbox and then use the token you want **BUT** you have to be careful because you are in the case you do not have any results and the `{{ id }}` will use the first result of your view as said on the description.

So you have to use your contextual filter : `{{ arguments.id }}` and it will work as you want.

---
Tags: views, 8
---


title: Custom wrapper field

text:
# Question
Title: Custom wrapper field
I have a normal field submit:

```
$form['submit'] = [
  '#type' => 'submit',
  '#value' => 'Submit,
];

```

But I wish he had a complex wrapper without using #prefix and #suffix. This wrapper also has to pass variables. What is the easiest way to do it? Creating a tpl.

# Answer
What you are looking for are "theme wrappers" ... this allows you to create a theme function (or tpl) to use to wrap a form element (or any element in a render array).

There is a good write-up here: https://guusvandewal.nl/drupal-blog/theme-wrappers-drupal-forms

Its for drupal 7 but not much has changed with theme wrappers in Drupal 8
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Unable to PhpUnit Test My Custom End Point
When I test my endpoint via POSTMAN, I don't have any problems. When I run my PhpUnitTest I keep getting 404:

```
1) Drupal\my_dashboard\Tests\Functional\MyDashboardResourceTest::testPost
Failed asserting that 404 is identical to 200.

```

rest.resource.snap\_shots\_resource.yml

```
langcode: en
status: true
dependencies:
  module:
    - serialization
    - user
    - my_dashboard
id: snap_shots_resource
plugin_id: snap_shots_resource
granularity: resource
configuration:
  methods:
    - POST
  formats:
    - json
  authentication:
    - cookie

```

SnapShotsResource.php

```
namespace Drupal\my_dashboard\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "snap_shots_resource",
 *   label = @Translation("Snap shots resource"),
 *   uri_paths = {
 *     "canonical" = "/snapshots",
 *     "https://www.drupal.org/link-relations/create" = "/snapshots"
 *   }
 * )
 */
class SnapShotsResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('my_dashboard'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to POST requests.
   *
   * @param array $data
   *   Data array.
   *
   * @return object
   *   Returns ResourceResponse.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function post(array $data = []) {
    $response = ['message' => $data];
    return new ResourceResponse($response);
  }

}

```

Here is my Test class MyDashboardResourceTest:

```
namespace Drupal\my_dashboard\Tests\Functional;

use \Drupal\Tests\rest\Functional\ResourceTestBase;
use Psr\Http\Message\ResponseInterface;
use Drupal\Core\Url;
use GuzzleHttp\RequestOptions;

/**
 * Tests the My Dashboard Resources.
 *
 * @group rest
 */
class MyDashboardResourceTest extends ResourceTestBase {

  /**
   * Modules to install.
   *
   * @var array
   */
  public static $modules = ['hal', 'rest', 'user', 'serialization', 'my_dashboard'];

  public function testPost() {
    $this->initAuthentication();
    $this->setUpAuthorization('POST');

    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = static::$mimeType;
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options[RequestOptions::BODY] = '{}';
    $url = Url::fromUserInput('/snapshots');
    $response = $this->request('POST', $url, $request_options);
    $this->assertSame(200, $response->getStatusCode());
  }

  /**
   * {@inheritdoc}
   */
  protected function setUpAuthorization($method) {
    switch ($method) {
      case 'POST':
        $this->grantPermissionsToTestedRole(['restful post snap_shots_resource']);
        break;
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function getExpectedUnauthorizedAccessMessage($method) {
    switch ($method) {
      case 'POST':
        return "The 'restful post snap shots resource' permission is required.";
      default:
        return parent::getExpectedUnauthorizedAccessMessage($method);
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function getExpectedBcUnauthorizedAccessMessage($method) {
    return "The 'restful " . strtolower($method) . " requires snapshots permission";
  }

  /**
   * {@inheritdoc}
   */
  protected function assertResponseWhenMissingAuthentication(ResponseInterface $response) {
    throw new \LogicException('When testing for anonymous users, authentication cannot be missing.');
  }

  /**
   * {@inheritdoc}
   */
  protected function assertNormalizationEdgeCases($method, Url $url, array $request_options) {

  }

  /**
   * {@inheritdoc}
   */
  protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options) {

  }

}

```

# Answer
I ended up fixing my issue by not using the ResourceTestBase request method but creating the Client myself:

```
$url = Url::fromUserInput('/snapshots');
$url = $url->setAbsolute(TRUE)->toString();

$client = new Client();

$request_options = [];
$request_options[RequestOptions::HEADERS]['Accept'] = static::$mimeType;
$request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
$request_options[RequestOptions::BODY] = $this->getBody();

// Tests good post.
$response = $client->request('POST', $url, $request_options);
$this->assertSame(200, $response->getStatusCode());
$this->assertSession()->statusCodeEquals(200);

```
> 1 votes

---
Tags: 8, testing
---


title: Rules link get url parameters

text:
# Question
Title: Rules link get url parameters
I've got a rule link in a view Rules link generates me this link per user displayed by the view

http://localhost/drupaltest/addequpier/18/14/6OwljLX8KLBfNPrW37bzulzuue25VJmkzWtGiPmR-mc

18 is the user id 14 the node id (i've added this parameter with rewrite url)

How can get those parameters from the url with rules ? Do i have to rewrite the url ?

I'm using Drupal 7

# Answer
> 1 votes
I've resolved my problem finaly, I think there was a conflict with a Disabled module (Rules Forms). I can set the displayed variables under "parameters" in my rule config.

---
Tags: views, rules
---


# Question
Title: How to add pagination after using hook_views_post_execute() to modify $view->result?
I have successfully used `hook_views_post_execute()` to remove results I do not want from `$views->result`.

Now, however, I need to paginate the remaining results.

The code in my `hook_views_post_execute()` requires the full result set to work. If I edit the view in the admin interface and set it to 10 items per page with full pagination, the `$views->result` in `hook_views_post_execute()` will only include 10 items, so my code doesn't function properly.

It looks like I need to use `hook_views_pre_render()` to set up the pagination, but I'm not sure how.

Can someone point me in the right direction?

# Answer
I eventually realized that `hook_views_query_alter()` was the appropriate hook, but it wasn't working because this view utilizes Search API. Turns out `hook_search_api_views_query_alter()` is a hook specifically for altering the query when using Search API.

I used this hook to add a condition to the view query before it is executed. This allowed me to turn pagination back on in the admin panel and have it work as anticipated.

```
function mymodule_search_api_views_query_alter(view &$view, SearchApiViewsQuery &$query) {
  if ($view->name === 'my_view_name') {
    // Do some stuff to get the nids I'd like to allow in my result set.
    $nids = array(1, 2, 3, 4, 5);

    // Add the condition to the existing query.
    $view->query->condition('nid', $nids, 'IN');
  }
}

```
> 1 votes

---
Tags: 7, views, paging
---


title: how to allow Inline css tag?

text:
# Question
Title: how to allow Inline css tag?
I am unable to use inline css in ckeditor wyswig for full html . In Allowed HTML tags i have added but the tag "style" get removed in ckeditor and appears as in finally render of the page .how can i get be rendered.

I am trying to use `<span style="font-size:1.5em; line-height: 1.5em;>Content </span>` but it appears as `<span>Content</span>`.

# Answer
If you have the "Limit allowed HTML tags" checked, it will generate a textarea at the bottom of the configuration of your full\_html profile.

You need to authorize the "style" attribute on the span tag by adding this attribute on the list.

```
<span style>

```

By default, you have for links :

```
<a href hreflang>

```

If you define a new style explained on this documentation it will be added automatically.

**EDIT:** It seems that for XSS reason, style tag are stripped out everytime, see this thread where they talked about that. You have to create styles and define what kind of stuff your end user will be able to add. If you absolutely need your user to be able to add some style directly from code source of your ckeditor, you have to disable the option "Limit allowed HTML tags" but it's not recommended.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Apply images and video responsiveness using incore or contrib drupal8 module?
How can I make the images or videos added to the body or any fields with text format(containing text and images) resized in a responsive fashion?

# Answer
> 1 votes
I love to use the FitVids module for videos to be automatically responsive on your site.

For images, I think you can manage it with CSS `max-width:100%;` for images. I don't know if there is a better method for that.

---
Tags: 8, media, theming
---


title: Proximity filter without Solr

text:
# Question
Title: Proximity filter without Solr
We have a view that displays indexed nodes and we would like to add the ability to filter by proximity to a user-input zip code.

I know this can be achieved with Solr and the Search API Location module (https://www.drupal.org/project/search\_api\_location) but we are not using Solr.

Is there some other way to implement a proximity search on indexed nodes?

# Answer
In order to solve this issue, I combined the results of two views.

1. The Primary View
    * uses the search index and displays indexed nodes
    * has the correct search facet exposed filters
    * can't perform a proximity search (without Solr & Search API Location)
2. The Secondary View
    * uses the node content and displays non-indexed nodes
    * can't use search facets for the exposed filters because the nodes are not indexed
    * can perform a proximity search with just Geofield, GeoPHP, and GeoCoder (all of which we already had installed)

To create the secondary view, I followed the steps outlined here.

Then I used `hook_search_api_views_query_alter()` to alter the query for the primary view. In this hook, I retrieve the secondary view, pass in the zip code from the exposed filter in the primary view, and execute the secondary view to get the results. Then I turn those results into an array of nids.

Finally, I add a condition to the views query to filter out all nodes that do not have an nid from that array.

```
/**
 * Implements hook_search_api_views_query_alter().
 */
function mymodule_search_api_views_query_alter(view &$view, SearchApiViewsQuery &$query) {
  if ($view->name === 'my_primary_view') {

    // Try to get the zip code from the exposed filter.
    $zip_code = NULL;
    if (isset($view->exposed_input['field_geo_latlon'])) {
      $zip_code = $view->exposed_input['field_geo_latlon'];
      unset($view->exposed_raw_input['field_geo_latlon']);
      unset($view->exposed_input['field_geo_latlon']);
      unset($view->exposed_data['field_geo_latlon']);
    }

    // Get the second view, pass in the zip code, get the results.
    $proximity_view = views_get_view('my_secondary_view');
    if (isset($zip_code)) {
      $proximity_view->exposed_input['field_geofield_distance'] = array(
        'distance' => '100',
        'unit' => '3959',
        'origin' => $zip_code,
      );
    }
    $proximity_view->init_display();
    $proximity_view->pre_execute();
    $proximity_view->execute();

    // Turn the results into an array of nids.
    $proximity_nids = array();
    foreach ($proximity_view->result as $proximity_result) {
      $proximity_nids[] = $proximity_result->nid;
    }

    // Add that condition to the view query.
    $view->query->condition('nid', $proximity_nids, 'IN');
  }
}

```

Note: Initially, the dysfunctional zip code filter from the primary view was filtering out all results when a zip code was entered by a user. I needed to keep this field so that users could still enter their zip code, but I did not want the filter to actually be applied.

To get around this, I edited the settings on the exposed zip code filter in the primary view so that when a zip code is provided, it returns all nodes where the zip code is not empty.

This ensures that entering a zip code into the primary view won't change the result set (technically it will remove results without zip codes, but that's ok) but will still allow us to retrieve the value from the input and pass it to the secondary view for the "real" proximity filter.
> 0 votes

---
Tags: 7, location, search
---


title: XML feed in Drupal 7

text:
# Question
Title: XML feed in Drupal 7
I'm using drupal 7 with feeds module.

I've followed this tutorial to try to create nodes with the feed but it didn't work.

Here is the feed : https://cb1-demo-fr-staffing.luceosolutions.com/openrest/requisitions/active Does anyone know why ?

# Answer
You do not have `xpath parser` inside your mapping, which is required for the XML feed you are using, as it is in XML format.

The Xpathparser is a little confusing at first, but basically in your mapping, map all the *XPath parser* values to your values within your Content type you're importing too. Then on `/import` it should be where you assign your XML field values from the feed to said Xpathparser values, AKA your CT fields.

Flush all caches then go back to your parser settings and click **XPath XML parser**.

Inside your mapping your source should be `xpathparser:0` and then you can map it to what field it should go to from your associated CT(set in **Node processor settings**). Do this for ever field from your CT which you want a value coming into.

Then when you go to `/import` there should be a dropdown called `XPATH PARSER SETTINGS` click on that. there will be a context field, give the context field the value of `//requisition`. (Optionally you can set this up on the Feeds settings under the **Xpath XML parser Settings** IF you have already set up your mapping)

The context is where you want the feeds importer to start importing tag data from. You want the context to be `//requisition` so you can grab the tag values from within it. (example job\_id). Then map the XML field in the XML file to said field.

Example: title = `job_id`, and Body = `rendered_job_posting`.
> 2 votes

---
Tags: 7, feeds
---


# Question
Title: How to resolve error Font-awesome library could not be found?
For some reason my Drupal 8 installation is issuing this error after I installed and enabled Fontawesome (via the commerce module).

I don't know

I think this is the dir it is asking me to check, but all seems fine

# Answer
You need to download FontAwesome and move files into the /libraries directory. It is explain in the documentation of the module here

And you had a clear warning message explaining that. You could have read the README.txt
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Is there any way to fetch all users into a list in rules?
I want to know if there is any way to fetch all users into a list in Rules?

I used Views Bulk Operations (VBO) and "Load items from VBO" in Rules. But it seems it doesn't work !!

# Answer
I'm assuming your question is about D7. A possible answer to your question is to use the Views Rules module, as further detailed below.

### 1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

> ... provides two types of elements in Rules, configured with a "Rules" view display:
>
> * **Views loop**: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.
> * **Collect view result rows (action)**: This action collects each variable in all view result rows into list variables for use in Rules.
>
> ***Tip***: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

### 2. Create a view of display type 'Rules'

After you enable the Views Rules module, you can use Views to create a view of those users you want "*to fetch into a list in rules*" (as in your question). Add of view of display type ***`Rules`*** (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

### 3. Create a rule using the view of display type 'Rules'

Create the appropriate Rules Actions in your rule, using these guidelines:

* Use the link that says `Add view loop` to add a Views loop, and select the "Rules" display created in the previous step.
* Configure the parameters and variable names.
* For each user contained in your Views loop, perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the *Rules row variables* as suggested in the previous step, your actual eMail can use tokens such as `[usermail:value]`, `[username:value]`, etc.

***Easy, no?***
> 2 votes

# Answer
If you want to *process the results of a VBO enabled view via Rules*, then typically your rule should include these Rules Actions (in the order specified):

* Load the VBO list of users that you want to be processed.
* Add a loop to perform a Rules Action, 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: rules, views
---


# Question
Title: What is wrong with my custom token to embed entities via token?
Edit: I guess it has something to do with the info part:

```
function mymodule_token_info() {
  $info = array();
  $info['types']['embed'] = array(
    'name' => t('Embed'),
    'description' => t('Embed entities via token.'),
  );
  $info['tokens']['embed'] = array(
    'name' => t('Embed entities using embed:node:nid:viewmode'),
    'description' => t('Embed entities'),
    'dynamic' => TRUE,
  );

  return $info;
}

```

---

I wrote a small module to allow embedding entities, such as nodes, via token:

```
/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'embed') {

    // return $replacements;

    foreach ($tokens as $name => $original) {
      $args = explode(':', $name);

      if (count($args) > 1) {
        $entityType = $args[0];
        $entityId = $args[1];
        $viewMode = isset($args[2]) ? $args[2] : 'full';

        $entity = \Drupal::entityTypeManager()->getStorage($entityType)->load($entityId);
        $viewBuilder = \Drupal::entityTypeManager()->getViewBuilder($entityType);
        $renderable = $viewBuilder->view($entity, $viewMode);

        $replacements[$original] = \Drupal::service('renderer')->render($renderable);
      }

      // @todo: use cache bubbleable_metadata better
    }
  }

  return $replacements;
}

```

The token \[embed:node:1\] actually works fine.

For some reason though, I get the error:

> Fatal error: Cannot use object of type Drupal\Core\StringTranslation\TranslatableMarkup as array in /modules/token/src/Token.php on line 89

when saving any node, sometimes even regular admin pages/ forms. Uninstalling my module fixes the issue.

Is something wrong with how I return the replacements?

Token.php:

```
/**
 * Extracts data from the token data for use in array_multisort().
 *
 * @param array $token_info
 *   List of tokens or token types, each element must have a name key.
 *
 * @return string[]
 *   List of the names keyed by the token key.
 */
protected function prepareMultisort($token_info) {
  $by_name = [];
  foreach ($token_info as $key => $token_info_element) {
    $by_name[$key] = $token_info_element['name'];
  }
  return $by_name;
}

```

# Answer
> 2 votes
See the example : https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21token.api.php/function/hook\_token\_info/8.3.x

Inside tokens there must be 3 levels, tokens\]\[token\_type\]\[token\].

Also tokens don't usually work like that and it will not be possible to validate that token, it is always a token type and that has tokens, which can have a type which then again has tokens. So you'd need to define types for your nested structure.

Not quite sure why you aren't using the entity\_embed project to inject tokens, I assume this is supposed to be used inside a formatted text. https://www.drupal.org/project/entity\_embed

---
Tags: 8, tokens, input-formats
---


title: Use custom token

text:
# Question
Title: Use custom token
I want to use Webform 8.x-5.x in Drupal 8 to create a personal contact form to be used by logged in users to send personal messages to each other.

At the same time I am using the Profile module to store other information for these users, including a Display Name for them.

Now, on the personal contact form I'd like to show the Display Name of the logged-in user in a "From" text field, and the Display Name of the recipient user in a "To" text field.

I know how to display a token as a default value in a text field. However the Token UI shows the global and Webform tokens only.

I also know that I can make my own module and use `hook_token_info()` and `hook_tokens()` to get the Display Name into a token.

But once I have my tokens with the desired information, how do I then get them to show up in the Webform Token UI so that I can use them as default values for my text fields on the form?

To be more precise, the question is, how do I get non-global and non-Webform tokens to show up in the Webform Token UI so that I can use them in Webform?

# Answer
> 2 votes
To add a custom token namespace to the Webform UI, you are going to have to implement HOOK\_preprocess\_token\_tree\_link() and add your custom token namespace to the 'token\_types'.

@see template\_preprocess\_token\_tree\_link() in the token.module.

---
Tags: webforms, tokens
---


# Question
Title: Move, style or remove title in taxonomy template
I would like to remove the title from rendering in the natural taxonomy page template so that I can add it in the teaser and reorder the fields. Currently, the title shows first, and then the other fields in the teaser display. When I view the "Manage Display" for the teaser view mode, the title field is "hidden" and if I show it, it ends up appearing twice. I would like to unhide it, define a specific class reorder the fields.

Can this be done without an added module? I have already played around with taxonomy view but am asking for an alternative that doesn't require using the taxonomy view, which I have disabled for the time being. E.g. If I need to edit the template, which template would it be and what specific way does it need to be edited to remove the title? My site is complex with a bootstrap theme and a sub-theme that I purchased as well as my custom modifications.

See screenshots below for a visual.

Teaser with title hidden

Shows title at the top without defined class

Teaser with title shown and class defined

Shows title twice

I want to make the one at the top go away or show it where the other one is with the proper class.

Bonus: I really want to add author and date information like in the screenshot below to the taxonomy template, which I pulled from my taxonomy view version before I disabled it.

# Answer
> 0 votes
Option one might be to change the template tpl for your taxonomy page. You can also create a new view for your page.

---
Tags: 7
---


title: 8 - Alter HTTP Response Headers

text:
# Question
Title: 8 - Alter HTTP Response Headers
I noticed this question, which discusses various ways to alter HTTP Response Headers.

Where would I be able to execute:

```
$response->headers->remove('X-Frame-Options');

```

I attempted to place this within my THEMENAME.theme file, but perhaps I am not doing it right because `$response` is not defined where I am using it.

Where does `$response` come from?

Where can I execute `$response->headers->remove('X-Frame-Options');`?

Note: I understand the risks of removing the HTTP Header. This is for development/testing purposes only.

# Answer
> 3 votes
Got it!

From these two sources:

I realized that I was missing a `mymodule.info.yml` file.

```
mymodule
  ├── mymodule.info.yml
  ├── mymodule.services.yml
  └── src
    └── EventSubscriber
      └── RemoveXFrameOptionsSubscriber.php

```

Then, go to `/admin/modules` in the backend (Extend tab) and install the new module & clear all caches afterwards.

Woohoo!

---
Tags: theming, 8, http-request
---


title: how to use hook_forms()

text:
# Question
Title: how to use hook_forms()
I'm trying to get multiple forms for a content type at one page

so, I went by hook\_forms($form\_id,$args), but when use it, I receive a not full populated form array

I have

**hook\_menus()**

```
$items['user/%user/administracion/saldos-vacaciones-admin'] = array(
    'type'=>MENU_LOCAL_TASK,
    'title'=>'Saldos admin',
    'page callback'=>'pezgordo_saldos_dias_feriado_form',
    'page arguments' => array(1),
    'access arguments' => array('maneja personas'),
    'file' => 'saldos_dias_feriado_form.inc',
    'file path' => drupal_get_path('module', 'pezgordo').'/includes/user',
);

```

**includes/user/saldos\_dias\_feriado\_form.inc**

```
function pezgordo_saldos_dias_feriado_form($persona=NULL){

$saldos = array_of_nodes();//this is the array of nodes I want their edit forms

$cuenta_forms = 0;
if($saldos){
    foreach($saldos as $ks=>$s){
        //$form_state[$ks]['build_info']['args'] = array($s);

        dpm("$cuenta_forms $ks");

        /*here! if I changes one statemet by the other,
        I can see using A $form[$ks] is an array of 29 elements,
        using B I get an aray of 53 elements, all node related items
        are gone, so form doesn't show at all*/

        //A
        //$form[$ks] = drupal_get_form('saldo_dias_feriado_node_form-'.($cuenta_forms),$s);
        //B
        $form[$ks] = drupal_get_form('saldo_dias_feriado_node_form', $s);

        //dpm($form['$ks]);

        $cuenta_forms++;
    }//fin para cada saldo
}//fin hay saldos

return $form;

}

```

**pezgordo.module**

```
function pezgordo_forms($form_id, $args){
$forms = array();
// Check if the form id is of the pattern add_to_collection_form-[NUMBER]
if(preg_match('/^saldo_dias_feriado_node_form-\d+$/', $form_id)){
    $forms[$form_id]['callback'] = 'saldo_dias_feriado_node_form';
    //$forms[$form_id]['callback arguments'] = $args;
}
dpm($forms);
return $forms;
}

```

**please any help ? thanks**

# Answer
You need to call the forms with a unique ID each time. You can do this:

```
$i = 0;
foreach($saldos as $ks=>$s){
  $form[$ks] = drupal_get_form('saldo_dias_feriado_node_form-' . $i, $s);
  $i++;

```
> 0 votes

---
Tags: forms
---


# Question
Title: Drush suddenly stopped working can't use PM command
Suddenly having errors in drush with aquia dev desktop...it's been working fine for a year at least and now this:

```
C:\aquiasites\fixing\sites\all\modules>drush en color_field -y
Command pm-enable needs a higher bootstrap level to run - you will [error]
need to invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en color_field' could not be executed. [error]

```

Any idea what is happening?

Runnin WIndows 7 64

# Answer
So simple, why nobody saw this including me!.....seems like I can't run Drush from modules directory, only from root, never noticed before, haven't used Drush for a while ...

Not working

```
C:\aquiasites\fixing\sites\all\modules drush en color_field -y

```

Working

```
C:\aquiasites\fixing drush en color_field -y

```

\[solved\]
> 0 votes

---
Tags: drush
---


title: Webform show/hide mandatory fields

text:
# Question
Title: Webform show/hide mandatory fields
I use D8 and I have a webform with multiple fields. One of my fields is a radio button and one other id address (with the fields address 1(mandatory), address 2 (not mandatory), city(mandatory), post code (mandatory) and country(mandatory).

I'm trying to hide the address field using the conditions given in the webform module and I managed to hide them. The problem is that when i try to submit the form while address field is hidden, the submission fails as those fields are mandatory and needs some value.

I added an extra condition that makes the address field 'required' when the value of my radiobutton is 'Yes' but when is triggered makes all the address subfields mandatory.

Check my YAML below:

```
field_address_different_to_s1:
  '#type': radios
  '#title': 'Is address different to organisation address in ‘Section 1'
  '#default_value': 'Yes'
  '#title_display': before
  '#options': yes_no
  '#options_display': two_columns
  '#required': true
  '#access_create_roles':
    - authenticated
  '#access_update_roles':
    - authenticated
  '#access_view_roles':
    - authenticated
address_s3:
  '#type': address
  '#title': Address
  '#default_value':
    address_s3: ''
    address_2_s3: ''
    city_s3: ''
    state_province_s3: ''
    postal_code_s3: ''
    country_s3: ''
  '#states':
    visible:
      ':input[name="field_address_different_to_s1"]':
        value: 'Yes'
    required:
    ':input[name="field_address_different_to_s1"]':
        value: 'Yes'
  '#access_create_roles':
    - authenticated
  '#access_update_roles':
    - authenticated
  '#access_view_roles':
    - authenticated
  '#address__required': true
  '#city__title': City
  '#city__required':
    ':input[name="field_address_different_to_s1"]':
      value: 'Yes'
  '#state_province__access': false
  '#postal_code__title': 'Post Code'
  '#postal_code__required':
    ':input[name="field_address_different_to_s1"]':
      value: 'Yes'
  '#country__type': textfield
  '#country__required':
    ':input[name="field_address_different_to_s1"]':
      value: 'Yes'

```

The #city\__required, #postal\_code\__required and #postal\_code\__required initially were true but I changed them to ':input\[name="field\_address\_different\_to\_s1"\]': value: 'Yes' hoping that will work.

Also I tried to use javascript in order to remove the 'required' class and 'aria-required' attributes from the field and the label but this also didn't work.

Any other idea/ solution please?

Thanks in advance.

# Answer
> 1 votes
I posted a recipe on Drupal.org called How to create an optional different billing address composite element, which contains an working YAML code snippet.

---
Tags: 8, webforms
---


# Question
Title: Is it possible to add or somehow relate a checkfiled to taxonomies?
I am trying to make something with the commerce module and I need to create options for my product and I was thinking making this via a taxonomy, but the options must be clickable (checkboxes) so ... is it possible to change taxonomies to checkboxes? if so, then how?

# Answer
> 1 votes
To change the tag selection for a taxonomy field from autocomplete to check boxes go to the content type or product type and change the widget in the tab *Manage form display*:

---
Tags: 8, commerce, taxonomy-terms
---


# Question
Title: Let users create content by using the default (non-admin) theme
sorry to ask a more conceptual question but I am really stuck.

I have a Drupal 7 site where users will sign in and then create a certain kind of content. I have the content set up ready to go.

Do I just let them have access to the `/node/add/[content-type]` page? If so, how can I theme this page so it has the headers / menus / footers of the rest of the website (and not the standard Drupal 'admin' view)?

I am able to add a custom `node-form.tpl.php` file but when I output the form using `echo drupal_render_children($form);` it still looks like the Drupal admin backend, and not a form that is consistent with the style of the rest of the website. I want it to look more like, say, a webform. Perhaps there a way to insert a `node/add` form into a panels page for example?

I feel like there is a "Drupal way" of doing it, it must be a fairly common use case but it seems my Google fu is failing me. Any help or advice appreciated.

**TLDR**; I want a node/add form to look like a standard website webform and not part of the Drupal admin/backend.

PS: I am using a custom theme and I am comfortable with custom modules.

# Answer
I might misunderstand you, or you did not yet try this. There is a permission `View the administration theme`, which normal users should not have.

This means that if you login as a less privileged user that has permission to `[Content type]: Create new content`, the add content page will look like any other front-end page already:
> 1 votes

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


title: Adding custom field while migrating

text:
# Question
Title: Adding custom field while migrating
I am trying to merging content types while migrating to drupal 8 from drupal 7 and at the same time differentiating them with the taxonomy terms in D8. E.g. The content types from D7 i.e. Article, Page, Blog will merge to a content types called "Media" in D8. But in D8 "Media" content type, there will be a vocabulary "Type of content" with terms as Article, Page and Blog, so that while migrating from D7, the content of Article will be tagged to "Article" term in "Media" content type and same for others.

I am able to merge them to single content type in D8, by giving destination plugin for each content type as -

```
destination:
  plugin: 'entity:node'
  default_bundle: media

```

but not able to figure out how to tagged with "Type of content" vocabulary. This is additional field which is present in D8 but not in D7.

I tried to add

```
$row->setSourceProperty('field_type_of_content', $type_of_content);
$row->setDestinationProperty('field_type_of_content', $type_of_content);

```

code in **hook\_migrate\_prepare\_row()** but not working...

Any suggestion. Thanks in Advance.

Regards Sunil Singh

# Answer
field\_type\_of\_content is presumably a term reference field, so the value to set for it would be a term ID, not a term name. If you know the IDs for the destination terms, you can map them directly:

```
source:
  plugin: d7_node
  node_type: article
process:
  field_type_of_content:
    plugin: default_value
    default_value: 5   # Known D8 ID for the "Article" term

```

More robustly, you can use migrate\_plus's entity\_lookup plugin to translate the term name to a term ID:

```
source:
  plugin: d7_node
  node_type: article
  constants:
    term_name: Article
process:
  field_type_of_content:
    plugin: entity_lookup
    source: constants/term_name
    value_key: name
    entity_type: taxonomy_term
    bundle: type_of_content
    bundle_key: vid

```
> 0 votes

---
Tags: entities, migrations
---


# Question
Title: Product migration with group and execute-dependencies options
I'm migrating from an SQL source in a D8 commerce site. Presently, I'm working on product and inventory data. I have one migration for product variations, one for products, and then 6 additional migrations for inventory tables all in a single migration group. (Inventory data migrations are dependent on the product/variation migrations.) Everything works properly when I run the migrations individually.

However, I have a strange problem when I run `drush migrate-import --group=my_inventory_group --execute-dependencies`. The migration runs fully and reports that everything is OK. I get all the inventory data, products, and variations, but the *commerce\_product\__variations* table gets only a single record added, instead of the 1510 records it should have. That record references the first product item in my source data and one of its variations.

What works for me is executing the product and variation migrations individually, and then the rest of the group.

```
drush migrate-import my_variation_migration
drush migrate-import my_product_migration
drush migrate-import --group=my_inventory_group --execute-dependencies

```

Why can't I execute the migration for the entire migration group with the single command?

# Answer
Perhaps https://www.drupal.org/node/2830357 comes into play here? Apart from that, the usual use of --execute-dependencies is to migrate a single migration making sure any migrations it depends on have been executed, the group scenario hasn't been tested so there may be some broken assumption in the code.
> 1 votes

---
Tags: 8, commerce, migrations
---


# Question
Title: Using Migrate API to select items from within an Events JSON array
I am using the migration import to pull in events from a calendar service json api. I can capture and map almost all the event details except the start date which is contained within an array. I tried to use the extract plugin but can't quite get it to work.

```
"events": [
   {
      "event": {
         "id": 920693,
         "title": "This is the event",
         "url": "http://woodowloriginaldesigns.com/what-lies-beneath/",
         "photo_id": 481020,
         "detail_views": 892,
         "event_instances": [
             {
                 "event_instance": {
                     "id": 2711527,
                     "ranking": 0,
                     "event_id": 920693,
                     "start": "2017-06-28T00:00:00-04:00",
                     "end": null,
                     "all_day": true
                 }
            }
    ],
    "address": "124 Main Street USA",
    }
  }

```

I am trying to get the `"start"` date out of there. The process section for my yaml file for the start date currently looks like this:

```
field_importdate:
  plugin: extract
  source: event_instances
  index:
    - 0
    - event_instance
    - start

```

When I omit this, I can successfully pull in/map all the other fields with a `drush migrate-import jobnamehere` command.

* How should my extract plugin be configured here to get the start date?

Happy to provide more details and entirety of yaml file if needed.

# Answer
> 0 votes
Have you tried mapping directly rather than using extract?

```
field_importdate: event_instances/0/event_instance/start

```

---
Tags: migrations, 8
---


# Question
Title: Migrate source id's and map them to already existing Drupal entity id's
I've tried a bunch of different setups, but I can't get it to work. Here are the two setups I was the most confident in that it would work. I simply want to map existing id's in the source to new id's that are already created in taxonomy.

Attempt 1:

```
  field_season:
    # Map the seasons to our already existing taxonomy terms
    -
      plugin: static_map
      source: season
      map:
        '1': 26 # Lente
        '2': 29 # Zomer
        '3': 24 # Herfst
        '4': 28 # Winter
    -
      plugin: entity_lookup
      value_key: tid
      entity_type: taxonomy_term
      bundle_key: tid
      bundle: seasons

```

Attempt 2:

```
  field_season:
    plugin: iterator
    source: field_season
    process:
      target_id:
        # Map the seasons to our already existing taxonomy terms
        plugin: static_map
        source: season
        map:
          '1': 26 # Lente
          '2': 29 # Zomer
          '3': 24 # Herfst
          '4': 28 # Winter

```

Edit: FWIW, all the other processes work just fine!

# Answer
This happens to me all the time, I post a question after fiddling around for hours and shortly after, I manage to find the answer myself. It appears that the first attempt was almost right. Though `bundle_key` should be `vid`, I'm not sure why though.

The config, for completeness sake.

```
  field_season:
    # Map the seasons to our already existing taxonomy terms
    -
      plugin: static_map
      source: season
      map:
        '1': 26 # Lente
        '2': 29 # Zomer
        '3': 24 # Herfst
        '4': 28 # Winter
    -
      plugin: entity_lookup
      value_key: tid
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: seasons

```
> 0 votes

# Answer
The entity\_lookup doesn't appear to be doing anything here - it's retrieving D8 terms by their tid, and returning their tid. The static\_map alone should do it if you know the mappings from the original tids to the new D8 tids.
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: Migrate a CSV into two entities with reference
I have a CSV as below:

```
chapter, headings, sentences
1, heading one, "1,2,3,4,5,6,7"
2, heading two, "1,2,3,4,5"
2, heading three, "6,7,8"

```

I want to migrate it to Drupal. The heading columns have to be migrated to the taxonomy heading. Once a heading is added, it should loop through the value in sentences and update the sentence entity by adding a reference to it.

The entity to be updated should be loaded matching the sentence column and chapter column. The sentences entity is already pre-populated with data.

**Fields in each entity:**

```
Taxonomy:
heading(string)

Entity(sentences):
sentence_no(int)
heading_reference(entity_reference)
sentence(string)
chapter_no(entity_reference)

```

I tried this tutorial. While the link is straight forward it doesn't really help my need.

I am ok if I migrate to D7 or D8. However D8 is preferred.

# Answer
> 1 votes
It's fundamental to how the migration process works that it processes one item being written at a time. In this case, since it's sentence entities that are being updated, it needs a migration that processes one sentence at a time. The layout of your CSV here is not well-suited for that, and to work directly from that CSV would require significant hackery. The best approach would be to either generate your CSV in this format in the first place, or have a preprocessing step to put the data in this form:

```
chapter,sentence,headings
1,1,heading one
1,2,heading one
1,3,heading one
1,4,heading one
1,5,heading one
1,6,heading one
1,7,heading one
2,1,heading two
2,2,heading two
2,3,heading two
2,4,heading two
2,5,heading two
2,6,heading three
2,7,heading three
2,8,heading three

```

Then, you'd have a migration with source IDs chapter and sentence, setting the heading for each sentence from the headings column.

---
Tags: migrations, importing-exporting
---


# Question
Title: How do I add a custom html.node--.html.twig based on content-type?
I want to override the default html.html.twig according to my custom content-type. But I only get suggestions like:

```
* html--node--16.html.twig
* html--node--%.html.twig
* html--node.html.twig
x html.html.twig

```

I have tried for file-name

```
html--node--content-type.html.twig

```

But this was not successful. Can anybody help?

# Answer
> 5 votes
You can use `hook_theme_suggestions_HOOK_alter()` to add another suggestion, something like:

```
function THEME_theme_suggestions_html_alter(&$suggestions, $variables) {
    // Check it's a node page.
    if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
        // Insert as second to last so the more specific template by ID still works.
        array_splice($suggestions, count($suggestions) - 1, 0, 'html__node__' . $node->getType());
    }
}

```

---
Tags: theming, 8
---


title: How to reset specific form elements

text:
# Question
Title: How to reset specific form elements
I have a form which I have included a reset button. Here is the code:

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

  ...code here...

  $form['filter']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('submission_list_reset'),
  );

  ... more code ...
}

function submission_list_reset($form, &$form_state) {

  if (isset($form_state['etd_filter'])) {
    unset($form_state['etd_filter']);
    $form_state['values']['filter_user'] = '';
    $form_state['input']['filter_user'] = '';
  }
  $form_state['rebuild'] = TRUE;
}

```

I thought what I have in the submission\_list\_reset function is correct but it still displays whatever the user typed in the filter\_user text field. I have tried clearing the values and input array with no success so I must be missing something really basic here. I have searched Drupal Answers and Google but have not found an answer. The answers I have found on Drupal Answers is about adding a reset button but not about clearing specific fields.

Thanks.

# Answer
> 2 votes
You can attach the reset function in this way:

```
function submission_list($form, &$form_state){
  $form = array();
  $form['name'] = array(
    '#title' => 'Name',
    '#type' => 'textfield',
  );
  $form['surname'] = array(
    '#title' => 'Surname',
    '#type' => 'textfield',
  );
  $form['actions'] = array(
    '#type' => 'actions',
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#attributes' => array(
        'class' => array('my-submit-button-class')
      ),
      '#submit' => array('your_submit_function')
    ),
    'reset' => array(
      '#type' => 'submit',
      '#attributes' => array('class' => array('my-reset-button-class')),
      '#value' => t('Reset form'),
      '#submit' => array('submission_list_reset')
    )
  );
  return $form;
}

function submission_list_reset($form, &$form_state) {
  $form_state['values']['name'] = '';
  $form_state['values']['surname'] = '';
}

function your_submit_function($form, &$form_state) {
  drupal_set_message('The form has been submitted');
}

```

But please consider to use ajax callback for this reset function, it would be better do not reloading the page only because of resetting. More info - Ajax forms in Drupal 7

# Answer
> 1 votes
Please use the right way `form_set_value()` in your validation function instead of `$form_state['values']['surname']`

Like this:

```
form_set_value($form['surname'], '', $form_state);

```

---

Update:

Please make sure to reference the $form\_state and $form to the same variable in memory by making sure there is `&` sign before the parameters like this:

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

```

---
Tags: 7, forms
---


# Question
Title: Adding new Vocabulary after node being Updated
I tried to add new vocabulary After Add/create a node for certain type..'`account`'

```
if ($node->type == 'account') {
  $nid   = $node->nid;
  $title = $node->title;
  $voc_title  = 'branches_' .$nid;
  $vocabulary = taxonomy_vocabulary_machine_name_load($title);

 if (!is_object($vocabulary)) {
   $vocabulary = new stdClass();
   $vocabulary->name = $title;
   $vocabulary->machine_name = $voc_title;
   taxonomy_vocabulary_save($vocabulary);
   node_save($account);
  }
}

```

How to add Vocabulary when Add/create a node?

# Answer
> 0 votes
I assume you are using the right hook, but you have some mistakes in your code.

In order to get the node title, you just need to do `$title = $node->title;`, the `node_load()` function expects a node ID, and not a title.

I don't understand where the `$nid` variable comes from. If you want the node ID, you need to do `$nid = $node->nid;`

The taxonomy\_vocabulary\_machine\_name\_load() function will return FALSE if it can't the vocabulary, so you can use `if (!$vocabulary) {}`

Finally, you don't need to save your node at the end, because you are not changing anything on it.

**Final code**

```
if ($node->type == 'account') {
  // Don't know if you already have the full $node on the hook you are using
  $account = node_load($node->nid);

  $title = $node->title;
  $name = 'branches_' . $node->nid;

  $vocabulary = taxonomy_vocabulary_machine_name_load($name);
  if (!$vocabulary) {
    $vocabulary = new stdClass();
    $vocabulary->name = $title;
    $vocabulary->machine_name = $name;
    taxonomy_vocabulary_save($vocabulary);
  }
}

```

**EDIT:** Well, I just see your answer, I clearly don't understand why you have a "field\_account" on your node because your are calling your node `$account` ?

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


# Question
Title: Add permission to taxonomy programmatically
I used `hook_user_save()` to create new vocabulary each time user being created/Added.

The question is How to add user Permission for new Vocabulary?

# Answer
By default, Drupal comes with a single permission to administer vocabularies, so if you want your new user to be able to access only the new created vocabulary, you should take a look at the module Vocabulary Permissions Per Role. I never used it, but it sounds to fit your needs.

You'll need to explore how it handles the new permission and configure the module each time you create a new vocabulary.
> 0 votes

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


# Question
Title: How to validate file is selected or not on ajax processed jquery validation
I am trying to do jquery validation on file upload for file is select or not. I want when user click on upload before submit check file is selected or not. if not stop ajax request. Any Idea to validate it?

```
$videoForm['profile_photos']['images']['field_photo'] = array(
    '#parents' => array('video', 'field_photo'),
    '#id' => 'field_photo',
    '#type' => 'managed_file',
    '#title' => 'Photo <em>(optional)</em>',
    '#field_name' => 'field_photo',
    '#process' => array(
    'm_customer_profile_image_remove',
    'm_customer_profile_image_upload',
    'file_managed_file_process',
        'customer_profile_image_preview',
    ),
    '#upload_location' => 'public://' . $user->uid,
    '#limit_validation_errors' => array(array('video', 'field_photo')),
    '#upload_validators' => array(
        'file_validate_size' => array(64*1024*1024),
        'file_validate_extensions' => array('gif jpeg jpg png')
    )
);

```

# Answer
What are you using for the file upload element? Is this in a form, webform etc.? With the Form API managed\_file should do what you want.
> 0 votes

# Answer
It's Working Example:

```
function yourModuleName_form_alter(&$form, &$form_state, $form_id)
{
   if($form_id == "test_node_form")
  {
    $form['field_file']['und'][0]['#process'][] = 'process_test_file';
  }
}

function process_test_file($element, &$form_state, $form)
{
   $element = file_managed_file_process($element, $form_state, $form);
   $element['upload_button']['#submit'][] = 'validateCustomFile';
   return $element;
 }
function validateCustomFile($form,$form_state)
{
  if($form_state['values']['field_file']['und'][0]['fid'] <= 0)
  {
    form_set_error('field_file', t('Please Select At Least One File.'));
  }
}

```
> 0 votes

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


# Question
Title: How can I create my desired template name suggestion?
For example, Imagine that I designed two `main-menu` with different style and template one for the header region (top bar, primary menu section) and another for the footer region as a "footer map" on my site as it's common in the most sites.

Since Drupal 8 it's not possible with template naming conventions to load a specific block template according to the region it is placed in ("Per-region block markup and per-region block templating feature removed").

> In Drupal 7 it was possible to specify separate block templates per region, such as block--header.tpl.php and block--footer.php to output different HTML for blocks placed in the header and footer regions. It was also possible to adjust variables based on the region in hook\_preprocess\_block(). Both of these features have been removed.

I decide to use below code, by using the below code I can add block region and id to the block template name suggestion:

```
function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    $suggestions[] = 'block__' . $block->getRegion() . '__' . $variables['elements']['#id'];
  }

```

If I have considered tree or even more footer region in my theme then my theme users should have this freedom to change the order of displaying this designed footer menu independent of which sub-footer region that's inserted in;
It is more useful if we design in LTR languages (Like English) and RTL languages(Like Persian)Simultaneously.
But what's that become outputted from above code is something like this:
`block--footer-1--mainnavigation-2.html.twig`

I think it's a good idea to design the different menu with different semantic name template separately. It's quite obvious if I need multi instances of a block then Its must probably be in different region, therefore, this difference in positioning make a good and sufficient semantic name convention to assign name to templates and get rid of complication.

for this reason, I want to remove the numbers from the end of block identifier because I think this is very dedicated and I want to achieve something like this:

`block--footer--mainnavigation.html.twig`

Something else that I want to pay attention to it is if I choose another footer names for example: `footer_menue` instead of `footer_1` then this hasn't necessary dynamics in theme layer due to the above reasons.

Anyway, the name convention that I like and follow out is:
What's this?(Most common part) it's block or page or....
Where should be placed? header, footer....
What is his name or usage? main-menu, Search Block,...
Like:`Block`+`Region Name without Number`\+ `Block(id) name without number`

# Answer
If you want to have more meaningful template suggestions, why don't you use better region names and block ids?

Region names are up to your theme, so instead of footer\_1, use footer\_something, and block configuration names are also up to how you configure/name your blocks.

You could use PHP to filter those things out, that's nothing really drupal specific, but that's likely increasingly complicated as you will have blocks and regions without those number suffixes, so you need to be caruful in not cutting those off.

Also, you could use suggestions based on the block plugin ID, not configuration ID, then placing the same menu multiple times will give you the same template suggestion.

Edit: If you really want to get rid of those kind of suffixes, then you could for example use trim:

```
rtrim('footer_1', '123_');

```

You can put whatever characters in there that you want, and it will remove them all from the right side of the string (there is also ltrim for left and just trim for both sides). Note that this will also remove a _ at the end if you have that.
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: How to disable context from URL in Views
I use D7. I have a view which I want to show only current user. Those fields, in the view, are related to the current user via relationship of Profile. So, I can also say that the current user can view their own profile's fields.

So, I set 'User: Uid' as 'User ID from logged in user' on contextual filer. But, if I write non-current user's uid after page's path(Let's say '/test-user') like '/test-user/100', it outputs that user's(uid=100) fields.Even if I set 'global $user; return $user-\>uid;' with PHP Code for User: Uid instead, I got the same result.

For some reason, with Field Permission module, I set those fields as 'View anyone's value for field\_name'. So, I have to control the visibility in this view somehow.

Can anybody give me some advice? Thank you.

# Answer
Found the solution. Actually this doesn't disable a context from URL. But it worked for my demand.

Click 'add' under Filter criteria. -\>Select 'User: Current'. -\>Select 'Is the logged in user' as 'Yes'.

That's all.
> 0 votes

---
Tags: views
---


# Question
Title: How to choose appropriate token for URL path alias pattern display in URL?
Using Drupal 7 + PathAuto + Token + Entity API

Having a really hard time setting url aliases...for nice URLs. I have it set up like this:

```
[node:field-root:parents]/[node:field-root:name]/[node:title]

```

But it's not what I want, I want every term displayed separately in the URL, now it's like this:

```
 ab/c/d/item

```

but I want:

```
 a/b/c/d/item

```

What token should I use to get this done, tried tons of combinations and can't get it working...

I see the explanations besides the token, but still, it's too complex and I can't wrap my head around this to get it working.

I saw a page that asks users to share their pattern recipes (https://www.drupal.org/node/124462), but there is nothing in there...if I could see a list of patterns and then resulting ULR it would be great.

Otherwise, how do I know what token to choose?

Picture below is hierarchy, the URL I want is:

```
 mysite . com /destinations/northern-laos/outodmxay/history

```

# Answer
This is the answer:

```
 [node:field-category:parents:join-path]/[node:field-category]/[node:title]

```
> 0 votes

---
Tags: path-aliases, tokens
---


# Question
Title: Custom submit handler: how to create node?
I created a form\_node\_alter for a content type called "banner" and I made a custom submit handler named "mymodule\_check\_submit\_handler()". Everything is ok, I can do what I want in the submit handler function but I don't know how to create the node of type "banner" once I executed my custom code.

Searching for a solution I found this code:

```
$values = $form_state->getValues();
$node = entity_create('node', $values);
$node->save();

```

But now I got this error: Error: Call to a member function getValues() on array in mymodule\_check\_submit\_handler()

How can I create the node in my custom submit handler?

# Answer
> 0 votes
After some searches I post the solution to myself!

This is the right code to use:

```
$values = $form_state['values'];
$node = entity_create('node', $values);
$node = node_submit($node); // Prepare node for saving
node_save($node);

```

---
Tags: forms
---


title: Printing PHP to node

text:
# Question
Title: Printing PHP to node
I got hook in my \*.modules file `php_invoke_preprocess_node` that should print data from JSON according to node type. I need to print it to node content everytime i run it but now it runs only once and print it at the top of the site and then it won't run until I clear cache.

```
function php_invoke_preprocess_node(&$variables) {
$node = $variables['elements']['#node'];
//check content type
switch($node->getType()) {
  case 'nodeType':
    $session = getSession('','');
    $data = ['additonal JSON headers'];
    echo (CallAPI($data, $session)); //return JSON array that i want to print to node but i dont know how
  break;

```

# Answer
That was a hell of a problem to solve. I had to rebuild my code. Instead of hooks I took a bit different approach and I tried a solution proposed by @IvanJaros but I wasn't able to get lazy builders to work. I found that in drupal 7 there was a `hook_init` that was called everytime but it got *deprecated* in `8`.
The answers are EventSubscribers, using them you can assign any function you want to specific event i.e. loading a page.
Here's a great tutorial that intruduce you to that feature.

**Here's my event code**

```
    class MyEventSubscriber implements EventSubscriberInterface{

        public static function getSubscribedEvents(){
        // Its called when respond transfer ended
        $events[KernelEvents::TERMINATE][] = ['onRespond',28];
        return $events;
    }

  public function onRespond(FilterResponseEvent $event){
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();
    $name = $user->getUsername();

    $data = [];
    if(isset($node)&&isset($name)){
        $nodeType = $node->getType();
        switch($nodeType){
            case 'nodeType':
                $soap_response = new JSonGetter();
                $data = $soap_response -> getUserData($name);
                echo('<script>var JSONarray = ' . print_r($faktury,1) . ';</script>');
                break;
        }

    }
    }

}

```
> 0 votes

---
Tags: 8
---


title: Force a session to become HTTPS?

text:
# Question
Title: Force a session to become HTTPS?
I'm working with a very complex legacy D7 site, and very complex requirements (bleaugh).

Anyway: I'm working on a deeplinking system that allows a jump to the site, which then logs-in a user (this is based on an encrypted ID), does some other stuff like setting up cookies, and then jumps to the required page.

This is fine, except some of them are HTTP pages, which work, and some are HTTPS, which don't.

What happens is that when it arrives on the required page there is no logged-in user (so "Access Denied"). But if I then go to an HTTP page (like the front page), the user *is* logged in.

So clearly I need to set up the HTTPS session data before jumping to the required page. I've been through the Drupal session code but I can't figure it out.

I need to set the SSESSPHPID cookie and possibly some other stuff - but what and what's right? Any help would be appreciated.

# Answer
> 0 votes
Long story short: It wasn't Drupal. We have the Brocade Traffic management stuff running above the site (and on local sites too so the dev environment is as close to live as possible).

The HTTP/HTTPS switching in that was causing the problem. After working with it for so long I should have checked it. Such is the life of a professional developer.

---
Tags: 7, users, sessions, cookies
---