# Question
Title: How to prevent users from updating "featurized" settings via the GUI?
We have some configuration pages where it is useful for privileged users to be able to see settings that have been exported as part of a feature, but there is no indication on the admin page that those settings have been "featurized." This has resulted multiple times in users changing settings only to realize weeks or months later that the change they had made was inadvertently overwritten during a subsequent code deployment (during the feature revert step).

How can we prevent privileged users from updating a setting in the GUI that have already been exported as part of a feature?

# Answer
> 0 votes
> How can we prevent privileged users from updating a setting in the GUI that have already been exported as part of a feature?

TL;DR: You can't.

Support for that depends on the module's admin implementation. Some modules indicate that the config is overridden by the DB, others do not. Some modules replace the delete with a disable, some do not. Some indicate that the config is from the DB or code, some do not.

What you could do:

* Restrict access to those sections. For instance, it's good to disable `views_ui`, `field_ui` and `context_ui` to prevent "privileged users" to futz around with these settings.
* Assign those users to roles that have more restrictive permissions. Besides, what's the purpose of having them see if they can't/shouldn't do anything with it?
* Tell your users about the possibility of these settings being wiped out and reason with them why.
* Modules are open-source. You can contribute a patch to these modules to add this functionality.

---
Tags: features, configuration, deployment
---


title: Add an entity reference to a user

text:
# Question
Title: Add an entity reference to a user
I'm attempting to programmatically create test users in Drupal 8 via `hook_update_n()`. I have an array of user attributes I'm using to create users.

I've got three fields added to the User entity that add term references to existing vocabularies that have been populated with terms. Two of these fields store a single term reference, while the third can store multiple term references.

I've retrieved the term object using this code.

```
    $term = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->loadByProperties(['name' => $user['bu'], 'vid' =>
    'tx_business_unit']);

```

I'm trying to add a term reference to my user field, called "user\_bu".

I've attempted to use the solution given on Programmatically update an entity reference field, but it doesn't work for me.

Everything else on my user record is being populated without issue.

# Answer
> 0 votes
For those of you who may be looking to answer the same question, here's how I got it to work in my case (I'm working on a Drupal 8.3 site):

```
$users = [
  'test_local_contributor' => [
    'password' => '1testme1',
    'langcode' => $language,
    'preferred_langcode' => $language,
    'email' => 'test_local_contributor@example.com',
    'roles' => [
      'employee',
      'local_contributor',
      'testuser',
    ],
    'location' => [
      'Kentucky',
      'Paradise',
    ],
    'sbu' => 'energy',
    'bu' => 'natural_gas',
  ],
  ...(there were other test users, omitted for brevity)
];

foreach ($users as $key => $user) {
  $newUser = User::create();
  $newUser->setUsername($key);
  $newUser->setPassword($user['password']);
  $newUser->enforceIsNew();
  $newUser->setEmail($user['email']);
  $newUser->set('langcode', $user['langcode']);
  $newUser->set('preferred_langcode', $user['langcode']);
  foreach ($user['roles'] as $role) {
    $newUser->addRole($role);
  }
  $newUser->set('status', 1);

  if (isset($user['bu'])) {
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $user['bu'], 'vid' => 'tx_business_unit']);
    $keys = array_keys($term);
    $newUser->set('user_bu', $keys);
  }

  if (isset($user['sbu'])) {
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $user['sbu'], 'vid' => 'tx_sbu']);
    $keys = array_keys($term);
    $newUser->set('user_sbu', $keys);
  }

  $loc_keys = array();
  foreach ($user['location'] as $location) {
    $newkeys = array();
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $location, 'vid' => 'tx_user_location']);
    $keys = array_keys($term);
    $newkeys = array_merge($loc_keys, $keys);
    $loc_keys = $newkeys;
  }
  $newUser->set('user_location', $loc_keys);

  $result = $newUser->save();
}

```

---
Tags: entities
---


# Question
Title: How do I say to Twig where to look for the template files?
I want to add another path where the templates are stored. In standard PHP I'd use `$loader->addPath('../path/to/templates')`. I found `Twig_Loader_Filesystem::addPath()`, but I have no clue where and how to use it.

Is there any hook?

# Answer
What you found is the class used from Twig to load the template files from the file system, but what Drupal uses is its own class derived from that, `Drupal\Core\Template\Loader\FileSystemLoader`, which is the default class implementing the twig.loader.filesystem service. Its only purpose is adding a namespace for each theme and module enabled from a Drupal site, so that is possible to reference a template file as @block/block.html.twig.

For how I understand it, replacing the class implementing that service with a class derived from the default implementation, you could be able to reference a template in a different directory with, for example, @external\_directory/template.html.twig.

See `FilesystemLoader::__construct()` for how Drupal adds new namespaces, and Altering existing services, providing dynamic services for how to alter that service to use a different class.
> 0 votes

---
Tags: theming
---


title: Render custom html below a custom form

text:
# Question
Title: Render custom html below a custom form
I am new to drupal, I am using drupal 8, I have develop a custom form by extending FormBase controller and i am trying to render it using a custom controller like below.

```
$form = $this->formBuilder->getForm('Drupal\xyz\Forms\XyzActionsForm',$parameter);

return [
  '#form'=>$form
]

```

This works fine form me. But now i also want custom html below this form so try below code

```
$form = $this->formBuilder->getForm('Drupal\xyz\Forms\XyzActionsForm',$parameter);

$form = render(form);

$form .= '<div>custom html </div>';

return [
  '#markup'=>$form
]

```

But this didn't work for me, Can anyone let me know how to achieve this.

# Answer
You have to use the power of render arrays.

For your example, I would use something like that :

```
$form_class = 'Drupal\xyz\Forms\XyzActionsForm';
$form = [
  'form' => $this->formBuilder->getForm($form_class, $parameter),
  'custom' => [
    '#type' => 'container',
    'inside' => [
      '#markup' => 'custom html', // Or use the power of render with html_tag type
    ],
  ],
];

return $form;

```

Then you can manage cache and other stuff on your render array and build your response with it.
> 4 votes

---
Tags: theming, 8, forms, page-controller
---


# Question
Title: Using cache for twig variables in preprocess function
I implement a menu on a region using a preprocess function to get a link with an anchor for each block of it with a title. I made a preprocess function for region, in my theme, where I test the region machine name.

I first used the $variables\['elements'\]\[XXX\]\['#id'\] to load each block, to find out if the label was set to be display. But I quickly discover that on my server, where the cache is on, the $variables\['elements'\] only contain an array of cached render.

I then modify my preprocess hook to use the key of the $variables\['elements'\], witch is finally the block key.

```
use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_region().
 */
function MYTHEME_preprocess_region(&$variables) {
  if ($variables['region'] == 'one_page') {
    $blocs_menu = array();
    foreach ($variables['elements'] as $key => $values) {
      if (substr($key, 0, 1) == '#') {
        continue;
      }
      $bloc_object = Block::load($key);
      if (is_object($bloc_object)) {
        $bloc_settings = $bloc_object->get('settings');
        if ($bloc_settings['label_display']) {
          $blocs_menu[] = array(
              'id' => $key,
              'label' => $bloc_settings['label'],
          );
        }
      }
    }
    if (count($blocs_menu)) {
      $variables['region_menu'] = $blocs_menu;
    }
  }
}

```

And in my override file region--one-page.html.twig

```
{%- if region_menu -%}
<nav class="page-nav-anchor">
  <ul>
{%- for menu in region_menu -%}
  <li><a rel="scroll" href="#block-{{ menu['id'] }}">{{ menu['label'] }}</a></li>
{%- endfor -%}
  </ul>
</nav>
{%- endif -%}

```

Everything is working well, but I would like to improve the concept :

* Be able to detect if the cache is activated on the project
* Include in cache my 'region\_menu' variable, and generate it only when cache have to be rebuild.

If I understand well, the twig template is also cached, then it is maybe just not really necessary to declare the menu if cache is ON ?

The thing is I'm really lost in the D8 cache API. I think I have to deal with the cache tags, because I don't have a render to cache.

I would appreciate some help, I cannot find some good (and easy) examples on the documentation or in the core modules.

# Answer
Regions are not cached on their own. What you build in a region template will be part of cached pages. If most pages you deliver are cached, this might be OK.

To optimize it build the menu in a block plugin and place the block at the top of the region. The block plugin can get the blocks from BlockRepository::getVisibleBlocksPerRegion. Use the access cache metadata this method provides for the region, add cache tags for all block entities and the tag `config:block_list`, so that the menu block gets invalidated when the block layout is modified.
> 0 votes

---
Tags: 8, caching
---


# Question
Title: hide a view block if it has less than x results
I would like to make a slideshow on author pages if they write more than 10 articles on my site, otherwise no. I have created a views block containing the slideshow and i wonder how to automatically/programatically hide it if les than 10 articles were written . Thanks in advance for any help Yaz

# Answer
> 0 votes
You can use the `template_preprocess_views_view()` in your `theme_name.theme` (assuming D8) or in your template.php

```
function MY_THEME_NAME_preprocess_views_view(&$variables) {
  if ($variables['display_id'] == 'MY_DISPLAY_ID' && count($variables['view']->result) < 10) {
    $variables['view']->result = NULL;
  }
}

```

This is working for Drupal 7 and I assume it will for Drupal 8. Be sure to check if your display is unique or you can also use the ID with :

```
$id = $variables['view']->storage->id(); // D8

```

---
Tags: views, hooks
---


title: Render Twig in hook_mail()

text:
# Question
Title: Render Twig in hook_mail()
I want to render twig when sending email (if it is possible) or include a template.

My code is like so:

```
/**
 * Implements hook_mail().
 */
function reg_email_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );

  switch ($key) {
    case 'new_user':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('User created: @title', array('@title' => $params['title']), $options);
      $message['body'][] = \Drupal\Core\Mail\MailFormatHelper::htmlToText($params['message']);
      break;
  }
}

```

I'd like to change `$params['message']` or part of this with twig. Is it possible?

# Answer
```
$body_data = [
  '#theme' => 'something',
  '#somearg1' => 'somevalue1',
  '#somearg2' => 'somevalue2',
];
$body_content = \Drupal::service('renderer')->render($body_data);
$message['body'] = explode("\n", $body_content);

```
> 2 votes

# Answer
It's possible, but if you want to keep the HTML output from Twig, you need to use a mail plugin that doesn't replace the HTML tags with other strings, or implement it and let Drupal use that plugin instead of the default one.

The code you are showing already replaces HTML tags with other strings, since it's calling \Drupal\Core\Mail\MailFormatHelper::htmlToText(), which as you see, replaces HTML tags with other strings. That is also the reason why you see `========` instead of `<hi>` and `</h1>`.
Even if you would remove that method call, the default implementation of the mail plugin uses the following code, in `PhpMail::format()`.

```
  // Join the body array into one string.
  $message['body'] = implode("\n\n", $message['body']);

  // Convert any HTML to plain-text.
  $message['body'] = MailFormatHelper::htmlToText($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = MailFormatHelper::wrapMail($message['body']);

```

It doesn't check the headers set for the email message; it always converts HTML to plain text.
> 0 votes

---
Tags: 8, emails, theming
---


# Question
Title: How to natural sort by text fields in Views?
I'm trying to sort a view by a text field. The text field include numbers, in general.

While sorting it sorts as below:

* 1
* 10
* 11
* 2
* 20
* ...

But I want to make the sorting **natural**.

The Views Natural Sort module doesn't work, it only works with the `Title` field, unfortunately (there was some options to sort text fields before but now there isn't any option for this).

**How can I natural sort the view by text field?** And use the table sort asc/sort desc feature?

*(The field should be text field and couldn't be an integer field.)*

# Answer
As per *Views Natural Sort* module homepage, you should enable *Enable Views Natural Sort Text Field* support to make the text fields sortable.

Here are the steps:

> 1. Enable *Views Natural Sort*.
> 2. Also *Enable Views Natural Sort Text Field* support (this will most likely go away in the future)
> 3. Navigate to the fields edit page for the field that you wish to enable 1. Natural Sorting on and check "Enable natural sorting." http://screencast.com/t/eDkW0c6AC This is needed so that we aren't indexing other text fields needlessly bloating the sorting table. In the future there may be a separate table for each field, I'll have to do some performance testing.
> 4. When you do that, your fields "Should" be reindexed... at that time. You should be taken to a batch operations screen.
> 5. Next you can go to the view you are editing and the option to sort the view naturally should be there. http://screencast.com/t/6XD7oeBtl
>
> *Note*: When working with fields there is the need to enable fields for indexing. At the point the setting is enabled, the field is indexed and will be ready for use in a view. Follow the following steps to allow natural sorting on text fields:
> 2 votes

# Answer
I had numbered title fields I wanted sorted naturally (1,2,3,4,5,6,10,11,20,21,30). Views natural sort did not work for me. Sorting was all messed up. What finally worked for me was to uninstall views natural sort and simply put "order by lpad(name, 10, 0)" in the database comment field of the view.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How can I add a link to the main menu from a custom module?
I've seen numerous questions on how to address this, but I've not quite found the answer. I'd like to add an additional link to the `main` menu. I've attempted this in `my_module.links.menu.yml` and run `drush cr`. This doesn't seem to limited impact.

This item will show up under the Tools menu, but not main.

```
my_module.list:
  title: 'List All Computers'
  description: 'Show all known computers'
  route_name: my_module.listAllComputers
  parent: main

```

Is there something wrong with the above? Is PHP a better way to add a link to the main menu? If so, where? Do I use a Drupal 8 hook?

# Answer
> 1 votes
You are missing the key `menu_name` that will permit the addition of your new menu item into your main menu.

```
my_module.list:
  title: 'List All Computers'
  description: 'Show all known computers'
  route_name: my_module.listAllComputers
  parent: main
  menu_name: main

```

The `parent` key is not mandatory, so if you want your link to be shown on the first level of your main\_menu, you don't need it.

---
Tags: navigation
---


# Question
Title: How to run drush tests from the command line?
I installed drush via composer, initially drush 8 was installed.

I then try to run tests via drush test-run command,unfortunately I get the following output indicating the command is not found.

> (16:38 vagrant@devbox .composer) \> drush test-run help The drush command 'test-run help' could not be found. Run `drush cache-clear
>  drush` to clear the \[error\]

Installing version 7 via composer gives same output. Clearing the drush cache did not help, am I missing something?

# Answer
> 6 votes
The test-run command was removed from Drush; the recommendation now is to simply run the `scripts/run-tests.sh` script in Drupal folder directly.

See: Running tests through command-line.

# Answer
> 3 votes
The exact command to run the test from drupal root is :

```
php scripts/run-test.sh module_name

```

Where module name may be Profile for example or your custom module name. Similarly you can run particular test case from a particular module as well.

# Answer
> 0 votes
Looks like you are in the composer directory. You need to be in the Drupal root of your site to run most commands.

Also you'll need the testing module enabled. Is it Simpletest?

---
Tags: 7, drush
---


title: Dependency injection on module.install

text:
# Question
Title: Dependency injection on module.install
How do I leverage dependency injection for drupal 8 when invoking my module.install-\>hook\_install() mehtod?

Or do I have to use `\Drupal::` method at this point?

# Answer
> 5 votes
Yes, for procedural code in hooks you have to use the static service container wrapper `\Drupal`. Either to get a service or to use one of the predefined static functions. See for example:

*shortcut.install*

```
/**
 * Implements hook_install().
 */
function shortcut_install() {
  // Theme settings are not configuration entities and cannot depend on modules
  // so to set a module-specific setting, we need to set it with logic.
  if (\Drupal::service('theme_handler')->themeExists('seven')) {
    \Drupal::configFactory()->getEditable('seven.settings')->set('third_party_settings.shortcut.module_link', TRUE)->save(TRUE);
  }
}

```

---
Tags: 8, installation, dependency-injection
---


# Question
Title: How to add a base field for an entity reference to a specific vocabulary
I have an Entity: `EntityX`. It installs correctly and works the way that I want it to; with, of course, one exception.

I want to attach an entity reference to a specific vocabulary. I have tried:

My vocabulary's machine name is: `custom_vocabulary`

In `EntityX`'s definition I have the following defined in the `baseFieldDefinitions` function:

```
$fields['my_custom_vocabulary'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Vocabulary'))
  ->setDescription(t('What was this tagged with.'))
  ->setSetting('target_type', 'custom_vocabulary')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'author',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

But when I go to install it, I get the following error:

```
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "custom_vocabulary" entity type does not exist. in /brew/www/html/core/lib/Drupal/Core/Entity/EntityTypeManager.php:133

```

While looking at the article defined in the `installation profile` for Drupal, I see that they use it as a field and not a true entity reference. Is there no way for me to do it this way? I can't have this all nicely bundled into one single entity.

What I don't know how to do is add a term from a vocabulary to an entity type.

# Answer
> 7 votes
Vocabularies are bundles of the entity type taxonomy term. If you want to reference a vocabulary then first set `taxonomy_term` as target type and second restrict the field to a specific vocabulary as target bundle:

```
$definition = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler_settings', ['target_bundles' => ['custom_vocabulary' => 'custom_vocabulary']]);

```

See change record https://www.drupal.org/node/2576151

---
Tags: 8, taxonomy-terms, entities
---


# Question
Title: Using a View's exposed Sort Criteria redirects to home page
I'm using the Content: Title Sort Criteria as part of a View and I've exposed that so that site visitors can sort results.

However, when (on the front end) I hit the Sort Criteria's "Apply" button I get redirected to the home page.

The URL does retain the sort critieria information, eg: `mysite.com/?sort_by=changed&sort_order=ASC`

It's just is missing the rest of the URL - the page name. It should be `mysite.com/listing-page?sort_by=changed&sort_order=ASC`.

Looking at the filter form's action attribute, I see it is set to `action="/"`.

Would anyone know how to fix this?

# Answer
> 1 votes
if you use panels, and i think you are, use content panes only, not block views, etc. and make sure in views UI in middle column to set "use panel path" to yes.

---
Tags: 7, views
---


# Question
Title: How to access files from a custom block without code
I've created a custom block in D8 via the UI. Is there any way to reference the files path in order to use images in the block without having to create a module?

# Answer
> 0 votes
I might be misunderstanding, but in a custom block you should be able to use standard img tags to display an image you've uploaded to your site.

---
Tags: blocks
---


# Question
Title: Cannot get values in 3rd level SubFormState
I have a block that embeds another plugins into itself and this includes configuration form. I can properly handle the form structure but when it comes to validation I am not able to access the values in the embedded plugin form validation handler. I was looking at the SubFormState and I tried to adjust the #parents of the provided form element but it didn't help. I know SubFormState is far from perfect but this should not be an issue.

This is my form:

```
// ...
$carousel_ajax = [
      'wrapper' => 'carousel-settings-ajax-wrapper',
      'callback' => [get_called_class(), 'selectCarouselAjaxFormRebuild']
    ];

    // No need for "#tree" option here since this form is already embedded.
    $form['carousel'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Carousel'),
      '#prefix' => '<div id="' . $carousel_ajax['wrapper'] . '">',
      '#suffix' => '</div>'
    ];

    $form['carousel']['plugin'] = [
      '#type' => 'select',
      '#title' => $this->t('Use carousel'),
      '#options' => ['' => '- ' . $this->t('None') . ' -'] + $this->carouselManager->getList(),
      '#default_value' => $configuration['carousel']['plugin'],
      '#ajax' => $carousel_ajax + ['trigger_as' => ['name' => 'select_carousel_submit']],
    ];

    $form['carousel']['select_carousel_submit'] = [
      '#type' => 'submit',
      '#name' => 'select_carousel_submit',
      '#value' => $this->t('Select carousel'),
      '#submit' => [[$this, 'selectCarouselFormSubmit']],
      '#limit_validation_errors' => [['settings', 'carousel']],
      '#ajax' => $carousel_ajax,
      '#attributes' => [
        'class' => ['js-hide']
      ]
    ];

    $form['carousel']['settings'] = [];
    if (!empty($configuration['carousel']['plugin']) && $this->carouselManager->hasDefinition($configuration['carousel']['plugin'])) {
      $carousel_plugin = $this->carouselManager->createInstance($configuration['carousel']['plugin'], $configuration['carousel']['settings']);
      $form['carousel']['settings'] = $carousel_plugin->buildConfigurationForm(
        $form['carousel']['settings'],
        SubformState::createForSubform($form['carousel']['settings'], $form, $form_state)
      );
    } else {
      $form['carousel']['settings'] = [
        '#type' => 'value',
        '#value' => []
      ];
    }

    return $form;

```

This is the block form validation handler(I am experimenting with various structures and whatnot):

```
public function blockValidate($form, FormStateInterface $form_state) {
    if ($form_state->hasValue(['carousel', 'plugin'])) {
      $carousel_plugin = $this->carouselManager->createInstance(
        $form_state->getValue(['carousel', 'plugin']),
        $form_state->getValue(['carousel', 'settings'])
      );
      //array_shift($form['settings']['carousel']['settings']['#parents']);
      $carousel_plugin->validateConfigurationForm(
        $form['settings']['carousel']['settings'],
        SubformState::createForSubform($form['settings']['carousel']['settings'], $form, $form_state)
      );
    }
  }

```

---

3rd level because the block itself is 2nd level being embedded in the `\Drupal\block\BlockForm::form`

# Answer
After quite some experimenting I came to a working solution.

```
  /**
   * {@inheritdoc}
   */
  public function blockValidate($form, FormStateInterface $form_state) {
    if ($form_state->hasValue(['carousel', 'plugin'])) {
      $carousel_plugin = $this->carouselManager->createInstance(
        $form_state->getValue(['carousel', 'plugin']),
        $form_state->getValue(['carousel', 'settings'])
      );

      // We have to do some manual adjustments here since the SubFormState
      // is far from perfect.
      $element = $form['settings']['carousel']['settings'];
      array_shift($element['#parents']);

      $carousel_plugin->validateConfigurationForm(
        $element,
        SubformState::createForSubform($element, $form, $form_state)
      );
    }

```

So the embedded validation handler has to receive **altered** form element and the subformstate has to receive the original, intact, form.
> 3 votes

---
Tags: 8, forms, blocks, plugins
---


title: How to create temporary select field?

text:
# Question
Title: How to create temporary select field?
I added a field:

```
$form['field_brand_selector']['#type'] = "select";
$form['field_brand_selector']['#title'] = "Brand";
$form['field_brand_selector']['#required'] = false;

```

This field is populated dynamically using Javascript. However, if I try to save the form, I get:

```
Illegal choice 49124 in Brand element.

```

I suspect that this is because I don't have this:

```
$form['field_brand_selector']['#options'] = $options;

```

So Drupal doesn't know which values are allowed for this Dropdown Selector. But seeing as this dropdown selector is not actually a field that must be saved, is there a way to "ignore" it's submission when I press save, so that I don't get the illegal Brand element error?

# Answer
Probably a hack, but this is how I solved it:

```
$form['field_brand_selector'] = array(
    '#type' => 'inline_template',
    '#template' => '{{ somecontent | raw }}',
    '#context' => [ 'somecontent' =>
    '
        <label for="edit-field-brand-selector">Brand</label>
        <select class="" id="edit-field-brand-selector" name="field_brand_selector" readonly="readonly"></select>
    '],
    '#weight' => 8,
);

```

This way Drupal doesn't validate the field I added.
> -1 votes

---
Tags: 8, forms
---


# Question
Title: Give access to private files to certain role?
I have a few image styles set up. But they are all stored as "private" files. I want to be able to give anonymous users public access to these files, or find some other way by which to generate access to this file. My goal is to provide access to private files for certain anonymous users depending on certain conditions.

I am hiding all images on the server to avoid anyone accidentally gaining access to them, but some "private" images should be viewable if a certain style is applied. For example, I am selling images on my site. The "waterproof" image style should allow any user (including anonymous) user to see the private file preview. But only logged in users should be able to view it with the "high\_res" thumbnail.

This is how I generate the URL:

```
$imageURL = file_create_url($badge->field_badge_image_image->entity->getFileUri());

```

This url can only be accessed by logged in users. If I try this code, I still get access denied.

```
$imageURL = ImageStyle::load('farm_logos')->buildUrl(
    $badge->field_badge_image_image->entity->getFileUri()
);

```

Is there no way to generate a URL that is accessible via public?

I also tried the "hook\_file\_download":

```
function mymodule_file_download($uri) {
    return array(
        "Accept" => "Accept",
        'Content-Type' => "image/jpg"
    );
}

```

But I was hoping this would make all private files public, but unfortunately it did not.

# Answer
I found the problem. As per this page:

> Once configured, files stored in the private directory are inaccessible via a direct link; however, if Drupal constructs a link to the file, the file will be accessible to anyone who can see the link.
>
> For example: you have created a new content type with a file field which stores files in your site's private file directory. Next you create a node from this new content type and attach two new files. When the node is published links to both attached files are visible and anyone who can view the node may download the files. Now, if you unpublish the node, all attached files become inaccessible for download even if you use the direct link to the files that worked when the node was published.
>
> Re-publish the node, and disable the "display" checkbox for one of the files. Save the node. Now one file is accessible for public download and the other is not accessible--**even if you have the direct URL for the file that is not listed you will not be able to download this file.**

So the problem was that I was expecting you could access a file if you have the right URL, even if that file is used on an UNPUBLISHED node. So to solve my problem I:

* Published all the nodes I needed to have access to the image
* Used "Rabbit Hole" to hide the nodes from the public
> 2 votes

# Answer
I was able to do this by creating a content type **Download Page** that had an upload field to private files. For the permission part I used node\_view\_permissions to hide the content\_type from Anonymous users. This is achievable via the permission **Download Page: View own content**. Since, Anonymous users do not have access to create Download Pages, the role no longer has access to the node.
> 0 votes

---
Tags: 8, files
---


title: Display 2 content type in front page

text:
# Question
Title: Display 2 content type in front page
I am learning Drupal 8, i have 2 content type (Notices, Plan), i want my front page look like this:

**List entries of Notices**

* item 1
* item 2
* item n

Pager of list Notices

**List entries of Plan**

* item 1
* item 2
* item n

Pager of list Plan

Can i do this in some way?

# Answer
> 2 votes
The fastest possible way is to create a Views page and a Views block. Then change the front page path with the one you used for the View (Configuration \> Basic site settings \> FRONT PAGE) Then create the block instance in the Content region (Structure \> Block layout)

Also, make sure you are using 2 different Pager ids in your view (in your view, under Pager \> Settings \> Pager ID) You may just use 1 for one of the views and 2 for the other one.

# Answer
> 0 votes
You can display entries as block with pagination by using views module. To know how to create block, watch views block tutorial.

I hope this would help.

---
Tags: views, theming
---


# Question
Title: Programmatically load webform edit page by SID
I am trying to load an edit form like (drupal 7) : node/6/submission/72/edit into a custom page where I run the drupal\_render\_form

but I am not sure is this the same as node load form? can some one provide references on how to load webform submission edit page into a body of page.

thank you!

# Answer
> 0 votes
I managed to solve it by creating a custom module, with a custom page and inside the custom page I use the :

```
drupal_get_form

```

and it works perfect!

---
Tags: 7, forms, webforms
---


# Question
Title: How can I override a Paragraphs field & bundle output with custom template in a custom module?
**Backstory**

I have created multiple Paragraph bundles. My goal is to have absolute control over the output of these bundles (1) as well as the output of the containing field (2) in a scalable way (for ease of future bundle addition -- there may be 30+ bundles in the future).

**Where I'm at**

I've created a theme suggestion using `HOOK_theme_suggestions_HOOK_alter` to override the bundles' output. This allowed me to create custom twig templates for each bundle.

```
/**
 * Implements hook_theme()
 *
 * Register a theme for each paragraph type
 *
 */
function MYMODULE_theme($existing, $type, $theme, $path){
  $theme_templates  = [];
  $paragraph_types  = MYMODULE_get_paragraph_types();

  // Register custom Paragraph bundle templates
  foreach ($paragraph_types as $paragraph_type){
    $theme_templates['paragraph__MYMODULE__' . $paragraph_type] = [
      'base hook' => 'paragraph'
    ];
  }

  // Register custom Paragraph bundle template fallback
  $theme_templates['paragraph__MYMODULE'] = [
    'base hook' => 'paragraph'
  ];

  // Register custom Paragraph field wrapper
  // $module_path = drupal_get_path('module', 'MYMODULE');
  // $theme_templates['paragraph__MYMODULE__field_wrapper'] = [
  //   'base hook' => 'field',
  //   'template' => 'paragraph--MYMODULE--field-wrapper',
  //   'path' => $module_path . '/templates'
  //  ];

  return $theme_templates;
}

/**
 * Implements HOOK_theme_suggestions_HOOK_alter
 */
function MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables, $hook) {
  $field = $variables['element']['#field_name'];

  if( $field == 'field_content_modules' ) {
    $suggestions[] = 'paragraph__MYMODULE__field_wrapper';
  }
}

/**
 * Implements HOOK_theme_suggestions_HOOK_alter
 */
function MYMODULE_theme_suggestions_paragraph_alter(&$suggestions, $variables){
  $entity              = $variables['elements']['#paragraph'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  $type                = $entity->getType();

  $suggestions[] = 'paragraph__MYMODULE';
  $suggestions[] = 'paragraph__MYMODULE__' . $type;
  $suggestions[] = 'paragraph__MYMODULE__' . $type . '__' . $sanitized_view_mode;
}

/**
 * Implements hook_theme_registry_alter()
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  $module_path      = drupal_get_path('module', 'MYMODULE');
  $template_objects = drupal_find_theme_templates($theme_registry, '.html.twig', $module_path);
  $paragraph_types  = MYMODULE_get_paragraph_types();

  // 1. Loop through the paragraph types
  // 2. Check if each paragraph exists in the `$template_objects` array
  // 3. If it doesn't exist, remove it from the registry so we don't get any errors
  // 4. If it does exist, set actual path to template
  foreach ($paragraph_types as $type){
    $template = 'paragraph__MYMODULE__' . $type;
    if(!isset($template_objects[$template])){
      unset($theme_registry['paragraph__MYMODULE__' . $type]);
    } else {
      $theme_registry['paragraph__MYMODULE__' . $type]['path'] = $template_objects[$template]['path'];
    }
  }
}

/**
 * Helper function to get a list of paragraph types by machine name
 *
 * @return array
 */
function MYMODULE_get_paragraph_types(){
  $paragraph_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('paragraph');
  return array_keys($paragraph_bundles);
}

```

So part 1 is done.

Part 2 is controlling the Paragraph field (not bundle) container HTML. This should be just a plain field template override. I've added a file:

```
/modules/custom/MYMODULE/templates/paragraph--MYMODULE--field-wrapper.html.twig

```

...and dropped in the contents of field.html.twig. When I uncomment the `hook_theme` code above ("Register custom Paragraph field wrapper"), I get this error:

> The website encountered an unexpected error. Please try again later. Recoverable fatal error: Argument 1 passed to Drupal\Core\Render\Element::children() must be of the type array, null given, called in /Users/phil/Sites/glades/www/modules/contrib/paragraphs/paragraphs.module on line 238 and defined in Drupal\Core\Render\Element::children() (line 71 of core/lib/Drupal/Core/Render/Element.php).

Any thoughts as to what I'm doing wrong with the field template override?

Most of this was inspired by a comment by jeremypeter here: https://www.drupal.org/node/2499827#comment-12159763

# Answer
> 4 votes
Per 4k4's comment to the original post, it was a naming convention issue as seen here: https://www.drupal.org/docs/8/theming/twig/twig-template-naming-conventions

In the *hook\_theme* and *hook\_theme\_suggestions\_HOOK\_alter* function above, I changed:

```
paragraph__contentmodules__field_wrapper

```

to:

```
field__paragraph__contentmodules__field_wrapper

```

Working code:

```
<?php

/**
 * Implements hook_theme()
 *
 * Register a theme for each paragraph type
 *
 */
function MYMODULE_theme($existing, $type, $theme, $path){
  $theme_templates  = [];
  $paragraph_types  = MYMODULE_get_paragraph_types();

  // Register custom Paragraph bundle templates
  foreach ($paragraph_types as $paragraph_type){
    $theme_templates['paragraph__MYMODULE__' . $paragraph_type] = [
      'base hook' => 'paragraph'
    ];
  }

  // Register custom Paragraph bundle template fallback
  $theme_templates['paragraph__MYMODULE'] = [
    'base hook' => 'paragraph'
  ];

  // Register custom Paragraph field wrapper
  $theme_templates['field__paragraph__MYMODULE__field_wrapper'] = [
    'base hook' => 'field',
  ];

  return $theme_templates;
}

/**
 * Implements HOOK_theme_suggestions_HOOK_alter
 */
function MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables, $hook) {
  $field = $variables['element']['#field_name'];

  if( $field == 'field_content_modules' ) {
    $suggestions[] = 'field__paragraph__MYMODULE__field_wrapper';
  }
}

/**
 * Implements HOOK_theme_suggestions_HOOK_alter
 */
function MYMODULE_theme_suggestions_paragraph_alter(&$suggestions, $variables){
  $entity              = $variables['elements']['#paragraph'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  $type                = $entity->getType();

  $suggestions[] = 'paragraph__MYMODULE';
  $suggestions[] = 'paragraph__MYMODULE__' . $type;
  $suggestions[] = 'paragraph__MYMODULE__' . $type . '__' . $sanitized_view_mode;
}

/**
 * Implements hook_theme_registry_alter()
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  $module_path      = drupal_get_path('module', 'MYMODULE');
  $template_objects = drupal_find_theme_templates($theme_registry, '.html.twig', $module_path);
  $paragraph_types  = MYMODULE_get_paragraph_types();

  // 1. Loop through the paragraph types
  // 2. Check if each paragraph exists in the `$template_objects` array
  // 3. If it doesn't exist, remove it from the registry so we don't get any errors
  // 4. If it does exist, set actual path to template
  foreach ($paragraph_types as $type){
    $template = 'paragraph__MYMODULE__' . $type;
    if(!isset($template_objects[$template])){
      unset($theme_registry['paragraph__MYMODULE__' . $type]);
    } else {
      $theme_registry['paragraph__MYMODULE__' . $type]['path'] = $template_objects[$template]['path'];
    }
  }
}

/**
 * Helper function to get a list of paragraph types by machine name
 *
 * @return array
 */
function MYMODULE_get_paragraph_types(){
  $paragraph_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('paragraph');
  return array_keys($paragraph_bundles);
}

```

---
Tags: 8, theming, paragraphs
---


title: Fatal error on Drush run

text:
# Question
Title: Fatal error on Drush run
I've installed Drush following http://www.zyxware.com/articles/4497/drupal-installing-latest-version-of-drush-on-linux-system-and-troubleshooting.

Now, when I try to run Drush, I get this error message.

> PHP Fatal error: Class Symfony\Component\Console\Style\SymfonyStyle contains 4 abstract methods and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Console\Output\OutputInterface::isQuiet, Symfony\Component\Console\Output\OutputInterface::isVerbose, Symfony\Component\Console\Output\OutputInterface::isVeryVerbose, ...) in /var/www/html/tubimer/vendor/symfony/console/Style/SymfonyStyle.php on line 33
> Drush command terminated abnormally due to an unrecoverable error.
> Error: Class Symfony\Component\Console\Style\SymfonyStyle contains 4 abstract methods and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Console\Output\OutputInterface::isQuiet, Symfony\Component\Console\Output\OutputInterface::isVerbose, Symfony\Component\Console\Output\OutputInterface::isVeryVerbose, ...) in /var/www/html/tubimer/vendor/symfony/console/Style/SymfonyStyle.php, line 33

How do I fix these errors?

# Answer
I suggest you to run -

```
composer self-update
composer update

```

It might solve your problem, but if it doesn't then try to install latest version of drush. I installed drush using https://www.drupal.org/node/1248790. However, there is a full documentation on how to install drush for specific operating system. Link to documentation - https://www.drupal.org/node/1791676
> 2 votes

---
Tags: drush, composer
---


# Question
Title: Troubles with adding video provider to Video Embed Field module
I have installed Video Embed Field module, youtube links works good. Next I have installed Video Embed Wistia, and can't set valid Wistia's links. The error is

> Could not find a video provider to handle the given URL.

Video embed field and Video Embed Wistia modules are on in `admin/modules`

What I have missed? Why it doesn't work?

# Answer
I've found solution, it's simple.

You need to go in the field settings of this field and find a checkboxes with all video providers. Mark Wistia or any new provider here and it will work.
> 0 votes

---
Tags: 8
---


# Question
Title: Overwrite the url function of a specific node entity
Can I overwrite the url function of a specific content type of node entity ? So to have a different pattern when i use: $node-\>url();

# Answer
**Entity URI callback**

You can implement an URI callback. Example in *comment.module*:

```
/**
 * Entity URI callback.
 */
function comment_uri(CommentInterface $comment) {
  return new Url(
    'entity.comment.canonical',
    [
      'comment' => $comment->id(),
    ],
    ['fragment' => 'comment-' . $comment->id()]
  );
}

```

and add the callback to the annotations of the entity type:

```
*   uri_callback = "comment_uri",

```

For an existing entity use a hook\_entity\_type\_alter().

**Bundle specific URI callback**

A URI callback for a specific content type can be defined in the bundle definitions:

```
**
 * Implements hook_entity_bundle_info_alter().
 */
function mymodule_entity_bundle_info_alter(&$bundles) {
  if (isset($bundles['node']['my_content_type'])) {
    $bundles['node']['my_content_type']['uri_callback'] = 'my_content_type_uri';
  }
}

```

The callback:

```
/**
 * Bundle URI callback.
 */
function my_content_type_uri(NodeInterface $node) {
  // build a url object $url
  return $url;
}

```

A bundle-specific callback takes precedence over the generic one for the entity type and a link template (defined in the links array of the entity type) takes precedence over both, so you need to remove the link template if you want to override an existing one, e.g. `canonical`, which makes you responsible to provide the route needed for the custom url, if it was built before by a route provider and is not defined in a \*.routing.yml file.

---

**Edit:**

To modify the url in links to a specific content type you can use a hook\_link\_alter():

```
function mymodule_link_alter(&$variables) {
  $url = $variables['url'];
  if ($url->isRouted() && $url->getRouteName() == 'entity.node.canonical') {
    if (isset($variables['options']['entity'])) {
      $node = $variables['options']['entity'];
      if ($node->bundle() == 'article') {
        // modify the links to articles
      }
    }
  }
}

```
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Breadcrumb per content type per role, bootstrap theme
I need to display a breadcrumb per content type and per role. What the best way to do it. I've tried a lot of module and none fit my needs.

I tried overwritting breadcrumb in template.php as follow, and it's not working :

```
function local_breadcrumb($variables) {
  $output = '';

  global $user;
  /** Breadcrumb for hsrehab_admin **/
  if(in_array('hsrehab_admin', $user->roles)) {
   if ($vars['node']->type == 'patient_sheet') {
     // Build Breadcrumbs
     $breadcrumb = array();
     $breadcrumb[] = l('Dashboard', '');
     $breadcrumb[] = l('Manage Patients', '/admin/manage-patients');
     $breadcrumb[] = l(drupal_get_title(), base_path() . request_uri());
     }
   }

  // Determine if we are to display the breadcrumb.
  $bootstrap_breadcrumb = bootstrap_setting('breadcrumb');
  if (($bootstrap_breadcrumb == 1 || ($bootstrap_breadcrumb == 2 && arg(0) == 'admin')) && !empty($breadcrumb)) {
    $output = theme('item_list', array(
      'attributes' => array(
        'class' => array('breadcrumb container'),
      ),
      'items' => $breadcrumb,
      'type' => 'ol',
    ));
  }
  return $output;
}

```

# Answer
You can create a theme template for each content type, then add the breadcrumb logic in there and output the modified breadcrumb there. Here's a great DO resource for theming and how to use template files. In a nutshell, you can clone your default page.tpl.php and rename it page--patient\_sheet.tpl.php and inside this template you can run and output the breadcrumb logic.
> 0 votes

---
Tags: 7, breadcrumbs, bootstrapping
---


# Question
Title: How can i restrict /admin login page to a particular IP only?
I want to restrict the http://www.mysite.com/admin login page to a particular IP only. Do you have any suggestion?

# Answer
I think I would go for doing this at the Apache level before hitting Drupal.

Have a look at the Apache manual for doing this but you are looking at something like this:

```
# Only allow request for admin only from localhost.
<Location /admin>
  Deny from all
  Allow from 127.0.0.1
</Location>

```

So admin will be denied for all but allowed from 127.0.0.1 for example. Also take in to account cleanurls. You will need to deny access to ?q=admin aswell.
> 7 votes

# Answer
There are a lot of IP modules out there that block access to the website by IP, but these are black/whitelists for the whole website.

There is a module called Restrict IP which only allows whitelisted IPs to log in.

> In general, this module provides features that allow an IP address (or range of IP addresses) to be whitelisted which restrict the functionality of users. Currently there are two features implemented:
>
> ### Restrict login by IP
>
> When a user is restricted, that user will not be able to log in outside the defined IP address ranges. It is also possible to specify global IP address ranges, which apply to ALL users, including user1. Following a denied log-in attempt, a user is redirected to an error page as specified by the site administrator.
>
> ### Restrict role by IP
>
> When a role is restricted, that role will not be available to users outside the defined IP address ranges. Role restriction does not affect users' ability to log in, only the availability of the restricted role to users. Role restrictions are available for all roles, except "anonymous user" and "authenticated user".
> 6 votes

# Answer
This code may help you. (Replace *mymodule* with machine name of the module containing this code.)

```
function mymodule_menu_alter($items) {
  $items['admin']['access callback'] = 'mymodule_check_by_ip';
}

function mymodule_check_by_ip() {
  if (in_array($_SERVER['REMOTE_ADDR'], ['PARTICULAR_IP_ADDRESS', 'ANOTHER_PARTICULAR_IP_ADDRESS'])) {
    return FALSE;
  }

  return TRUE;
}

```
> 3 votes

# Answer
This can be done by configuring `.htaccess` to raise the `[F]` flag (returns a 403 Forbidden status code to the client) for certain URLs when `%{REMOTE_ADDR}` doesn't match a given IP.

To be placed after `RewriteEngine on`:

```
RewriteCond %{REMOTE_ADDR} !^100\.22\.44\.[8-9]$
RewriteRule ^/user - [F]
RewriteRule ^/USER - [F]

```
> 1 votes

# Answer
There is a module available for D7 to provide page level access for IPs

Restrict Page IP

> Provides administrator to restrict/allow access to pages based on user IPs.
>
> ## Features
>
> * IPs can be an individual IP or range of Ips.
> * Page url can have wild cards like 'blog/\*'
> * Restricted user IPs will be denied showing custom error message (can be modified on module's configuration page)
>
> Note : User 1 has been skipped from these restrictions.
> 0 votes

---
Tags: users
---


title: How do I format JQuery in Drupal 8?

text:
# Question
Title: How do I format JQuery in Drupal 8?
I'm trying to write a simple JQuery function in order to animate my mobile navigation. However, I'm not sure how to format the .js file. I've looked up some examples online, but I couldn't get my function to work, when I tried to use the example templates. Here's what I'm currently using, which works in Chrome, but FireFox logs an error, which I'll also post below:

My code:

```
(function ($, Drupal) {
      $(function(){
        $( '#mobile-menu-toggle-button' ).click(function(){
          $( '.mobile-menu-toggle' ).toggleClass( "open" );
        });
        $( '.overlay' ).click(function(e){
          if(e.target != this) return;
          $( '.mobile-menu-toggle' ).toggleClass( "open" );
        });
      });
})(jQuery, Drupal);

```

FireFox errors:

```
ReferenceError: Drupal is not defined

```

I'm thinking my formatting is off. Any help would be greatly appreciated.

# Answer
> 3 votes
D8 makes fewer assumptions about what you need in the page, so the Drupal JS library isn't included unless it's specified.

Just add

```
- core/drupal

```

as one of your library's dependancies, rebuild the cache, and all should be well.

---
Tags: theming, 8, javascript, installation
---


# Question
Title: Add attributes like id to block level elements in CKEditor?
In Drupal 8, is there a way/module to add attributes like "id" to h1-h6, p, span and so forth?

I am trying to find a way to support anchors, which Drupal does not seem to support anymore.

edit: Yes, I can instruct to edit with the Source button, but I am looking for a more user friendly way with a dialog and I am not seeing it.

# Answer
If you just need to add ID to a link you can use the D8 Editor Advanced link module https://www.drupal.org/project/editor\_advanced\_link

It basically allows you to put attributes on anchor tags without touching the source code.
> -1 votes

---
Tags: 8, wysiwyg
---


# Question
Title: Displaying individual fields in a template
I have a template for a specific content type. I want to output individual fields from that content type in a specific order, which requires me to change the content type template. It's too complicated to explain why I need to do this.

In the template I see `{{ page.content }}` for outputting all the fields together, which displays everything, but I want to take the field variables out of this, and separately display each of them.

So for example I tried the following, but it displays nothing to the page.

```
{{ page.content.field_field_name1 }}
{{ page.content.field_field_name2 }}

```

I also tried `{{ content.field_field_name1 }}`, `{{ field_field_name1 }}`, and `{{ content.field_field_name1.entity }}`, but none of them work.

Suggestions?

# Answer
You can not print out content fields directly in the page template. content is available in the node template, not in the page template.

The correct way to print out parts of the node elswhere in the page template is to define a block that does that, for example with the ctools module and a specific view mode that just contains the fields you want.

Alternatively, you can load the node yourself in theme\_preprocess\_page() and then view/prepare them manually and put it in $variables. But using blocks and regions is the standard and recommended way to put something in the page template.
> 3 votes

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


# Question
Title: Load block programmatically, result: <drupal-render-placeholder
I want to load a block programmatically:

```
$block = \Drupal::entityManager()->getStorage('block')->load('contextualcart');
$block = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
$blockMarkup = \Drupal::service('renderer')->render($block);

```

But the result is:

```
<drupal-render-placeholder callback="Drupal\block\BlockViewBuilder::lazyBuilder" arguments="0=velocontextualcart&1=full&2" token="5IaX-v_M8zGkro6F9hTE93zRfIj9p4nHeLFv8Ja6ZW0"></drupal-render-placeholder>

```

This is fine, because I have to insert a block in AJAX.

What happened? How do I fix it?

# Answer
> 4 votes
When calling `->render()` it is rendering a structured array tree assuming that it is part of a whole page which will then do placeholder replacements later.

Use `renderRoot()` if you are the last instance and e.g. return this directly as an AJAX or JsonResponse.

# Answer
> 1 votes
The following code solved the issue:

```
$block = \Drupal::service('plugin.manager.block');
$block = $block->createInstance('block_contextual_cart')->build();
$blockMarkup = \Drupal::service('renderer')->render($block);

```

Source: @BOES comment.

---
Tags: 8, blocks
---


# Question
Title: Deliver ajax commands on successful form submit
First of I apologize if this has been asked before, but I haven't found anything that actually does what I want to do.

**Question:** I'm trying to deliver some ajax commands on after a successful ajax submission of a form.

**The Code**

```
function my_module_form_form($form, &$form_state){
    $node = $form_state['build_info']['args'][0];
    $form = array(
        'track_id' => array(
            '#type' => 'textfield',
            '#title' => t('Track ID'),
            '#required' => true,
            '#prefix' => '<div id="form-finished-wrapper-'.$node->nid.'">',
        ),
        'courier' =>array(
            '#type' => 'textfield',
            '#title' => t('Courier Name'),
            '#required' => true,
        ),
        'actions' => array(
            '#type' => 'actions',
             'submit' => array(
                '#type' => 'submit',
                '#ajax' => array(
                    'callback' => 'my_module_form_ajax_submit',
                    'wrapper' => 'form-finished-wrapper-'.$node->nid,
                ),
                '#prefix' => '<div class="modal-footer">',
                '#suffix' => '</div>',
                '#value' => t('OK'),
            ),
        ),
    );

    return $form;
}
function my_module_form_validate($form, &$form_state){
    // form_set_error('courier', 'catch all');
}

function my_module_form_ajax_submit($form, &$form_state){
    $return_form = array(
        'track_id' => $form['track_id'],
        'courier' => $form['courier'],
    );
    return $return_form;
}
function my_module_form_submit($form, &$form_state){

    $node = $form_state['build_info']['args'][0];
    $track_id = $form_state['values']['track_id'];

    $node->field_track_id[LANGUAGE_NONE][0]['value'] = $track_id;
    $node->field_courier_name[LANGUAGE_NONE][0]['value'] = $courier;
    node_save($node);

/* How can I deliver the below commands?

    $ajax_commands = array();
    $ajax_commands[] = ajax_command_invoke('myModal, 'modal', array('hide'));
    $ajax_commands[] = ajax_command_replace('form-finished-wrapper-'.$node->nid, t('Submited Successfuly'));
    ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));

*/

}

```

**Context**

The form appears in a modal my\_module\_form\_ajax\_submit is responsible to display validation errors along with messages. I have tried ajax\_delivery and ajax\_render to return the commands. With ajax\_render nothing happens, but with ajax\_deliver I get an ajax popup with the commands in JSON. I think I'm close but surely I'm missing something.

Any help appreciated!

# Answer
You return the ajax commands in your ajax callback function.

```
function my_module_form_ajax_submit(array $form, array &$form_state){
  if (count(form_get_errors())) {
    return array(
      'track_id' => $form['track_id'],
      'courier' => $form['courier'],
    );
  }
  else {
    $ajax_commands = array();
    $ajax_commands[] = ajax_command_invoke('myModal', 'modal', array('hide'));
    $ajax_commands[] = ajax_command_replace('form-finished-wrapper-'.$node->nid, t('Submited Successfuly'));
    return array('#type' => 'ajax', '#commands' => $ajax_commands);
  }
}

```

I'm not sure what you were trying to do with your original callback, so I couldn't incorporate it.
> 1 votes

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


title: Computed field value in twig template

text:
# Question
Title: Computed field value in twig template
I use a computed field, to calculate and store a floating value for a node. Now I want to work with this value in a twig template. When I access the field value via `{{ content.computed_field.0 }}`it outputs the correct value, say `0.22`. When I try to calculate with this value, i.e. `{% set newvalue = content.computed_field.0 * 100 %}` the page breaks (just pre-calculation twig content is outputted).

My first guess was that, for some reason, the field value is stored or read as a string (or another type?!). My DB says its a float and I don't know how to check a variable type in twig.

I tried to to use twigs `number_format()`-function : `{{ content.computed_field.0|number_format(2) }}`. This transforms the computed field to 1. I have no clue why this happens.
What am I doing wrong? Any tips or a workaround?

I use Drupal 8, Twig 1.25, and Computed Field 8.x-2.0-alpha3

Thank you in advance

# Answer
You could try this, if your using a node template: {{ node.computed\_field.value * 100 }}
> 1 votes

---
Tags: theming, entities
---


# Question
Title: Drupal 8 separate pages for separate taxonomy terms
I have two taxonomies. I want different page templates for each taxonomy term page. Lets call the taxonomies as `taxonomy_one` and `taxonomy_two`.

When I go to taxonomy term twig debug suggests following names:

```
<!-- FILE NAME SUGGESTIONS:
* page--taxonomy--term--2.html.twig
* page--taxonomy--term--%.html.twig
* page--taxonomy--term.html.twig
* page--taxonomy.html.twig
x page.html.twig
-->

```

Is there any way to override the taxonomy term page template by adding twig file such as:

`page--taxonomy-one--term.html.twig`?

# Answer
> 1 votes
Finally I found answer and posting it here in case someone needs it.

To do this you need to create the following function in your `your_template.theme` file:

```
use Drupal\taxonomy\Entity\Term;

function stravel_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()
      ->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()
      ->getRawParameter('taxonomy_term')
  ) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

```

This allows you to create page templates such as `page--taxonomy--mytaxonomy.html.twig` to display single term data. Now you can easily add regions, blocks and views as usual.

**However, to display data related to the relevant term, you need to add contextual filters.**

---
Tags: theming, 8
---


# Question
Title: How to return Views Field Value in Twig Template
How do I return a field value from Views when using a Views Relationship? Im using views-view-fields--pagedisplay--html.twig

```
fields.title.content

```

seems to return titles but

```
fields.field_movie_length.content

```

does not return any vales, however the field exists if I

```
{{ dsm(fields) }}

```

I have Twig Tweak & Twig Feld Value modules installed also.

# Answer
Views templates don't work like field templates, so the modules you have installed won't help. Though you can use node and field templates by switching the Format of the View to *Content* instead of *Fields* or you can configure a single field to use a field template in STYLE SETTINGS.

If you want to use the views templating system you might consider switching to the format *Table*, because this template has the most options.

The template you have now has very limited options. The field array is exactly the output you have configured in Views UI and this is the place where you should apply your adjustments.

After all of that, if you still want to see which fields and their content are delivered to your template, then use this loop for debugging:

*views-view-fields.html.twig*

```
{% for key, field in fields %}
  <p><i>{{ key }}:</i> {{ field.content }}</p>
{% endfor %}

```

`field.content` is finally rendered html, so you can't do much with it. The array keys contain the field names of the fields you have selected and arranged in the FIELDS section of the Views UI. It doesn't matter whether the fields come from relationsships.
> 0 votes

---
Tags: views, theming, 8
---


title: Redirect URL Path

text:
# Question
Title: Redirect URL Path
I need to add a redirect that makes all traffic going to the first URL path below to the second URL path. This needs to be done in a bulk fashion for all pages listed under this path.

```
www.site.com/PATH/page
to
www.site.com/page

```

I've installed the module Match Redirect and began experimenting but I can't get it to work the way I need.

# Answer
> 2 votes
The "Match Redirect" module will redirect all matching patterns to only *one* target path. Here's relevant paragraph from the project page:

> Only the source patterns can have wildcards. The target url is a single page and I have no plans to add wildcards to the target url.

To answer your question, you can do this is via `.htaccess`. Here's an example:

```
RewriteRule ^OLD-PATH/(.*)$ /NEW-PATH/$1 [R=301,NC,L]

```

I think it will work if you add these rules at the top of the `.htaccess` file, so they are executed before Drupal's rules.

# Answer
> 0 votes
One other way, without using additional modules would be to create a content with the alias **oldurl** adding the following full html content to the body:

```
<script>
window.location="http://www.yoursite.com/newurl"
</script>

```

---
Tags: 7, uri, redirection
---


title: How to redirect page to specific url?

text:
# Question
Title: How to redirect page to specific url?
How to redirect page to specific url **suppose blog-landing** page to **blog-landing/all** page

How to target specific page **/blog-landing** page when user enters url into browser user should redirect to **blog-landing/all**

What i have tried :

```
 function bootstrap_preprocess_page(&$variables) {

 $request = \Drupal::request();
 $current_path = $request->getPathInfo();
 $path_args = explode('/', $current_path);
 $first_argument = $path_args[1];
  if($first_argument =="blog-landing")
  {
    $response = new Symfony\Component\HttpFoundation\RedirectResponse('/node/12/edit');
 $response->send();
return;

}

else
{

 echo "sorry not redirected";
 }
}
}

```

# Answer
Use a default parameter (for example `blog_id`) in your `routing.yml` file:

```
mymodule.route_name:
  path: '/blog-landing/{blog_id}'
  defaults:
    _title: 'Show blogs.'
    _controller: '\Drupal\mymodule\Controller\BlogController::viewAction'
    blog_id: 'all'

```

If the `blog_id` parameter is omitted the default value ('all') is used.

**After your edit:**

If you are redirecting via the `RedirectResponse()` class you should call the `send()` method in order to redirect.
> 0 votes

# Answer
One other way, without using additional modules or rewrite rules would be to create a content with the alias **oldurl** adding the following full html content to the body:

```
<script>
window.location="http://www.yoursite.com/newurl"
</script>

```
> 0 votes

---
Tags: 8
---


# Question
Title: Define states that target only element in multi-value fieldset
I am using Webforms in Drupal 8, and I have a checkbox on a webform composite element which basically show/hides an address field.

```
public static function getCompositeElements() {
  $elements = [];

  $elements['address_same'] = [
    '#type' => 'checkbox',
    '#title' => t('They live at the same address'),
  ];

  $elements['address_postal'] = [
    '#type' => 'textfield',
    '#title' => t('Street address'),
    '#states' => [
      'visible' => [
        ':input[name="spouse[address_same]"]' => array('checked' => FALSE),
      ]
    ]
  ];
}

```

The issue I have is that this group of fields may have one or more values on the form, and if there is more than one then the states get all confused because they are targeting the wrong field.

This may be the same on Drupal 7, but I can not figure out how to give #states a generic selector for address\_same so that it only targets the one just before it.

Most likely I will just go write some custom jQuery for this, just thought there must be a way of doing it.

# Answer
See the first comment on my question, the Webform module (super-duper) maintainer @jrockowitz committed a change to the module's composite element example which explains how to do this in Drupal 8.

So this is my solution based on the question code:

```
use Drupal\Component\Utility\Html;
use Drupal\webform\Element\WebformCompositeBase;

class MembershipItem extends WebformCompositeBase {

  public static function getCompositeElements() {
    $elements = [];

    // Generate an unique ID that can be used by #states.
    $html_id = Html::getUniqueId('webform_membership_item');

    $elements['address_same'] = [
      '#type' => 'checkbox',
      '#title' => t('They live at the same address'),
      '#attributes' => [
        'data-webform-composite-id' => $html_id . '--address_same'
      ],
    ];

    $elements['address_postal'] = [
      '#type' => 'textfield',
      '#title' => t('Postal address'),
      '#states' => [
        'visible' => [
          '[data-webform-composite-id="' . $html_id . '--address_same"]' =>['checked' => FALSE],
        ]
      ]
    ];

    return $elements;
  }
}

```
> 0 votes

---
Tags: 8, forms, webforms
---


# Question
Title: temporary://fileh4Oxvi could not be copied, because the destination directory is not properly configured
I am using Advagg and Amazons3 Module, which is causing this error:

> temporary://fileh4Oxvi could not be copied, because the destination directory is not properly configured.

Files are getting created in "tmp" folder but that has been not copied to s3 bucket.

I had given the "tmp" folder 755 and even 777, which is not working. And I even tried Configuring the temporary directory, which is not working even.

Any inputs are really appreciated.

# Answer
> 1 votes
> ...could not be copied, because the **destination** directory...

The temp folder is the source in this context, Drupal is complaining that the destination is not writable.

You need to make your public file system (usually sites/default/files) writable by the web server user.

---
Tags: files
---


# Question
Title: Show a field only once if the value is the same
I have a content-type with a field "Shooting Date" of type "date".

I have a block-view which collects all nodes of this type.

I sort these nodes by "Shooting Date".

I now want to display the year at the top, then all elements in this year.

E.g.:

2017

-Node 1

-Node 2

-Node 3

2016

-Node 4

What I have by default ist:

2017 -Node 1

2017

-Node 2

2017

-Node 3

2016

-Node 4

Can anyone tell me how I can show the year only once if the value is the same?

# Answer
> 1 votes
You might want to use the "Grouping field".

* Add your date field to your views.
* Click the "Format Settings"

* Select your date field in "Group Field".

* Tick the "Use rendered output to group rows".
* Tick the "Remove tags from rendered output".
* Change the date format to "Y".

* Save.

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


title: Custom Module Configuration not working

text:
# Question
Title: Custom Module Configuration not working
I have the following file.

> modules/custom/test\_module/config/install/test\_module.settings.yml

```
test_module.settings:
    message: 'Hello'
    langcode: 'en'

```

But I am not able to get the following value.

```
$config = \Drupal::config('test_module.settings');
print $config->get('message');

```

I have referred this link.

**UPDATE:**

Removing `test_module.settings:` line solved the issue.

# Answer
> 2 votes
```
test_module.settings:
    message: 'Hello'
    langcode: 'en'

```

Is that really content of your file? It should only contain:

```
message: 'Hello'
langcode: 'en'

```

Also, Configuration on config/install is only imported when a module is *installed*. If it is an existing module, you need to re-install it or write an update function to initialize the configuration.

You can always use something like print\_r($config-\>get()) to see everything in your config file.

---
Tags: 8, configuration
---


# Question
Title: How do I create a content entity with bundle of a configuration entity in here path?
We are currently working on a Drupal 8 project in conjunction with a PIM (MaPS). We need to use the MaPS Suite module, which allows to import MaPS data into Drupal. Unfortunately, the MaPS Suite module is not available in Drupal 8 (we contacted the developer, but the Drupal 8 port was stopped) and we are therefore trying to bring it to this version.

It has been a week since we started and we are confronted with a problem that seems simple, but that we cannot solve.

In the MaPS Suite module there is a profile system that allows us to create multiple connection profiles to MaPS servers. We have converted this profile management to a configuration entity.

And for each profile, it's possible to create converters, each converter allows (basically) to do the mapping between a MaPS field and a Drupal field. For those converters that are specific to a profile, we created a content entity that bundled the configuration entity profile.

For that, we went through the automatic generation in Drupal console, unfortunately this generation does not do exactly what we needs, it creates a page of configuration on a side and a page of content on the other. We must have the content in the configuration (for ergonomics).

What we want is this:

* admin/maps-suite/profiles (profile collection)
* admin/maps-suite/profile/add
* admin/maps-suite/profile/{maps\_import\_profile}/edit
* ...
* admin/maps-suite/profile/{maps\_import\_profile}/converters (converter collection)
* admin/maps-suite/profile/{maps\_import\_profile}/converter/add
* admin/maps-suite/profile/{maps\_import\_profile}/converter/{maps\_import\_converter}/edit
* ...

When we do this, we are able to create our content entity, but once done, it is impossible to run the pages collection, edit and other where converters entities are present. The {maps\_import\_profile} parameters are not retrieved from the collection page and others, so it is impossible to create the edit links and the rest.

The error we get is the following:

First eror resolved with adding parameters in MapsImportConverterHtmlRouteProvider:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("maps\_import\_profile") to generate a URL for route "entity.maps\_import\_converter.collection". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 180 of core\lib\Drupal\Core\Routing\UrlGenerator.php).

New error:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("maps\_import\_profile") to generate a URL for route "entity.maps\_import\_converter.edit\_form". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 180 of core\lib\Drupal\Core\Routing\UrlGenerator.php).

This is part of the code we are using.

### Profile

```
/**
 * Defines the Maps import profile entity.
 *
 * @ConfigEntityType(
 *   id = "maps_import_profile",
 *   label = @Translation("Maps import profile"),
 *   label_collection = @Translation("Profiles"),
 *   handlers = {
 *     "form" = {
 *       "add" = "Drupal\maps_import\Form\MapsImportProfileForm",
 *       "edit" = "Drupal\maps_import\Form\MapsImportProfileForm",
 *       "delete" = "Drupal\maps_import\Form\MapsImportProfileDeleteForm",
 *       "export" = "Drupal\maps_import\Form\MapsImportProfileExportForm",
 *       "importer" = "Drupal\maps_import\Form\MapsImportProfileImporterForm"
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\maps_import\MapsImportProfileHtmlRouteProvider",
 *     },
 *     "list_builder" = "Drupal\maps_import\MapsImportProfileListBuilder",
 *   },
 *   admin_permission = "administer maps suite",
 *   config_prefix = "maps_import_profile",
 *   bundle_of = "maps_import_converter",
 *   entity_keys = {
 *     "id" = "profile",
 *     "label" = "label",
 *     "fetchMethod" = "fetchMethod",
 *     "configurationFile" = "configurationFile",
 *     "objectsFile" = "objectsFile",
 *     "token" = "token",
 *     "publicationId" = "publicationId",
 *     "url" = "url",
 *     "webTemplate" = "webTemplate",
 *     "options" = "options",
 *     "rootObjectId" = "rootObjectId",
 *     "presetGroupId" = "presetGroupId",
 *     "mediaDirectory" = "mediaDirectory",
 *     "mediaAccessibility" = "mediaAccessibility",
 *     "maxObjectsPerRequest" = "maxObjectsPerRequest",
 *     "maxObjectsPerOp" = "maxObjectsPerOp",
 *     "format" = "format",
 *     "enabled" = "enabled"
 *   },
 *   links = {
 *     "add-form" = "/admin/maps-suite/profile/add",
 *     "edit-form" = "/admin/maps-suite/profile/{maps_import_profile}/edit",
 *     "export-form" = "/admin/maps-suite/profile/{maps_import_profile}/export",
 *     "delete-form" = "/admin/maps-suite/profile/{maps_import_profile}/delete",
 *     "importer-form" = "/admin/maps-suite/profile/{maps_import_profile}/importer",
 *     "collection" = "/admin/maps-suite/profiles"
 *   }
 * )
 */

```

### Converter

```
/**
 * Defines the Maps import converter entity.
 *
 * @ingroup maps_import
 *
 * @ContentEntityType(
 *   id = "maps_import_converter",
 *   label = @Translation("Maps import converter"),
 *   bundle_label = @Translation("Maps import profile"),
 *   handlers = {
 *     "list_builder" = "Drupal\maps_import\MapsImportConverterListBuilder",
 *     "form" = {
 *       "default" = "Drupal\maps_import\Form\MapsImportConverterForm",
 *       "add" = "Drupal\maps_import\Form\MapsImportConverterForm",
 *       "edit" = "Drupal\maps_import\Form\MapsImportConverterForm",
 *       "delete" = "Drupal\maps_import\Form\MapsImportConverterDeleteForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\maps_import\MapsImportConverterHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "maps_import_converter",
 *   admin_permission = "administer maps suite",
 *   entity_keys = {
 *     "id" = "id",
 *     "bundle" = "type",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *   },
 *    links = {
 *     "add-form" = "/admin/maps-suite/profile/{maps_import_profile}/converter/add",
 *     "edit-form" = "/admin/maps-suite/profile/{maps_import_profile}/converter/{maps_import_converter}/edit",
 *     "delete-form" = "/admin/maps-suite/profile/{maps_import_profile}/converter/{maps_import_converter}/delete",
 *     "collection" = "/admin/maps-suite/profile/{maps_import_profile}/converters",
 *   },
 *   bundle_entity_type = "maps_import_profile",
 * )
 */

```

The bundle is correct on the converter entities but we fail to make sure, once the entity is created, to use its bundle for route generation.

Edit 1 (fix the first error): As we use a config and content entity, there is default routing with custom MapsImportConverterHtmlRouteProvider that extends AdminHtmlRouteProvider. We were able to add the parameters in all the routes of the entity to be converted, this pass the first error for collection but a new one appaer. I put the error above. I put the entire ConfigEntity and ContentEntity above, and here is the MapsImportConverterRouteProvider :

```
<?php

namespace Drupal\maps_import;

use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
use Drupal\Core\Entity\Controller\EntityController;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Symfony\Component\Routing\Route;

/**
 * Provides routes for Maps import converter entities.
 *
 * @see \Drupal\Core\Entity\Routing\AdminHtmlRouteProvider
 * @see \Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider
 */
class MapsImportConverterHtmlRouteProvider extends AdminHtmlRouteProvider {

  /**
   * {@inheritdoc}
   */
  public function getRoutes(EntityTypeInterface $entity_type) {
    $collection = parent::getRoutes($entity_type);

    $entity_type_id = $entity_type->id();

    $routes = $collection->all();
    foreach ($routes as $route_id => $route) {
      // Use the add form handler, if available, otherwise default.
      $operation = 'default';
      if ($entity_type->getFormClass('add')) {
        $operation = 'add';
      }
      $route->addDefaults(['entity_type_id' => $entity_type_id]);

      // If the entity has bundles, we can provide a bundle-specific title
      // and access requirements.
      $expected_parameter = $entity_type->getBundleEntityType() ?: $entity_type->getKey('bundle');
      // @todo: We have to check if a route contains a bundle in its path as
      //   test entities have inconsistent usage of "add-form" link templates.
      //   Fix it in https://www.drupal.org/node/2699959.
      if (($bundle_key = $entity_type->getKey('bundle')) && strpos($route->getPath(), '{' . $expected_parameter . '}') !== FALSE) {
        $route->addDefaults(['_title_callback' => EntityController::class . '::addBundleTitle']);
        // If the bundles are entities themselves, we can add parameter
        // information to the route options.
        if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
          $bundle_entity_type = $this->entityTypeManager->getDefinition($bundle_entity_type_id);

          $route
            // The title callback uses the value of the bundle parameter to
            // fetch the respective bundle at runtime.
            ->addDefaults(['bundle_parameter' => $bundle_entity_type_id])
            ->addRequirements(['_entity_create_access' => $entity_type_id . ':{' . $bundle_entity_type_id . '}']);

          // Entity types with serial IDs can specify this in their route
          // requirements, improving the matching process.
          if ($this->getEntityTypeIdKeyType($bundle_entity_type) === 'integer') {
            $route->addRequirements([$entity_type_id => '\d+']);
          }

          $bundle_entity_parameter = ['type' => 'entity:' . $bundle_entity_type_id];
          if ($bundle_entity_type instanceof ConfigEntityTypeInterface) {
            // The add page might be displayed on an admin path. Even then, we
            // need to load configuration overrides so that, for example, the
            // bundle label gets translated correctly.
            // @see \Drupal\Core\ParamConverter\AdminPathConfigEntityConverter
            $bundle_entity_parameter['with_config_overrides'] = TRUE;
          }
          $parameters = $route->getOption('parameters');
          $parameters[$bundle_entity_type_id] = $bundle_entity_parameter;
          $route->setOption('parameters', $parameters);
        }
      }
    }

    return $collection;
  }

}

```

Edit 2 (fix the second error): After many tests, we managed to run the collection page of the converters. To do this, in the MapsImportConverterListBuilder, we had to add the following:

```
public function getDefaultOperations(EntityInterface $entity) {
  $operations = parent::getDefaultOperations($entity);

  foreach($operations as &$operation) {
    $operation['url']->setRouteParameter('maps_import_profile', $entity->getType());
  }

  return $operations;
}

```

The last problem that persists now is to be able to filter the converters correctly on the collection page. As seen above, the collection page can be found here: \- admin/maps-suite/profile/{maps\_import\_profile}/converters This page works but show all the converters, not only those with the {maps\_import\_profile} provided. I already know that we need to use the getEntityIds function to achieve this but i can't figure out how to retrieve the parameters from the route in this function.

# Answer
> 0 votes
After a while, we finally managed to get what we wanted. For this, here is the list of errors and their correction:

Error:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("maps\_import\_profile") to generate a URL for route "entity.maps\_import\_converter.collection". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 180 of core\lib\Drupal\Core\Routing\UrlGenerator.php).

Correction:

As we use a config and content entity, there is default routing with custom MapsImportConverterHtmlRouteProvider that extends AdminHtmlRouteProvider. We were able to add the parameters in all the routes of the entity to be converted, this pass the first error for collection but a new one appaer. I put the error above. Here is the MapsImportConverterRouteProvider :

```
<?php

namespace Drupal\maps_import;

use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
use Drupal\Core\Entity\Controller\EntityController;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Symfony\Component\Routing\Route;

/**
 * Provides routes for Maps import converter entities.
 *
 * @see \Drupal\Core\Entity\Routing\AdminHtmlRouteProvider
 * @see \Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider
 */
class MapsImportConverterHtmlRouteProvider extends AdminHtmlRouteProvider {

  /**
   * {@inheritdoc}
   */
  public function getRoutes(EntityTypeInterface $entity_type) {
    $collection = parent::getRoutes($entity_type);

    $entity_type_id = $entity_type->id();

    $routes = $collection->all();
    foreach ($routes as $route_id => $route) {
      // Use the add form handler, if available, otherwise default.
      $operation = 'default';
      if ($entity_type->getFormClass('add')) {
        $operation = 'add';
      }
      $route->addDefaults(['entity_type_id' => $entity_type_id]);

      // If the entity has bundles, we can provide a bundle-specific title
      // and access requirements.
      $expected_parameter = $entity_type->getBundleEntityType() ?: $entity_type->getKey('bundle');
      // @todo: We have to check if a route contains a bundle in its path as
      //   test entities have inconsistent usage of "add-form" link templates.
      //   Fix it in https://www.drupal.org/node/2699959.
      if (($bundle_key = $entity_type->getKey('bundle')) && strpos($route->getPath(), '{' . $expected_parameter . '}') !== FALSE) {
        $route->addDefaults(['_title_callback' => EntityController::class . '::addBundleTitle']);
        // If the bundles are entities themselves, we can add parameter
        // information to the route options.
        if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
          $bundle_entity_type = $this->entityTypeManager->getDefinition($bundle_entity_type_id);

          $route
            // The title callback uses the value of the bundle parameter to
            // fetch the respective bundle at runtime.
            ->addDefaults(['bundle_parameter' => $bundle_entity_type_id])
            ->addRequirements(['_entity_create_access' => $entity_type_id . ':{' . $bundle_entity_type_id . '}']);

          // Entity types with serial IDs can specify this in their route
          // requirements, improving the matching process.
          if ($this->getEntityTypeIdKeyType($bundle_entity_type) === 'integer') {
            $route->addRequirements([$entity_type_id => '\d+']);
          }

          $bundle_entity_parameter = ['type' => 'entity:' . $bundle_entity_type_id];
          if ($bundle_entity_type instanceof ConfigEntityTypeInterface) {
            // The add page might be displayed on an admin path. Even then, we
            // need to load configuration overrides so that, for example, the
            // bundle label gets translated correctly.
            // @see \Drupal\Core\ParamConverter\AdminPathConfigEntityConverter
            $bundle_entity_parameter['with_config_overrides'] = TRUE;
          }
          $parameters = $route->getOption('parameters');
          $parameters[$bundle_entity_type_id] = $bundle_entity_parameter;
          $route->setOption('parameters', $parameters);
        }
      }
    }

    return $collection;
  }

}

```

Error:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("maps\_import\_profile") to generate a URL for route "entity.maps\_import\_converter.edit\_form". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 180 of core\lib\Drupal\Core\Routing\UrlGenerator.php).

Correction:

After many tests, we managed to run the collection page of the converters. To do this, in the MapsImportConverterListBuilder, we had to add the following:

```
public function getDefaultOperations(EntityInterface $entity) {
  $operations = parent::getDefaultOperations($entity);

  foreach($operations as &$operation) {
    $operation['url']->setRouteParameter('maps_import_profile', $entity->getType());
  }

  return $operations;
}

```

We had to make similar changes in editing, deleting, and so on.

Last problem:

> In the Collection page, all converters were displayed, not just those of the current bundle.

Correction:

To solve this problem we had to remove the management of the collection of the entity to create ourselves a controller and be able to add the parameters. For this we used the Block module with BlockListingController.

---
Tags: entities
---


# Question
Title: Disable search form in nav from collapsing
Is there a way I can have my search form in nav bar not collapsed when screen size decreases? I'm using bootstrap on Drupal 7

# Answer
You can change your markup using the page.tpl.php

* Copy the `page.tpl.php` file from `/bootstrap/templates/system` to your theme.
* Edit the `page.tpl.php` that you've copied.
* Move the line 108 - 110 below / above the `navbar-collapse collapse` div.

* Create a new div.
* Put the code from line 108 - 110 into the new div.
* Save
* The changes should be like the screenshot below.

* Flush cache
> 0 votes

---
Tags: search, navigation
---


# Question
Title: In Drupal 7 how do you output array objects to be view able in watchdog error reports?
For some reason I couldn't use devel to debug output object arrays. Is there a way to output the array data to watchdog error reporting? This would also solve the issue of having to install or enable another module.

# Answer
> 17 votes
You can use watchdog but the message part should be translatable, so any variables should use placeholders defined in the variables array. Check out format\_string to see how these should work.

```
watchdog(
  'my_module_name',
  'Here is the printed variable: <pre>@placeholder_name</pre>',
  array('@placeholder_name' => print_r( $my_variable, TRUE)),
  WATCHDOG_INFO
);

```

Also, convention dictates that the first parameter, `$type`, should be the module name calling watchdog.

# Answer
> 10 votes
You can do the following to output array data to be viewed in watchdog:

```
// Directly use values.
watchdog("log_name", '<pre>' . print_r( $my_object, true) . '</pre>');

```

Then goto /admin/reports and look for "log\_name".

# Answer
> 2 votes
If you don't mind enabling another module, though, I wrote Object Log for just this kind of thing:

https://www.drupal.org/project/object\_log

It's lightweight, easier to use in code, more user-friendly to view, and doesn't get pushed down the log as other log events are recorded.

---
Tags: 7, debugging, log-messages
---


# Question
Title: Correct analysis for "Mismatched entity and/or field definitions"
Drupal 8 sometimes displays a warning in site status

> Mismatched entity and/or field definitions

There has already been a question about this and the answer is to run `drush entity-updates`. I can't find any description of a solution directly from the GUI.

I have run the command several times and it works fine. But I don't understand the point of Drupal printing this warning, rather than Drupal solving the problem automatically (by executing whatever the entity-updates command does).

Please can anyone tell me

1. Is there any analysis that I should do before running entity-updates?
2. Is there any reason I shouldn't write a cron hook that will call entity-updates automatically?
3. Should I raise an issue against Drupal core to request that Drupal runs the clean-up automatically rather than printing a warning?

# Answer
> 2 votes
Thanks to 4k4 and Clive and following the link I think I can now write up the answer to my question.

* This Drupal Change Record (and more detail) documents that module developers should write hook\_update functions for entity updates. So if you get the "mismatched" warning after a contrib module update then **it's a bug** in that module and you should not apply to update to the live site.
* This question explains that entity-updates is a developer tool. If you are a developer working on a test site you may see the "mismatched" warning whilst making changes. You will run entity-updates when you are ready.

So the answer to my questions 2 and 3 is **no**.

---
Tags: 8
---


title: Where is the Rules Evaluation Log?

text:
# Question
Title: Where is the Rules Evaluation Log?
Where is the Rules Evaluation Log? I need to view it but I can't find it.

# Answer
There are typically 2 ways of Rules debugging, as further detailed below.

# 1. Rules Evaluation Log

Within the Rules **settings** (located at `admin/config/workflow/rules/settings` in your site), experiment a bit with the debugging facilities that come with the Rules module. More specifically, within the "**debugging**" section of that page, you should change the value of "*Show debug information*" to "*Always*". Be aware also of what's mentioned at the end of that same debugging section, i.e.:

> Debug information is only shown when rules are evaluated and is visible for users having the permission Access the Rules debug log.

So double check (at `admin/people/permissions#module-rules`) that for the userid you're using you've granted the required permission.

### Example of a Rules evaluation log

Here is an example of such Rules Evaluation Log:

### URL to view the Rules Evaluation Log

There is not really "an" URL you can go find this log. Such Rules Evaluation log only gets displayed whenever "some Rules event happens" (for a rule that is enabled, disabled doesn't count ...). Like in my sample screenprint: that log is shown right after some user performed a login (because in this site there was an enabled rule that used event "User logged in"). Also, assume you just have 1 enabled rule, using a Rules Event X, then you need to "make something happen" in your site that triggers that Rules Event (if the event is not triggered, then you wouldn't see any logging data).

# 2. Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value". That's not within Rules Conditions (as in your question), but if you add that as your first Rules Action, then you can be sure that the values displayed are identical to the value of these variables at the end of the Rules Conditions.

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

# 3. Resources

PS: I'm assuming this question is about D7.
> 1 votes

---
Tags: rules
---


title: How do I display empty fields?

text:
# Question
Title: How do I display empty fields?
I have redesigned the layout of the page using the display suite module. When I go to the node, I see empty fields are not there. I like to see the empty fields on the node. I have been looking for the settings and I could not find it. How can I display empty fields?

# Answer
Display suite accepts custom templates that override the default layouts.

An easy way to achieve what you want if you are using a custom theme is add a custom template override for whatever DS layout - 2 column for example - you are trying to change.

By default I think the DS templates don't show empty fields.

eg in twig:

```
{% if user_picture is not empty %}
  {{ user_picture }}
{% endif %}

```

If you always them them to be rendered - or at least some layout code around them you can add custom markup.

This article discusses the basics. It is about drupal 7 but drupal 8 matters are discussed in the comments below.
> 1 votes

# Answer
I never did it I have a small though...

Write a customer formatter (module /custom\_formatters) for this field which outputs for the length of the field &nsbp;

Another option is maybe to add custom tokens which a writing blank spaces and set the initial value to this token.
> 0 votes

---
Tags: display-suite
---


title: Registration form in popup in drupal 8

text:
# Question
Title: Registration form in popup in drupal 8
I have to show log in and registration form in popup in drupal 8 website. I had check for module but I did not find any module.

can anyone help me ?

# Answer
> 0 votes
You Can take a look on Login Popup module.

This module will provide simple Login and Register link as a block plugin, which will load the Drupal Login form and Register form in a popup.

# Answer
> 0 votes
When I have had to do such things in a custom theme I have created a popup with CSS/JS (or Bootstrap to be honest) in a relevant template file and put a region in the popup which you populate with whatever you want.

---
Tags: 8, users
---


title: What is the system log and where is it?

text:
# Question
Title: What is the system log and where is it?
at admin/config/workflow/rules/settings one can configure settings for logging related to rules and it states that: "Evaluations errors are logged to the system log". What and where exactly is the 'system log'?

# Answer
By default the logs are saved at `/admin/reports/dblog` for which the `dblog` module in the core is responsible. More about `dblog` : https://www.drupal.org/docs/8/core/modules/dblog/overview

You can also have the logs stored on the file system by enabling the `syslog` module (also in core). More about `syslog` : https://www.drupal.org/docs/8/core/modules/syslog/overview

It is recommended that you should not use the dblog module if you need to log messages more frequently as it does a write operation to the database.
> 1 votes

---
Tags: rules
---


# Question
Title: How to add a simple online payment transaction?
My client ask me to add a simple online transaction system to his drupal 7 site. Payment amount for his users are actually fixed for example 100$, 250$ and 350$. Also he wants link that transaction with his local bank and as optional he wants add the pay-pal also.

Could anyone please tell me how can I start to integrating this? I checked the drupal-ecommerce kicksart but I believe thats more advanced to this. However if anyone can instruct me to optimize it's requirement my client needs then it would be helpful.

I also checked Drupal https://drupal.org/project/simple\_payments but since it's not supporting for the drupal 7 I've not much read on it.

# Answer
> 4 votes
I agree that Commerce Kickstart is too advanced for what you need. You'd end up spending a lot of time configuring "off" a lot of stuff just to give your users a simple checkout.

I've setup several simple custom payment solutions for Drupal sites using **Webform** and **Stripe.com**.

Here's an example of a Stripe/Webform component: https://drupal.org/sandbox/jlyon/1472346

Basically you'd build out the component that captures their CC info and submits it to Stripe via javascript, then run the charge on the server side using the token that Stripe gives you. This gets you out of the bulk of PCI compliance (you just need to have SSL enabled and ensure that you don't let any CC info be sent to your server). Since Webform is easy to use and you can add whatever form elements you'd like, you can quickly capture the right customer info and set the "product" or dollar amount in a dropdown field, then run the charge in a `_validate()` function.

Not quite plug and play but also not a lot of development time to get a solid working solution.

**Edit:** You mentioned PayPal – you could provide that as an alternate purchase opition and use a simple paypal button to send them on their merry way; also https://drupal.org/project/webform\_paypal

**Edit 2:** After thinking about Ryan's comment a bit, I would suggest you first grab Commerce module and tinker with it for a while. You may find that it gets you what you need. I have really enjoyed implementing some custom, lean payment systems using Stripe where a traditional "checkout" workflow wasn't appropriate, but there's no need to reinvent the wheel if it fits.

# Answer
> 3 votes
The Payment module provides a simple to use payment processing API for Drupal 7.

# Answer
> 0 votes
You may want to consider the Webform Stripe module which provides a lightweight, powerful integration between Webform and Stripe. From the project page:

> Webform Stripe adds super simple Stripe integration to Webforms, so that submissions can be "purchased".
>
> With this, you can use webforms for event registrations, online donations, or even for simple products where you need to gather additional information from a user.
>
> It uses Stripe Checkout to collect payments as the form is submitted.
>
> There are lots of ways to collect payment for Webforms. Most of them are difficult or require lots of modules. This is super simple solution. If you require more complex workflows or integration with your store, consider the myriad of options available for Commerce, Ubercart, or Payment.

# Answer
> 0 votes
As a non-programmer and having looked at the myriad of ways, for a simple solution I'd recommend Webform Stripe - unless it is too simple for your needs.

My need is predominantly to collect payment over the phone but I can also use it for clients to purchase fixed price service.

---
Tags: 7
---