title: Change machine name of system block

text:
# Question
Title: Change machine name of system block
I'm attempting to edit page restrictions on the 'Main Page Content' block, however I'm not able to save any changes to the block because it complains about the machine name having capital letters in it.

The machine name for the block is THEME\_content. I'm assuming because the theme name has capital letters in it. However because of this I can't make any changes to it, since it checks the machine name upon saving. There is a text field for the machine name but it does not allow me to edit it. Is there anyway I can change the machine name? Or make it so that I can save this block despite the name?

# Answer
**1.** First of all, The step you are showing, at that step you can easily change the machine-name, See in following image, where I have created the block 'Main Page Content' and it is not allowing me to go ahead, before changing the block machine-name. Hence, you can easily change the machine-name here. Hence there is no problem in editing the machine-name.

*Secondly, if system is saying, you can not use capital letter, then simply you can't as system designed in that way.*

>

**2.** **`Main Page Content`** Why you want to give your block name `Main Page Content` title, Block with same name with machine-name theme\_content has already been provided by the default Drupal 8. So, why you wan to create the another block with same `title` and same kind of `machine-name`. That block(Main Page Content) is used for displaying the main content which is not supposed to be changed. If you want just create the other custom block and place it in CONTENT region.

**3.** **Once the machine-name is stored in the database, practically you can't change that.** please read the accepted answer of this Question How do I change the machine name of a field once it's been created.

**4.** **Till which step you can edit machine-name:** After creating the block and before final saving, you can see the `edit` link in the following image. So at that time you can change the machine-name. And before placing it in the region. Once you places block and it gets enabled, after that you can not change the machine-name.

>
> 2 votes

# Answer
I think this is a bug in Drupal 8. I am having the same problem... I attempted to uncheck the sitename in the system block, but found I could not save the change. I am unable to edit the field marked in red. I have capitol letters in the sitename (I have my reasons), and Drupal should be converting those to lowercase before assigning the machine name. Normally it does this elsewhere. But in this case, it fails to do so, thus creating an irreconcilable error. You are stuck with the error for this block until the bug is fixed.

You can, however, disable that block on the "Structure/Block-Layout" page, and create a new one that has the same effect, for instance, presenting the site logo as navigation to the home page, but leaving off the site name.

You can inspect your site as it is now -- (Ctrl+U) or right-click/Inspect -- to see what you want the code to look like in that new block.

Once you create the new logo block, click the tab for Block Layout, then press "Place block" next to the navigation region. Select your new block, and you should be good to go.
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: Default Redirect after login based on destination
I have custom routing and a user controller in a module that redirects authenticated users to a private area on a site.

It works fine when users are coming from the login page - redirects them to a dashboard at a custom user page - but I would like users to continue to the page they are requesting if they come to the site from a link.

It is common for users to share links to internal content and they are then having to log in and get to the link from their dashboard which is causing some annoyance.

I have reasonably simple routing for the user page and a controller in my module that redirects users to their `userPage`. Is their a way to have this not redirect depending on the link they are requesting?

# Answer
> 2 votes
You mite need to add 'destination' query parameter for shared link.

For example: `https://www.drupal.org/user/login?destination=search/site/destinations`

# Answer
> 2 votes
If the pages are giving an access denied message and you want them to login first then it sounds like you might want r4032login

As the project page says:

> Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message that reads:
>
> "Access denied! You must login to view this page."
>
> Also, the desired page is appended in the url query string so that, once login is successful, the user is taken directly where they were originally trying to go.

---
Tags: 8, users, redirection
---


# Question
Title: Entity Reference Views - Contextual Filters - Administrator override
I have an Entity reference field View with contextual filter with Logged in user ID . The result of this view could be seen by the user only if he/she added some data. That is fine.

I would like to use the same Entity reference field View, so that administrator can view all the results without any restriction.

How can we achieve this. Thanks for the help.

# Answer
> 0 votes
I'm not really sure why this works but anyways.. It seems to be what you want.

You'll need Views Contextual Filters OR.

In my test, I used the contextual filter for author UID. So your entity reference field would only shows nodes created by the current user.

1. In your view, add the `Content: Author` relationship (don't check required) and `Content: Author uid` contextual filter (provide default: current user).
2. Enable `Contextual filters OR` in Query settings under Advanced.
3. Add a second contextual filter for `Content: Author uid` (provide default: current user)
4. Under *More* at the bottom of the filter, click **exclude**.

When added this an entity reference field, normal users only see nodes they've created but as admin, I see every node on the site. Weird but it works.

# Answer
> 0 votes
In Drupal 8 I was able to do this without any contrib module like contextual filters OR.

1. add the Authored By contextual filter for your entity type
2. choose provide default value... from logged in user
3. below in the "when value provided" section select "specify validation criteria
4. For validator select User ID
5. check "restrict user based on role"
6. select your NON-ADMIN roles
7. for "Action to take if filter value does not validate" select "display all results"

So if viewed by the non-admins is will show only where the logged in user id matches the entity owner. For admins it will show all.

---
Tags: views, entities
---


# Question
Title: Display Only the Product Add to Cart Button
Drupal 8.4.2

On both the `commerce-product` and the `node--product` level, I can get the add to cart button to show, but it also renders the `product variation` fields as well.

If I have content that does not have variations and only a single price, how can I render just the "add to cart button" in the commerce form?

I've been all through config via the admin panel and feel I am just missing something obvious???

My question would be: How do you render just the add to cart button on the product level, or node level (via reference) via the admin panel?

# Answer
Yes the link above resolved my question: Where is the "add to cart" configuration?.

There is a sub-menu link that I was missing.

This allowed me control of the display of the form items on both the product and node level. With this I am able to choose to show the variations and quantity fields. Thanks Patrick Kenny!
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: When should I create a service or a utility function?
I had this question in mind along all the last week: When I should create a service or an utility function?

In the Drupal Core we have both Services and Utility functions, but I can't find the distinction between them (when I need to create a service or when I need to create an utility function).

I will take as example the Modules Weight module where I have the InternalFunctions class.

```
<?php

namespace Drupal\modules_weight\Utility;

class InternalFunctions {

  public static function prepareDelta($weight) {
    $delta = 100;

    $weight = (int) $weight;

    if ($weight > $delta) {
      return $weight;
    }

    if ($weight < -100) {
      return $weight * -1;
    }

    return $delta;
  }

  public static function modulesList($force = FALSE) {
    $modules = [];
    $installed_modules = system_get_info('module');

    $config_factory = \Drupal::service('config.factory');

    if ($force) {
      $show_system_modules = TRUE;
    }
    else {
modules.
      $show_system_modules = $config_factory->get('modules_weight.settings')->get('show_system_modules');
    }

    $modules_weight = $config_factory->get('core.extension')->get('module');

    foreach ($installed_modules as $filename => $module_info) {
      if (!isset($module_info['hidden']) && ($show_system_modules || $module_info['package'] != 'Core')) {
        $modules[$filename]['name'] = $module_info['name'];
        $modules[$filename]['description'] = $module_info['description'];
        $modules[$filename]['weight'] = $modules_weight[$filename];
        $modules[$filename]['package'] = $module_info['package'];
      }
    }
    uasort($modules, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);

    return $modules;
  }

}

```

In this class I have two static functions but they are both utility functions or `prepareDelta()` is an utility function and `modulesList()` should be in another class and have a service?

The only difference that I found at this time is that inside the namespace Drupal\Component\Utility (where you will see a lot of utility fucntions) none of them use inside a service and usually a service use another services inside (I don't have review all the services to validate this).

So, when I should create a service or an utility function?

# Answer
> 8 votes
In general use services. See the following blog post when it is OK to use static utility functions:

> **So never use static?**
>
> Well no, there are valid use cases. One is that if you have a list of pre defined items static can help reduce memory since it will be on class level and not in any instances.
>
> Other cases are utility methods which do not require outside dependencies, for instance a slugify method.
>
> ```
> <?php
> class Util
> {
>     public static function slug($string)
>     {
>         return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $string)));
>     }
> }
>
> ```
>
> The slug method only does a very well defined behavior. It is easy to take the behavior into account in unit tests and I would not be too worried when I see this call.
>
> These methods can even be unit tested since they do not require initialization.

Source: https://stovepipe.systems/post/avoiding-static-in-your-code

(The amount of static code now in Drupal is because of the transition from procedural D7 code, so don't use Drupal in the current state as example.)

---

About the example from the question, the rest of the utility class (not shown in the question)

```
<?php

namespace Drupal\modules_weight\Utility;

/**
 * Provides module internal helper methods.
 *
 * @ingroup utility
 */
class InternalFunctions {

...

  /**
   * Return the modules list ordered by the modules weight.
   *
   * @param bool $force
   *   Force to show the core modules.
   *
   * @return array
   *   The modules list.
   */
  public static function modulesList($force = FALSE) {
    // If we don't force we need to check the configuration variable.
    if (!$force) {
      // Getting the config to know if we should show or not the core modules.
      $force = \Drupal::service('config.factory')->get('modules_weight.settings')->get('show_system_modules');
    }
    // Getting the modules list.
    $modules = \Drupal::service('modules_weight')->getModulesList($force);

    return $modules;
  }

}

```

calls the module own service in a static wrapper:

```
\Drupal::service('modules_weight')

```

This is probably because the utility class is used in legacy procedural code. In OOP code this is not necessary, here you should inject the service directly.

# Answer
> 11 votes
> Ken Rickard from Slack Drupal #contribute channel says: "I would create a service if you expect other modules (or other developers) to interact with that code. Utility methods are just private shortcuts for yourself."

Yes, a cool thing about services is that anyone can overwrite them. So if you want to give other people the ability to customise a particular piece of code. See Altering existing services, providing dynamic services.

In addition, you should make it a service if you need to do Mock test for PHP Unit testing. See Services and dependency injection in Drupal 8, see Unit testing more complicated Drupal classes.

Q & A:

Service unit test

Writing unit tests for a method that calls static methods from another class

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


# Question
Title: Empty value "- Select -" does not appear for select fields with states requirement
When I create a standard select box using the Drupal 7 form API, the first value (also the one selected on a fresh 'blank form') is `<option selected="selected" value="">- Select -</option>`. This value is not specified in the form definition and I am doing no form altering. (This is fine)

However, when I create a second select box that depends on the first using `#states`, it does not have any such default value. For complex forms with multiple dependencies this inconsistency is a problem.

An example form definition is as follows:

```
function sb_quickquote_test_form($form, &$form_state, $post=array()) {

  $fields['first_select'] = array(
    '#type'             => 'select',
    '#title'            => 'First select box',
    '#options'          => Array('First', 'Second', 'Third'),
    '#required'         => TRUE,
  );

  $fields['dependent_delect'] = array(
    '#type'             => 'select',
    '#title'            => 'Dependent select box',
    '#options'          => Array('Something', 'Another thing', 'Something else', 'Final thing'),
    '#states'           => Array(
      'visible' => Array('select[name=first_select]' => array('value' => '2')),
      'required' => Array('select[name=first_select]' => array('value' => '2')),
    ),
  );

  $fields['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $fields;
}

```

In this simple example, we have 2 select boxes and a submit button. The two select boxes are displayed as:

```
 ______________      ________________
| - Select - |v|    | Something    |v|
`--------------'    `----------------'
| - Select -   |    | Something      | <- no empty option
| First        |    | Another thing  |
| Second       |    | Something else |
| Third        |    | Final thing    |
 --------------      ----------------

```

(Because of the `#states` setting, the second select box only appears when the first select box has "Third" selected)

This inconsistency is causing problems in a situation where we are generating complex dynamic forms with inter-dependant fields.

Does anyone have any idea why the fields are being given inconsistent options and what the best approach is to work around the problem?

# Answer
> 25 votes
To force the "empty option", assign it with something like:

```
"#empty_option"=>t('- Select -'),

```

# Answer
> 3 votes
you need change this:

```
 'visible' => Array('select[name=first_select]' => array('value' => '2')),
 'required' => Array('select[name=first_select]' => array('value' => '2')),

```

select to ：input

the correct code is :

```
 'visible' => Array(':input[name="first_select"]' => array('value' => '2')),
 'required' => Array(':input[name="first_select"]' => array('value' => '2')),

```

# Answer
> 2 votes
To extend doterobcn answer you can also set the empty value (the key) of your empty option.

In Drupal 8:

```
$form['country'] = [
  '#type' => 'select',
  '#multiple' => FALSE,
  '#title' => t('Country:'),
  '#required' => FALSE,
  '#options' => $countries,
  '#default_value' => 'FR',
  '#empty_option' => t('- None -'),
  '#empty_value' => '_none',
];

```

Which will give :

```
<option value="_none">- None -</option>

```

---
Tags: 7, forms
---


# Question
Title: change an add entity route to a custom route in order to not use admin theme
I will start off by saying i have already studied these posts, to no avail:

Overriding an entity add/edit form through alterroute

How to load my Entity in Entity form

https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones

I am trying to alter my add-entity route to be not under /admin, as we want this form to use the default theme, not admin theme.

My module is 'project', my entity is 'project'. Here is my route in the project.routing.yml file:

```
mycompany.project.add_form:
  path: '/mycompany/project/add/{project_type}'
  defaults:
    _entity_form: 'project.default' #I have also tried custom form_mode here
    _title: 'Add Project'
  requirements:
    _permission: 'add project entities'

```

I get the error: Call to a member function id() on string in /Applications/MAMP/htdocs/sfchapter6nov2/core/lib/Drupal/Core/Entity/EntityForm.php on line 363

Yes, this error has been documented before, with posts such as the ones above. I believe my unique problem is because my entity has an entity type, ie a bundle. The {project\_type} is my bundle name. The EntityForm does not have an instance of the entity, and I cannot find where to create it.

Help and suggestions much appreciated! Mary Edith

# Answer
The problem is that now the route parameter is a string and so you generate the error. You need to upcast the route parameter to an entity (the config entity of the bundle):

```
  options:
    parameters:
      project_type:
        type: entity:project_type

```

More info https://www.drupal.org/docs/8/api/routing-system/parameter-upcasting-in-routes
> 1 votes

---
Tags: entities, routes
---


# Question
Title: Access RNG Event Configuration options programatically
I am creating a module that allows an admin type user to create multiple RNG events at one time. I have that functionality working now, the next step is to configure the events programatically.

I need to be able to:

1. Accept new registrations
2. Set up the email notification (and enable it)
3. Set maximum users
4. Set the registration type

I'm having a hard time finding these values, and I'm unsure how to proceed. Do I need to set up SQL queries to handle these, or can I access these values in another way?

Thanks!

# Answer
> 0 votes
Accept new registrations, maximum users, registration type are regular fields attached to the event entity. Use the regular entity field API to set those. Email notifications would require a bit more digging.

---
Tags: rng
---


title: How to add CSS to the module?

text:
# Question
Title: How to add CSS to the module?
I am very new to Drupal. I have an html form and I want to create a module that take the html of the form and create a table in the database and saves the form values in database.

what i have done i have created a form with form api (with `buildForm` method) my form is being rendered and i have converted it into Twig template (it is being shown in twig template), but first my CSS is not getting loaded.

My library file: `mymodulename.libraries.yml`

```
bootstrap:
  version: 1.x
  css:
    css/bootstrap.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

global-components:
  Version: 1.x
  css:
    css/baselayout.css: {}
    css/form.css: {}
    css/wisdom.css: {}

  js:
    js/jquery.smartmenus.min.js: {}
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

# Answer
> 1 votes
CSS lives one level further down in a libraries file; under `system`, `module` or `theme`. e.g.:

```
bootstrap:
  version: 1.x
  css:
    theme:
      css/bootstrap.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

---
Tags: theming, 8
---


# Question
Title: Is it possible to collect credit card info and address info on separate pages in Commerce 2?
I want my checkout flow to look like this:

1. Users enter their credit card information and press "Next."
2. Users enter their address information (customer profile), then press "Next."

In the default Commerce workflow, users enter their credit card info and address on the same page.

I want to split credit card info and address info into different pages.

How can I do this safely?

**Why do this?**

Because if a user makes an error when typing their address and validation fails, it also resets the credit card information. I want to have the user do the credit card and address info separately so if validation fails, they only have to re-input one or the other.

# Answer
> 5 votes
Creating a checkout flow plugin may solve your problem. Create a Plugin in your custom module like an example shown below:

```
namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutFlow;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowWithPanesBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @CommerceCheckoutFlow(
 *  id = "custom_checkout_flow",
 *  label = @Translation("Custom checkout flow"),
 * )
 */
class CustomCheckoutFlow extends CheckoutFlowWithPanesBase {

  /**
   * {@inheritdoc}
   */
  public function getSteps() {
    return [
      'login' => [
        'label' => $this->t('Login'),
        'previous_label' => $this->t('Return to login'),
        'has_order_summary' => FALSE,
      ],
      'card_info' => [
        'label' => $this->t('Card information'),
        'previous_label' => $this->t('Return to Card information'),
        'next_label' => $this->t('Continue to Card information'),
        'has_order_summary' => FALSE,
      ],
      'address_information' => [
        'label' => $this->t('Address information'),
        'previous_label' => $this->t('Return to Address information'),
        'next_label' => $this->t('Continue to Address information'),
        'has_order_summary' => FALSE,
      ],
      'review' => [
        'label' => $this->t('Review'),
        'has_order_summary' => TRUE,
      ],
    ] + parent::getSteps();
  }

}

```

After creating a plugin, you need to change the checkout flow settings for your order type.

**For more information visit:** https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-flow

---

## **Update**

CustomCheckoutFlow

```
<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutFlow;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowWithPanesBase;

/**
 * @CommerceCheckoutFlow(
 *  id = "custom_checkout_flow",
 *  label = @Translation("Custom checkout flow"),
 * )
 */
class CustomCheckoutFlow extends CheckoutFlowWithPanesBase {

  /**
   * {@inheritdoc}
   */
  public function getSteps() {
    return [
      'login' => [
        'label' => $this->t('Login'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => FALSE,
      ],
      'card_information' => [
        'label' => $this->t('Card information'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => TRUE,
      ],
      'order_information' => [
        'label' => $this->t('Order information'),
        'has_sidebar' => TRUE,
        'next_label' => $this->t('Continue to Order information'),
        'previous_label' => $this->t('Go back'),
      ],
      'review' => [
        'label' => $this->t('Review'),
        'next_label' => $this->t('Continue to review'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => TRUE,
      ],
    ] + parent::getSteps();
  }

}

```

Then create CheckoutPanes as shown below:

BillingInformation

```
<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use \Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\BillingInformation;

/**
 * Provides the billing information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_billing_information",
 *   label = @Translation("Billing information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class CustomBillingInformation extends BillingInformation {

}

```

PaymentInformation

```
<?php
namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation as PaymentInformationBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the payment information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_commerce_payment_information",
 *   label = @Translation("Custom Payment information"),
 *   display_label = @Translation("Payment information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class PaymentInformation extends PaymentInformationBase {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form = parent::buildPaneForm($pane_form, $form_state, $complete_form);

    // Add an after build callback in order to make modifications on the address form.
    $pane_form['#after_build'][] = [$this, 'paneFormAfterBuild'];

    return $pane_form;
  }

  /**
   * After build callback for the pane form.
   */
  public function paneFormAfterBuild(array $pane_form, FormStateInterface $form_state) {
    // Get billing form element. Where it is located depends on the payment method that is chosen.
    if (isset($pane_form['add_payment_method']['billing_information'])) {
      $billing_form = &$pane_form['add_payment_method']['billing_information'];
    }
    elseif (isset($pane_form['billing_information'])) {
      $billing_form = &$pane_form['billing_information'];
    }
    else {
      // No billing information found.
      return $pane_form;
    }

    // Get the address form element.
    $address_form = &$billing_form['address']['widget']['0']['address'];

    // Add element validation callback to autofill the address.
    $billing_form['#element_validate'] = array_merge(
      [[$this, 'profileSelectValidate']],
      \Drupal::service('element_info')->getInfoProperty('commerce_profile_select', '#element_validate', [])
    );

    // Set all address fields to non-required.
    foreach (Element::children($address_form) as $key) {
      $address_form[$key]['#required'] = FALSE;
    }

    // Hide the address form.
    $address_form['#access'] = FALSE;

    return $pane_form;
  }

  /**
   * Element validation callback for the profile select element.
   */
  public function profileSelectValidate(array &$element, FormStateInterface $form_state) {
    $billing_profile = $this->order->getBillingProfile()->get('address')->getValue();
    $form_state->setValue($element['address']['widget'][0]['address']['#parents'], $billing_profile[0]);
  }

}

```

PaymentProcess

```
<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentProcess as BasePaymentProcess;

/**
 * Provides the payment process pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_payment_process",
 *   label = @Translation("Custom Payment process"),
 *   default_step = "payment",
 *   wrapper_element = "container",
 * )
 */
class PaymentProcess extends BasePaymentProcess {

  /**
   * {@inheritdoc}
   */
  public function isVisible() {
    // This pane can't be used without the PaymentInformation pane.
    $payment_info_pane = $this->checkoutFlow->getPane('custom_commerce_payment_information');
    return $payment_info_pane->isVisible() && $payment_info_pane->getStepId() != '_disabled';
  }

}

```

After this set checkout panes for your custom checkout flow as shown in the image below:

Find full code at https://github.com/patilvishalvs/my\_checkout\_flow

---
Tags: 8, commerce
---


# Question
Title: How to override text field widget form in Drupal 8
In my project I am using maxlength module to display the message like 'Content limited to 100 characters, remaining: 20'. The module using the hook 'hook\_field\_widget\_third\_party\_settings\_form' and provide textboxes to add length size and count down message.

I want to alter this count down message for all the fields by using my own custom module. Please help on this ?

# Answer
> 1 votes
You can create you own widget for textfield you will use in your forms each time you need :

```
<?php

namespace Drupal\your_module\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextareaWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'your_widget_widget' widget.
 *
 * @FieldWidget(
 *   id = "your_module",
 *   label = @Translation("Your widget name"),
 *   field_types = {
 *     "string"
 *   }
 * )
 */
class YourWidget extends StringTextfieldWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'textfield',
      '#default_value' => $items[$delta]->value,
      '#placeholder' => $this->getSetting('placeholder'),
      '#maxlength' => $this->getFieldSetting('max_length'),
      '#attributes' => [
        'class' => ['js-text-full', 'text-full'],
      ],
    ];

    return $element;
  }

}

```

You probably have to override settingsForm() with your maxlength settings. You can do this for each widget type (textarea...)

Note that you can generate skeleton with this drupal command :

```
$ drupal generate:plugin:fieldwidget
$ drupal gpfw

```

---
Tags: hooks
---


# Question
Title: How to check if a user is logged in inside a view
I can easily check if a user is logged in in most templates by simply using a twig variable, or making a custom one myself. My issue is that I would like to be able to check if a user is logged in inside a custom text field in a view.

I used

```
{% if logged_in %}
     Test
{% endif %}

```

But it didn't seem to work. Also

```
{{ dump(logged_in) }}

```

came up null. Also I looked in the available options for context filters and relationships but nothing seemed to have anything to do with the current user. Only authors of the content. Is there a way to know if the user is logged in from a view?

I suspect that it might be possible with some preprocess hook for views but if that can be avoided by using an option in views that would be preferable.

For clarification this is a view that displays a list of articles. Each with an image, title, and a snippet of body text. The article node has a field deciding whether a user login is required. If the user login is required then the body text is replaced for anyone that isn't logged in.

UPDATE: I attempted adding the variable in a preprocess hook but that didn't seem to do anything either.

```
function mymodule_preprocess_views_view_field(&$variables){
    $variables['logged_in'] = (\Drupal::currentUser()->isAnonymous())?false:true;
}

```

But {{ dump(logged\_in) }} still came up null.

# Answer
> 1 votes
I managed to accomplish this task by creating my own custom view field plugin

in mymodule.views.inc I used

```
function mymodule_views_data() {

  $data['views']['table']['group'] = t('Current User');
  $data['views']['table']['join'] = [
    // #global is a special flag which allows a table to appear all the time.
    '#global' => [],
  ];

  $data['views']['logged_in'] = [
    'title' => t('Logged In'),
    'help' => t('Check if user is logged in'),
    'field' => [
      'id' => 'logged_in',
    ],
  ];

  return $data;
}

```

and then in /mymodule/src/Plugins/views/field/LoggedIn.php I had

```
<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("logged_in")
 */
class LoggedIn extends FieldPluginBase {

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);
        $this->field_alias = 'logged_in';
    }

    /**
     * {@inheritdoc}
     */
    public function usesGroupBy() {
        return FALSE;
    }

    /**
     * {@inheritdoc}
     */
    public function query() {
        // Do nothing -- to override the parent query.
    }

    /**
     * {@inheritdoc}
     */
    protected function defineOptions() {
        $options = parent::defineOptions();

        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {

        $logged_in = \Drupal\mymodule\Modules\CurrentUser::isLoggedIn();
        return $logged_in;
    }

}

```

Some of the contents of LoggedIn.php might not be necessary (not 100% sure) I was using another module as an example.

# Answer
> 0 votes
In D7 views supported distinctions between 2 views based on the Permissions/Roles settings per View.

I'm not sure this functionality exists in D8 of using 1 display over another depending on Permission settings of the View.

In D7 and using Display Suite you can set a view\_mode different for the 1st or Nth view row returned by Views. It was a submodule of Display Suite. Using something like DS in D8 should to allow you to modify the View Mode of rows in the view result set depending on the rows' special flag value.

# Answer
> 0 votes
I see you've already achieved what you needed but I think the easiest way is to copy over the field's tpl template from the views folder, rename it to the name provided under "Information" in the view's settings put it in your theme's folder, and add

`global $user; if($user->uid) {`

The other option is a bit of views trickery using the "No results behaviour" option in a field's settings. You would have two views with their visibility controlled by blocks / panels / context etc., one for logged in users with no changes, and one for anonymous users where you exclude the body field from display, add the Boolean field for being logged in, click "Treat 0 as empty", and use the replacement pattern to display the body field if empty.

# Answer
> 0 votes
I posted a module for this (link below) based on Matt's answer, but with a change in the way the render function is done:

https://github.com/andileco/logged\_in

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


# Question
Title: My Custom drupal 8 module does not shown in modules list
I'm developing my first drupal 8 module, a custom migration module, the `info.yml` file is written as follow :

```
name : Drupal Center Custom Migrate
description : This module provides custom migration configuration and plugins to migrate my custom site from drupal 6.
type : module
core : 8.x

package : Custom migrate
dependencies :
  - migrate
  - migrate_plus
  - migrate_tools
  - migrate_upgrade
  - migrate_drupal

```

The above code is saved as `dc_custom_migrate.info.yml` . This module also provides some config migration file and some custom source plugins.

The problem is my custom module is not shown up in modules list.

I can't figure it up where am I doing wrong!!!

PS. I'm developing in windows 10 environment and using Aquia Dev Desktop 2 as web service simulator.

# Answer
Remove the spaces between the identifiers and colons:

```
name: Drupal Center Custom Migrate
description: This module provides custom migration configuration and plugins to migrate my custom site from drupal 6.
type: module
core: 8.x

package: Custom migrate
dependencies:
  - migrate
  - migrate_plus
  - migrate_tools
  - migrate_upgrade
  - migrate_drupal

```

Then it'll work.

See the YAML rules for more info.
> 3 votes

---
Tags: 8, .info
---


# Question
Title: All content types are using an incorrect /edit url
I’ve run into a really strange issue. Just recently every new node I create, of any content type, has a nonsensical /edit url. Instead of /node/\[nid\]/edit, it’s /using-library/frequently-asked-questions20/edit (and then next one I create will be /using-library/frequently-asked-questions21/edit). The actual alias for the node is /rooms-studios/test. I’m attaching a screenshot. Has anyone seen something like this? What could be causing it?

The problem was happening in my production environment, but not in my test environment. And then I pulled the production db into test and NOW it's happening in my test env. But I can’t find any sign of that edit url in my db. I found a handful of nodes that were created in 2015 that also have this strange /edit url. When I deleted aliases and cleared caches, it seemed to resolve itself until I did a Bulk Update and then they're back to the weird url.

I'm using Pathauto 7.x-1.2, but there's no setting to update the /edit url and, as I understand it, another submodule is required to change the edit url.

# Answer
> 0 votes
Ah, I've figure it out. I had custom code to fix issues with FacetAPI Pretty Paths. In my case, node/42 was a search page with a pathauto pattern (e.g., /test). Because of the custom code, anything that started with node/42 (e.g., node/420, node/4272) would apply the same pattern, event to admin pages, so I was getting urls like /test0/edit and /test72/edit. I updated the issue in case anyone else comes across something similar when working with pretty paths.

---
Tags: path-aliases
---


title: Clearing cache breaks site

text:
# Question
Title: Clearing cache breaks site
I'm trying to load a production site in a dev environment using the site's codebase (`core` 8.3.7, `contrib` and `custom` modules and `vendor` folder) and the current database.

After struggling a bit with it, I managed to import the DB (it's PGSQL with a **lot** of extensions), and the site was up. I looked into the status report page and besides a few update warnings, there are no errors.

First time I try to clear cache, the site breaks and starts complaining about missing modules (one of them made sense, the other is the `basic_auth` module, which is in core). I manually cleaned up the missing one from the DB, but I'm getting a log of `PluginNotFoundException`s, which to me, says I must have done something wrong. I've tried importing the DB again and I traced the caching issues down to `router` cache and `views` cache. All of the other caches are cleaned with no issues, but these two throw the above exceptions.

I've tried to install the codebase again via `composer`, respecting the `.lock` file with `composer update --lock`, and it says there is nothing to install/update.

I'm a bit lost, and the only way I can make the site work (even if momentarily) is by importing the DB again, but it breaks after cache clearing and/or configurations being exported, either via drush or via backend.

AFAICT, even if the codebase was in fact missing something (ie, someone installed something in production not managed by composer), it would show up in the `contrib` folder and by importing the DB it should be fine, right?

Does anyone have some suggestions on where to start looking for the problem?

# Answer
Are you sure there are no differences in the codebase? This would explain the issue. The plugins/routes are cached in the database until you clear the cache. Then they are rediscovered from the codebase and the missing plugins or routes become visible. It's not necessarily that the code is missing physically, it can also be a problem with autoloading.

If there is a problem with syncing the codebase by git/composer, use another tool, for example rsync. Make sure to sync the complete codebase, also the files in the root folder.
> 0 votes

# Answer
Had a very similar issue with a missing "list" plugin on D8.4.2. I discovered that my issue was caused by an OSX update to 10.13.1 which seriously messed with my vagrant/virtual box/composer/drupalvm local environment. My files were not syncing between host and guest machines apparently caused by some issues with NFS. One indication of this issue is that I had missing modules on the module list page.

Here is a link to where I found my solution: https://github.com/geerlingguy/drupal-vm/issues/1547

Ultimately, the fix was upgrading to 10.13.2 beta, then I deleted core and contrib modules manually and ran composer update to replace. I had no issues with the beta version of OSX.

Hope this helps.
> 0 votes

---
Tags: 8, caching, deployment
---


# Question
Title: How to get entityreference_backreference data programmatically
The User profile for my site contains the Entity Reference field 'Parent' which points to another User.

I have the `entityreference_backreference` module enabled on my Drupal 7 site. I need to programmatically access the values of the properties added to the user entity by the `entityreference_backreference` module, so that for User A, I can identify all other Users which point to A via the 'Parent' EntityReference field.

If I do the following

```
$wrapper = entity_metadata_wrapper("user",$some_user);
$wrapper->getPropertyInfo();

```

I can see that that an entry for the entityreference\_backreference field **field\_parent\_user\_eb** is available in the `getPropertyInfo()` output. So the property does exist.

However, if I do

```
$wrapper->get('field_parent_user_eb');

```

it comes back with "data = null".

Also if I just try to access `$some_user->field_parent_user_eb` that also gives a null result.

It looks like the property is never being set.

What am I doing wrong? I can see that there is a "*getter callback*" defined for the **field\_parent\_user\_eb** property, which is set to `entityreference_backreference_related_entities`, but I can't see how I can use this.

Any help much appreciated!

# Answer
> 0 votes
OK this was my ignorance of how to use Entity Metadata Wrappers. The way to get the value of the **field\_parent\_user\_eb** field is

```
$wrapper = entity_metadata_wrapper("user",$some_user);
$value = $wrapper->field_parent_user_eb->value();

```

`$value` contains an array of entities which (back) reference the original `$some_user`.

I should have read https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers before posting.

---
Tags: 7, entities
---


# Question
Title: File Field description field default using tokens?
Using Drupal 8 File Field and enabling the optional description field works normal.

I want to have a default value populated for the field using tokens from other fields in the content type (to create a standard formatted description). Is there a way to enable this or must I disable this field and override the twig for the content type to display the desired description for the file link?

Note that this question pertains the optional description field (not the filename - that works perfectly well with the tokens using File (Field) Paths module.)

# Answer
> 1 votes
Good news - it's not that hard! Here's what you need to do:

1. Install Drupal Console (if you haven't already): https://drupalconsole.com/
2. Install the devel module: https://www.drupal.org/project/devel
3. Enable the webprofiler module (part of devel) `drush en webprofiler`
4. Webprofiler adds a toolbar to the bottom of your browser window. Use this to get the form ID of the form you want to modify.
5. Use Drupal Console to generate a `hook_form_FORM_ID_alter()` function. You'll need either a custom theme or a custom module for this.
    * *Warning:* If you're modifying the node edit form, it probably uses the admin theme. You probably don't have a custom admin theme, so you may want to put this in a custom module.
6. Customize your function to prepopulate the field the way you want. Here's what I did:

```
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() on behalf of coit_customizations.module.
 *
 * Provides a default for file description on meeting edit form
 */
function coit_customizations_form_node_meeting_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Check to see if there's already a file description
  $existing_description = $form['field_supporting_documents']['widget'][0]['#default_value']['description'];

  // If there isn't, add the default
  $new_description = $existing_description ? $existing_description : 'Download Supporting Documents';
  $form['field_supporting_documents']['widget'][0]['#default_value']['description'] = $new_description;
}

```
7. Don't forget to enable your module!

For further reading:

One last tip: **xdebug** is very useful for inspecting your form array so you know what to customize. If you're trying to do this kind of thing and aren't using xdebug, I recommend you check it out.

As an easier alternative, just add this to your function: `drupal_set_message($form);`

---
Tags: 8, files
---


# Question
Title: 'Could not find the alias' error after installing drush alias for Pantheon
I'm attempting to get the drush alias to work with Pantheon, but when I try to run `drush @pantheon.mysite.dev status` I get `Could not find the alias @pantheon.mysite.dev`.

I've already installed the aliases by running `terminus aliases`, but it doesn't seem to be seeing the generated file. I did go in manually to confirm that the alias file was placed inside of the .drush directory.

When I run `drush sa`, I get the following:

```
@none
@self
default

```

I did recently installed drush 9 on my Drupal 8 sites, but I still have a number of Drupal 7 sites running an older version of drush. I understand that the directory structure for drush 9 is different. Do I need to install the aliases for it somewhere else?

Just so you're aware. I installed drush 9 via composer, and I'm using the drush launcher which lives in my bin directory.

# Answer
If you already have `terminus` installed, you can use `terminus drush` instead of your local `drush`.

The advantage of `terminus drush` is that it already has everything you need to work with Pantheon.

The disadvantage is that you will have to do some work to set it up with your local dev environment; for that, I would just use your local `drush`.

So, the workflow looks like this:

* Do I need to call a drush command on Pantheon? `terminus drush`
* Do I need to call a drush command on my local dev server? `drush`
> 3 votes

---
Tags: drush, 8
---


# Question
Title: how to find nid of nodes that are created programmatically?
This is related to RNG module, but not entirely dependent on it. I've written a module that creates nodes (it's intended to create multiple nodes at any given time). This is where the tricky part comes in... I need to modify the rng event settings of the nodes that are created. There are approximately 4 settings that need to be set. Thus far, the only option I have come up with is modifying the database with an insert/update...but to do this effectively, I need to know the node id of the nodes that were just created.

# Answer
> 1 votes
Assuming that you create a node programmatically as follows:

```
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Node title',
]);
$node->save();

```

You can get the newly created Node ID with the `$node->id()` method as the variable `$node` is a referenced one.

# Answer
> 0 votes
I think the fastest way to do this is create a rule which emails you all the information about each node created.

The second fastest would be to create a view sorted by node id and filter by the author which I'm using is the same for each one of the programmatically created nodes.

The third is if you are creating these programmatically anyway, keep programming and use some combination of hook\_node\_insert() and hook\_node\_update.

The fourth is to steal the code from the Drupal project/hook\_post\_action https://www.drupal.org/project/hook\_post\_action

# Answer
> 0 votes
To get **"node nid"** from a **node**, you can use the **"id()"** function.

An example.

```
$node->id();

```

A complete example:

```
$nodenew= Drupal\node\Entity\Node::create([
  'type'        => 'article',
  'title'       => 'Node title',
]);
$nodenew->save();

//obtain the nid.
echo $nodenew->id();

```

If you want to get the complete node, you can use this code

```
$node= Node_load($nodenew->id());

//obtain the field title.
echo $node->get('title')->value;

```

---
Tags: rng
---


# Question
Title: Where is list of theme features in Drupal 8 that can be exposed on the "Settings" page?
In my theme.info.yml file, I can expose features to show up in the settings of my theme. It's documented here: drupal.org theming

```
features:
  - comment_user_verification
  - comment_user_picture
  - favicon
  - logo
  - node_user_picture

```

I tried to google a list of these, but can't find it. Is there some way I can figure out all the options available here, if there's not an explicit list anywhere?

# Answer
Here is the answer:

http://cgit.drupalcode.org/drupal/tree/core/config/schema/core.data\_types.schema.yml#n172

There needs to be documentation for this. Maybe I'll write it.....
> 0 votes

---
Tags: 8
---


# Question
Title: Why is this extremely simple form not getting an upcast entity from its route?
I have a `my_job_board.routing.yml`:

```
my_job_board.user_register_form:
  path: '/my-job-board/register/{user_role}'
  defaults:
    _form: '\Drupal\my_job_board\Form\UserRegisterForm'
    _title: 'Register for My Job Board'
  requirements:
    _access_user_register: 'TRUE'

```

(this is nearly identical to the route defined at line 56 of User module's `user.routing.yml`),

and a `src/Form/UserRegisterForm.php`:

```
<?php

namespace Drupal\my_job_board\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RoleInterface;

class UserRegisterForm extends FormBase {

  public function getFormId() {
    return 'my_job_board_user_register';
  }

  public function buildForm(array $form, FormStateInterface $form_state, RoleInterface $user_role = NULL) {
    var_dump($user_role);
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}

```

(my `buildForm()` has an identical signature to that of `Drupal\user\Form\UserPermissionRoleSpecificForm` which corresponds to the route I mentioned above).

Visiting `/my-job-board/register/employer` gives me the following error:

```
TypeError: Argument 3 passed to Drupal\my_job_board\Form\UserRegisterForm::buildForm() must be an instance of Drupal\user\RoleInterface, string given in Drupal\my_job_board\Form\UserRegisterForm->buildForm() (line 31 of modules/custom/my_job_board/src/Form/UserRegisterForm.php).

```

If i visit the same path with `string` instead of `RoleInterface` as the 3rd typehint for `buildForm()`, I see the output of `var_dump($user_role)`: `string(8) "employer"`.

Why am I not getting a `RoleInterface` passed into `buildForm()`? What am I missing?

# Answer
It seems entity routes (beginning `entity.`), like those in the user module, get the `Drupal\Core\ParamConverter\EntityConverter` converter automatically applied; other routes don't.

You should be able to apply it yourself easily enough:

```
my_job_board.user_register_form:
  path: '/my-job-board/register/{user_role}'
  defaults:
    _form: '\Drupal\my_job_board\Form\UserRegisterForm'
    _title: 'Register for My Job Board'
  requirements:
    _access_user_register: 'TRUE'
  options:
    parameters:
      user_role:
        type: entity:user_role

```

See Parameter upcasting in routes for more info.
> 5 votes

---
Tags: 8, forms, routes
---


# Question
Title: Strategy to consolidate multiple fields across content types?
I've got a handful of content types that all use different fields to hold the same type of data. For instance,

Content Type A -- Field Name: field\_type\_a\_user, Field type: Entity Reference

Content Type B -- Field Name: field\_type\_b\_user, Field type: Entity Reference

Content Type C -- Field Name: field\_type\_c\_user, Field type: Entity Reference

I'm building out a view displaying nodes that might reference any of the three of these content types, and the view needs to display information about the user referenced in the node's user field.

It seems inefficient to be using multiple different fields to be storing the exact same type of data. Is there an efficient way to go about creating a new field, field\_user, and moving the data from all of these old fields into the new field? And then update all references throughout the site to use this new field?

Or would it be better to just add all three fields to my new view and call it a day?

# Answer
> 2 votes
I can't say which is better, because it depends on what customization you intend to do in the future.

That said, generally speaking, if you have different content types that use the same field for the same purpose, you should choose to re-use the field across content types in the design stage; doing so would've saved you the trouble you face now.

**How to consolidate multiple fields**

First, create a new field on one content type.

Next, re-use the field on all the other content types you want to use it on.

Then, see this question on renaming fields for information about how to use SQL to copy the data from the old fields to the new fields. ALWAYS make a backup before doing this; if you make a mistake in this step, you can break your site.

Now, you will have to fix your views, twig templates, and anything else that might be broken. You can go to your exported config folder and search for the field names of the old fields, but I wouldn't change the config directly; I would use the config folder as a hint of what to change, and then update the values in the UI. I'd do this because sometimes one setting changes another, and if you do it in the UI, everything should get changed properly.

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


# Question
Title: Alter a date format in a view based on another date
In Drupal 8, I have a View formatted as a Table displaying a node type with two Date-Time fields. They are Start Date and End Date. Within the View I have them in the same column. I would like to alter how the End Date displays based on the Start Date. In particular, if the End Date is the same day as the Start date, I only want the time component displayed. I have created a Time date format for use elsewhere, that I assume will be referenced for this. In the event that the dates are different days, they need to use the default format.

I assume that one of the view hooks is what I need. But I am unsure of which one and do not know exactly what I would need to alter in the view's code.

# Answer
> 0 votes
You can override the output using twig code:

```
{% if field_date1.striptags == field_date2.striptags %}
    {{ field_date1 }}
{% else %}
    {{ field_date1 }} - {{ field_vegdate2 }}
{% endif %}

```

Or something like this...

---
Tags: views, datetime
---


# Question
Title: how to show file counter using file_download
This is a beginner question, in file\_download module. I have installed it and then I followed Install Instructions. But I couldn't figure out how to show the counter or statistics\_popular\_block, I tried to create a new view but didn't get any thing. I am new to views.

When I look to the source code I can see things such like:

```
src
  FileDownloadSettingsForm.php
  Plugin
     Block
         FileDownloadPopularBlock.php
     views
         field
             FileDownloadCounterTimestamp.php
             FileDownloadNumeric.php

```

any help?

# Answer
The module's project page gives these instructions:

1. Download to modules directory
2. Enable module
3. Apply formatter to any file or image field
4. Apply settings for title, currently either filename or nothing

Did you apply the formatter? To apply the formatter, you need to go to "Manage field display" for your content type, choose the image/file field, and then change the formatter.
> 0 votes

---
Tags: views, 8, blocks
---


# Question
Title: Is there any way to generate url alias instead of this taxonomy/term/%/faq, in views
I have created a page view taxonomy/term/%/faq. It works fine but I need to replace taxonomy/term/% with its url alias.

# Answer
> 3 votes
Pathauto just allows you to generate the URLs automatically so I believe you would still have the issue.

You will need something like https://www.drupal.org/project/path\_alias\_xt to extend the alias functionality to the other subpaths like the node/%/edit, taxonomy/term/%/faq etc.

# Answer
> 0 votes
I did it that way : using page\_manager (with ui) & panels, creating a panel page with an URL */taxonomy/term/%* and disabling (not deleting) default *taxonomy\_term* view (with its URL /taxonomy/term/% )

Then i copied default *taxonomy\_term* view to a new one using different URL (different than */taxonomy/term/%*), i added a block (and disabled 'page' displayID) to this view acting exactly like default taxonomy\_term view page.

**Note :** this block should have a contextual filter that correspond to taxonomy term ID (with depth or not)

Then i added this created block in my panel.

That allows to do what you are needing (get alias for URLs), and moreover, you can add things (blocks) to this page and it is a lot more flexible than overriding default *taxonomy\_term* view. I did not this for that puprose, but you can get your goal this way.

---
Tags: views, 8
---


# Question
Title: Improve D8 performance to access a custom REST controller
**Context**

I'm currently upgrading a site from Drupal 7 to Drupal 8.

In the D7 version, there was a custom "proxy" module which served back-end services. Requests starting with a `/service` prefix, such as `http://my-drupal-domain/service/service-name?service-args`, were redirected to a custom `index.php` inside a D7 module. This alternative `index.php` called the minimal Drupal code needed : includes and `drupal_bootstrap()`. Then, the custom module's function handled the request, sometimes using Drupal native functions (to manipulate users for example) and passing it to the target service. Finally, it returned the service response to the client.

Now I want to migrate this to Drupal 8.

I managed to code a custom REST controller, using a custom route :

```
my_module.rest_services:
  path: '/service/{endpoint}'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProxyController::index'
  methods: [GET, POST, PUT, DELETE]
  requirements:
    _access: 'TRUE'

```

The `ProxyController`, which extends `Drupal\Core\Controller\ControllerBase`, is basically the same code that handled the requests in the previous site, converted to the OOP-way of D8.

**Initial problem**

My problem is that, using D8 routes and Symfony2 components, the response time for any request increase proportionally with the number of concurrent users compared to the D7 version. For 20 users, this latency is +1s with D8 than with a D7 minimal bootstrap... That's huge! (see chart below, for the exact same call to D7 with a custom minimal bootstrap and D8).

Is there a way to bypass some of D8 code to redirect requests directly to my controller ? Some sort of "minimal D8 bootstrap".

Or a way to improve D8 routes performance ?

**Edit: need to cache file parsing**

I just discovered Drupal 8 is not the only responsible for my performance loss! during the request handle process, in my module's code, I read and parse a YAML configuration file, using `file_get_contents()` and `Drupal\Component\Serialization\Yaml::decode()`. But Drupal does not cache the value by default : the file is read and parsed on each call. With 20 concurrent users, it can take up to 600ms...

I need to find a way to tell D8 "Read this config file once, parse it and cache the content so you don't have to read it again unless your cache is cleared".

# Answer
> 2 votes
Given I did not have many responses, I answer myself to share the bits of explanation and solution I found.

Below the performance loss sources I've identified :

* The use of D8 full bootstrap, including modules loading, routes resolving, etc.
* Reading and parsing a YAML config file each time the module handles a request

And the solutions I applied :

**Custom D8 minimal bootstrap**

Based on this post and the default D8 `index.php`, I created a custom Bootstrap in my proxy module :

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\my_module\Controller\ProxyController;

chdir( $_SERVER['DOCUMENT_ROOT'] );

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$container = $kernel->getContainer();

$response = ProxyController::create( $container )->index( $request );
$response->send();

$kernel->terminate($request, $response);

```

Like it was made in the D7 version, I redirected all request with the `/service` prefix to this file.

**PHP config instead of YAML**

I didn't find a way to load and parse the YAML config file once and cache the result. (I'm still interested if someone know how to do that by the way)

So i converted the config file content myself into PHP, put it into a .php file and use `include` instead of `file_get_contents()` and `Yaml::decode()`.

**Result**

You can see here the response time obtained combining the 2 solutions above.

I assume the remaining perf loss is due to the use of OOP instead of procedural PHP. But if I want to stick to the D8 standards, I can't do much about it...

---
Tags: 8, routes, performance
---


# Question
Title: Ajax modal does not show for authenticated users
I'm testing a simple ajax modal link on a Drupal site and figured out that the modal

```
<a class="use-ajax" data-dialog-type="modal" href="/search/node">Search</a>

```

does only show when logged in as admin. For authenticated users it does not load (it just shows the search page). This is independent of the underlying theme I am using (bartik or a bootstrap subtheme). No error messages or status-reports give any indication what's going on. I thought only for anonymous users ajax needs to be added for the theme dependencies ? What am I missing here ?

# Answer
> 1 votes
For `use-ajax` to work for Anonymous as well as Authenticated user, Core `core/drupal.ajax` library must need to be loaded on page, where we're using 'use-ajax' class.

You can include this library with either using `#attached` in your *Form* or *Controller* or you can implement `hook_page_attachments` hook and attach ajax library.

If you're trying to add link to text inside your form, you can directly use `#ajax` instead of using classes as per directed in Ajax commands for opening and closing Dialogs and generic Dialog Controller added to core

```
  $form['link'] = [
    '#type' => 'link',
    '#title' => 'Link 1 (modal)',
    '#url' => Url::fromRoute('ajax_test.dialog_contents'),
    '#ajax' => [
      'dialogType' => 'modal',
    ],
  ];

```

Hope this helps.

---
Tags: 8, ajax
---


title: Where does Drupal store its content?

text:
# Question
Title: Where does Drupal store its content?
I have been currently learning Drupal while trying to duplicate a Drupal application into CakePHP.

I have been looking at the database tables to know where data is being stored so I can safely migrate any data or study how it is working.

I have researched and have come across questions like:

Where does Drupal store the content of a node's body? Where does Drupal store NODE data?

So far, I have only seen the title in my Drupal (7) installation.

What I have seen in my node revisions table for a recipe content type, which includes fields like, `field_ingredients`, `field_instructions`, `field_description`, `field_preptime`, `field_cookingtime`, just the title of the recipe. This is a sample record on my `node_revision` table.

```
nid   |  vid  |  title         |  log   | timestamp  | status | comment | promote  | sticky
-------------------------------------------------------------------------------------------
1     |  1    |  Awesome Sauce |        | 1369998600 | 1      | 2       | 1        | 0

```

As you can see I can only see the title. Where are the other field contents?

# Answer
Drupal 6 stored it's content in one table per content type. CCK will adhere to that unless you share a field among several nodes, in which case the fields will be broken out to a separate table.

Drupal 7 creates a new table for every *field*, so you'll see a lot of tables named `field_data_[name_of_field]`, and `field_revision_[name_of_field]`, the former for the active data, and the latter for tracking any other revisions of the same data. You might be interested in this discussion How to disable the revision feature completely? if you don't need the revision functionality.

Use the entity\_cache module to alleviate some of the performance hit from all the joins this causes on complex content types.

If you need an entity that is complex enough to make the D7 approach unusable, consider creating a custom entity where you make properties of your fields. That costs a bit of flexibility, but will make Drupal store the content like the title, which is a property, in the types table.
> 8 votes

# Answer
In Drupal 7 all the fields in the base table are known as properties, like the title and other fields in your case. All the other fields like body image and many other which you create are stored in other tables. Actually, Drupal make a separate table for every field in the database and store the primary key of the entity bundle (article, basic page) in that field\_table as a foreign key. Basically Drupal make two tables for every field 1: is for storing the data (field\_data\_\[name\_of\_field\]) and 2: is for revision (field\_revision\_\[name\_of\_field\]).
> 1 votes

# Answer
It is stored in node\_revisions table. fields are stored in a new table for each field. so `field_description` would have a table called `field_data_field_description`
> -1 votes

---
Tags: nodes
---


# Question
Title: How to limit webform submissions access to only users who have Webform submissions?
I am using Webform for surveys. But I want to permit users who have submitted to see all results. In other words: to see all Webform submissions.

Any user can submit but no user can't see all results without submission.

Any ideas or suggestions?

# Answer
Here are the steps to get this to work:

* Create a dedicated role, let's call it "WSA" (short for "Webform Submission Access"). By default, no user has this role.
* Configure the permission "Access all webform results" so that only role WSA has access to it.
* Install/enable the Rules and Webform Rules modules.
* Create a, rather basic, rule like so:
    + Rules Event: After a webform has been submitted.
    + Rules Condition: Check that the current user has role "authenticated" (I trust you do not want Anonymous users to get access to the submissions ...). Add whatever other conditions you may want (eg: check the form-id), if any.
    + Rules Access: Grant access to the WSA role for the "current user" (who submitted the webform).

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

# Answer
Maybe not a complete solution but here is how you can start of

* create a view that displays submissions
* make it available to everyone (view has permissions)
* put it in a URL that is not linked from your main site (its like being hidden but not exactly)
* put the URL link at the submission completion page (thank you page)

beware this will not prevent a person that knows this URL to visit it and see the results. I am not aware at this point of a module that will give the required permission `see results after submission` or something similar so if the above is not to your satisfaction then you might want to create a module to do that or modify webform to include such a feature
> 1 votes

---
Tags: views, users, webforms
---


title: Show closed form as read only form

text:
# Question
Title: Show closed form as read only form
I'm working on a Drupal 8 project where I need to show closed webforms as read-only form (without submit button and possibility to answer them), but Webform behaviour doesn't fit my need, as it only display a message "Sorry...This form is closed to new submissions." without displaying the webform.

Is their any way/hook that will allow me to display these closed webform?

# Answer
> 0 votes
You would need to not close the form but use hook\_webform\_submission\_form\_alter() to change all elemnts to be readonly and hide the submit buttons.

---
Tags: webforms
---


title: How can I make a container resizable?

text:
# Question
Title: How can I make a container resizable?
I've the body field as container. When I add '#resizable' to the field with `hook_form_alter()`, it is not getting resizable.

```
function test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form' || $form_id == 'node_page_form') {
    kint($form);
//      $form['body'] = [
//        '#resizable' => TRUE,
//      ];
  }
}

```

How can I make it resizable?

# Answer
In the official documentation

says the following:

> "#resizable": Controls whether the text area is resizable. Allowed values are "none", "vertical", "horizontal", or "both" (defaults to "vertical").

in this documentation we can see, that this property "#resizable" is applicable only to textarea.

Then, you can try:

```
function test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form' || $form_id == 'node_page_form') {
    $form['body']['widget']['0']['#resizable']='horizontal';

    //or
    //$form['body']['widget']['0']['#attributes']["style"]="resize:vertical";

  }
}

```

if you change the text format in "**restricted HTML**" you will see

if you want to use the "both" parameter

```
function test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form' || $form_id == 'node_page_form') {
      $form['body']['widget']['0']['#resizable']='both';

  }
}

```

if you change the text format in "restricted HTML" you will see:
> 0 votes

---
Tags: forms
---


title: Display last logon date on profile

text:
# Question
Title: Display last logon date on profile
I have D7 with profile2 how can I display the user last active date (last login date) on the users profile so other users know that they are an active user. It doesn't have to the actual date it can say something like "Active within the last week"

# Answer
> 1 votes
You can implement template\_preprocess\_user\_profile

In your theme's template.php file add:

```
function MYTHEMENAME_preprocess_user_profile(&$vars) {
  $vars['user_profile']['last_login'] = array(
      '#markup' => t('Last login') . ': ' . format_date($vars['user']->login, 'medium'), // prints the actual last login time using the medium date format
      '#weight' => 99, // defines location
  );
}

```

Clear the cache and check the user profile page (e.g. /user/1)

# Answer
> 1 votes
If no coding needed, use module linked below

> https://www.drupal.org/project/login\_history

# Answer
> 0 votes
it depends on where do you want to implement this but it just to lines:

```
// Load user object.
global $user;

// Get the timestamp of last login
$user->login;

```

then you'll have the option on how to output this(e.g):

```
date('d M Y h:i', $user->login);

```

or use it a Drupal way by implementing format\_date() which can be use like this:

```
format_date($user->login, 'custom');

```

you can make your own custom format to have as you mentioned!

Hope this helps!

# Answer
> 0 votes
You can use this simple and lightweight module here

https://www.drupal.org/project/last\_login

---
Tags: 7, users
---


# Question
Title: Is there a way to see what fields are used in Rules?
There is an field list overview in the reports for Views that shows the fields used.

Here is a sample of it:

Is there a quick way to find out which fields are used with Rules? It would be enough to check if a certain field is used by Rules.

**SOLUTION:**

As I don't have a special SQL tool drush works too by entering a query similar to what's included in the accepted answer:

```
drush sqlq "SELECT id,plugin,active,name,label FROM rules_config WHERE data LIKE '%points_dec%'"

```

# Answer
Consider a rule as in this (random) sample (in Rules export format):

```
{ "rules_new_node_with_special_optionlist_value" : {
    "LABEL" : "New node with special optionlist value",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A new node got created with option list value =  \u0022[node:field-optionlist]\u0022" } }
    ]
  }
}

```

Obviously, the above rule uses a field with machine name `field_optionlist`.

Execute an SQL query on the Drupal database which looks like so:

```
SELECT id,plugin,active,name,label
FROM `rules_config`
WHERE `data` LIKE '%optionlist%'
LIMIT 3

```

The results I get by using this query (limited to the first 3 results only) looks like so:

```
id  plugin         active  name                                           label

20  reaction rule  0       rules_verify_updates_to_node_properties        Verify updates to node properties
21  reaction rule  0       rules_new_node_with_special_optionlist_value   New node with special optionlist value
28  rule           1       rules_set_an_initial_value_for_a_text_field    Set an initial value for a text field

```

Obviously, the result with `id=21` matches with my (random) sample rule.

To execute the above query, you can use whatever SQL query tool, such as PhpMyAdmin. Or if you rather want to have a site building tool, just use the Forena module (disclosure: I'm a co-maintainer). After you enable this module, these are the steps required to find the answer to your question:

* Use relative link `/admin/structure/forena/data/add` (= **`Create New SQL Query`**).
* Select a "Data source" in which the SQL statement (= data block) will be stored (saved).
* Enter the above SQL statement, and use the `Test Changes` button (to prototype your SQL).
* *Voilà*, there is the (prototyping) result.

The above should answer the "*It would be enough to check if a certain field is used by Rules*" part of your question, but if you want to further improve this prototype, use the power of Forena to build a custom report from it, and make all sort of magic happen, eg:

* export it to a CSV.
* eMail it to somewhere.
* ...

**Note**: the above approach works for all sorts of "Rules queries" ... after all, in the above query I used (part of) the machine name of some field (= `optionlist`). Do an educated guess what kind of results you get if you would use the machine name of:

* a content type, e.g: `article`.
* a rules component, e.g: `rules_send_email_notification`.
* a module that some rule(s) depend on, e.g: `webform_rules`.
> 3 votes

# Answer
There's no admin screen, but if you are using the Features module and you have exported all your rules as a feature, then you can use `grep`.

`cd myfeaturesfolder`

`grep my_field *`
> 0 votes

---
Tags: 7, entities, rules, log-messages
---


# Question
Title: Importing multiple product variations in one product display
I have this huge problem I cant understand. I import products via feeds....i have mapped excel cvs file.... I can import one product variation to one product display... But I have 4 product variations and I dont know hot to setup my excel file because product display and product variation match connect with eachother withunique identifier like sku but I have here four different skus for 4 variations like for example 22SKU\_red 22SKU\_orange 22SKU\_blue 22SKU\_black

Any idea how to set it up to import with excel?

# Answer
I haven't tested this in the context of importing product displays, but in theory you should be able to accomplish this by choosing a character to separate the SKU's, putting all SKU's in single column, and by using the Feeds Tamper plugin "Explode".

The explode tamper plugin cares that your input data is handled as multiple values.

Example XLS file:

```
Product display title | SKU
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
Lorem Ipsum           | 22SKU_red|22SKU_orange|22SKU_blue|22SKU_black
Dolor Sit Amet        | 23SKU_red|23SKU_orange
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

```

**Steps**

1. Separate the SKU's in your Excel file with a certain character, for example a pipe character: "|".
2. Install the module Feeds Tamper. Also enable the Feeds Tamper Admin UI module (included with Feeds Tamper).
3. Go the Tamper page of your feeds importer (/admin/structure/feeds/\[importer\_id\]/tamper).
4. Click "Add plugin" for the "Product: SKU (field\_product:sku)" mapper.
5. For the plugin to add, select "Explode". As string separator, choose the character that you used to separate your SKU's. If you followed the example, then this would be the pipe character: "|". See also the image:
> 0 votes

---
Tags: commerce, feeds
---


# Question
Title: Feeds cant import product node again after manually deleting it
I came across this problem. I mapped product variations to the wrong category, and then I manually deleted variations. Also the display got deleted. Then I tried to import it again via csv excel file but it did not work, it imported variations, but product display was not imported again. Like the deleted files is stuck there in the system somewhere. I am uploading my feeds node display import setting screenshot

# Answer
> 1 votes
First, make sure that the product display is really deleted. If not, read on...

Was Feeds disabled when you deleted the product display? If so, Feeds wasn't able take note of the deletion and then there is indeed still a reference to this display.

Note: in the examples below I have assumed you have not attached the importer to a content type, but instead you use the standalone import form. If you *do* have attached the importer to a content type, you'll need to specify the feed node ID in the queries (which in the examples is set to `0`).

**feeds\_item table**

Feeds keeps track of imported items in the 'feeds\_item' table. The column 'id' references the machine name of your importer. If you still know the ID of your product display, you could lookup in this table the correspending feeds\_item record with the following query (where 'my\_importer' is the machine name of your importer and '56' is the ID of the deleted product display):

```
SELECT * FROM `feeds_item` WHERE `id`='my_importer' AND `feed_nid`=0 AND `entity_id`=56;

```

**Delete all imported items and remove left-overs from the feeds\_item table**

If you no longer know the product display node ID, the easiest solution is to delete all imported items using the Feeds importer:

1. Go to /import.
2. Select the importer that you used.
3. Click on the tab 'Delete items' and confirm the deletion.

Then, the feeds\_item records that point to no longer existing product displays will remain in the feeds\_item table. You can delete these with the following query (where 'my\_importer' is the machine name of your importer):

```
DELETE FROM `feeds_item` WHERE `id`='my_importer' AND `feed_nid`=0;

```

**Search for orphaned feed items**

If deleting all imported items is not an option and you don't know the product display node ID, you'll need to create a join database query in order to find out which feed\_items are orphaned. Example:

```
SELECT feeds_item.* FROM `feeds_item`
LEFT JOIN `node` ON `feeds_item`.entity_id = `node`.nid AND feeds_item.id='my_importer' AND `feed_nid`=0
WHERE `node`.nid IS NULL;

```

This will show you the orphaned feeds items.

**Patch for cleaning up orphaned feeds items**

There is also a patch available which goal it is to clean up orphaned feeds items: https://www.drupal.org/project/feeds/issues/1394320

---
Tags: commerce, feeds
---


# Question
Title: Blank spaces opening RSS XML file - How to solve?
All of the sudden, we are experiencing problems with our RSS feed which comes with the Drupal core 7.x . It is no longer valid due to two spaces before the opening XML tag. The following error is what I get in the feed validator:

> line 1, column 2: XML parsing error: \<unknown\>:1:2: XML or text declaration not at start of entity

So I am aware of other related posts on Stack Exchange and tried the things mentioned in:

These are the things we did do so far:

* Checked all PHP-files on the website for containing blank spaces before the opening tags. There were a few, we fixed them all but no help.
* Changed the default theme to another theme, making sure it is not theme related.
* When I create a custom RSS feed with Views, the same two blank spaces show up before the XML opening tag.
* I checked every page, block and view that has manually written PHP tags everywhere and deleted every space that could cause this.
* All modules and Drupal core is updated to the most recent versions.
* I checked on the Drupal forum for related issues in XML Sitemap, Metatag, RDF, Schema.org (modules we are using) with no success. I disabled every one of the above mentioned modules one by one, but with no success.
* Eventually we exported the complete website, except the sites/default/files/ folder which contains no PHP files anyway, and imported it local. The blank spaces are gone in the local setup.

What makes it a bit difficult too, is that I have no idea when the RSS feed went broken. It can be between a week and a few months, making it difficult to filter out when I updated some contrib modules.

So we are quite desperate in finding this, especially since the problem doesn't exist in a local setup. We have a news website so having a working RSS feed is pretty important.

We must be overlooking something, but have no idea what it can be.

# Answer
The issue was a module which had two blank spaces AFTER the closing PHP-tags in its .module file. All the topics I've found on the internet only mentioned blank space before the opening PHP-tags, so if anyone else ever have this issue, also look in the closing tags
> -2 votes

# Answer
Some more troubleshooting ideas:

* Do the spaces only appear on the RSS page, or also on other pages? That could tell you whether the problem is in a central place or a template/include-file that is only loaded for the RSS feed.
* You can use `var_dump(get_included_files())` (ideally in the template, just before the XML is generated) to see a list of all PHP files that have been included so far. This might help with investigating - look for closing PHP tags at the end of the files, print statements, etc.

Also, an idea for a dirty workaround (may cause other problems, but could be worth a try if it's urgent): `ob_start()` buffers all output, while `ob_end_clean()` deletes it. So if you put an `ob_start()` in the top of your index.php and an `ob_end_clean()` at the start of the RSS template, this *might* let you discard the spaces. (It shouldn't affect anything else, because the buffer is flushed automatically if it's still open when the script ends.)
> 3 votes

# Answer
To debug whitespaces in the page output, you can use XDebug PHP extension. Here are the suggested options in your XDebug PHP's ini file:

```
; Data
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=0       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=256        ; int: Controls the protection mechanism for infinite recursion protection.

```

Then either use step-by-step debugging mode, or temporary activate `xdebug.auto_trace=1` to generate trace files within your `xdebug.trace_output_dir` on every request.

Then request XML file and check the trace file. It'll take a while to track down the source of it by checking the returns of certain functions near end, but at least it's possible.

---

Alternatively disable as many modules as you can and you can find the problem by trial and error.

---

If you believe one of your `.module`'s file could consist trailing spaces, the following `ex` command (part of Vim) will remove any of these:

```
ex +'bufdo!%s/\s\+$//e' -scxa **/*.*

```

Note: If your shell supports a new globbing option, use `**` for recursive scan. Enable by: `shopt -s globstar`.

---

Another way is to run your files through the coding standards using Coder module. After installation, the following command will find the issue related hidden trailing spaces:

```
phpcs --standard=Drupal some_folder/

```

To fix the issue in-place, try this one:

```
phpcbf --standard=Drupal some_folder/

```

Note: Before run, make sure you've everything committed or made a backup, as above command will reformat all your files.
> 0 votes

---
Tags: 7, meta-tags, xml-sitemap, rdf
---


# Question
Title: How to Enter Fields in the Order Information form (and confirmation email)?
I need to add additional fields in the customer's information form during checkout, such as Telephone number and "How did you hear about us?". I don't see within the Commerce pull-downs in the Admin panel any way to do that similar to how fields are added in other Drupal forms. I assume Commerce allows such customization. Of course that data needs to be added into the database records as well.

In addition, how are those additional fields added to the email that is generated when the order is completed? While the customer may not need it, other people within the ordering / fulfillment process are designated as getting copies of that email and need that information within the email.

# Answer
**Adding additional fields to the customer**

You'll want to add the fields to the customer profile:

`/admin/config/people/profiles/manage/customer/fields`

**Editing the email text**

According to the Commerce documentation:

Use the template file located in `/commerce/modules/order/templates/commerce-order-receipt.html.twig`.
> 1 votes

---
Tags: commerce
---


title: Synchronize teaser config file Issue

text:
# Question
Title: Synchronize teaser config file Issue
After creating a new content type in DEV and then in STAGE importing the exported DEV; After successful import I find below file in in CHANGED stage(1 Changed).

core.entity\_view\_display.node.my\_node\_type.teaser

Is anyone having any idea why it is happening?

.

# Answer
> 0 votes
I cannot say what exactly is the problem (it is a bug for sure), but here's how you solve it: Go to the "Manage Display" tab for the content types for which the teaser display setting is not imported. On your DEV instance go to the teaser display and save it without changing anything (or changing something if you want to). Now export the config and push it via Git. Re-import on Stage and it should import cleanly now.

---
Tags: 8, configuration
---


title: Get User IP Address in Twig Template

text:
# Question
Title: Get User IP Address in Twig Template
Is there a way to get the user's IP address in a twig template? All the twig examples I find say to do it like this:

```
{% set ipAddr = app.request.server.get("REMOTE_ADDR") %}

```

But this variable always returns NULL. These examples aren't specific to Drupal so I'm guessing part of the Drupal implementation blocks/omits this.

# Answer
> 4 votes
Suppose you want to get the ip in the page.html.twig file.

in your

> YOURTHEME.theme

you can try

```
use Symfony\Component\HttpFoundation;

function YOURTHEME_preprocess_page(&$variables) {
  $variables['page']['ip'] = \Drupal::request()->getClientIp();

}

```

in your template

> page.html.twig

you can try:

{{ page.ip }}

---
Tags: theming, 8
---


# Question
Title: custom views slideshow tpl from unformatted list of views drupal 7
I want to create a slideshow in the front page. the slide show must have banner image of particular content type of recent nodes. how should i achieve this? should i create a view and theme it?

# Answer
Butterfly

you can use very options:

1. Create view with the slider content and theming tpls adding slick.js fe. as block or node to display only in frontpage
2. Add carousel module (there are many modules..carousel bootstrap, flexslider...) and create new view of this type with the slider content as block and display this block in frontpage .

Regards, Iván.
> 0 votes

# Answer
Thankfully i found a soution and here's what I did. I was given the HTML of the carousal. 1. I made a view in the drupal admin panel. 2. Format as table and feild and disable all the default classes. 3.select one of style output in themeing information on the bottom left of the admin view. 4. Make a tpl. 5. Put the HTML in for each(for the divs/ classes which repeat) loop. And the divs which don't repeat put them out of for each loop.

You will get the slideshow if the CSS and JavaScript are included properly and the divs and classes are put properly in the views tpl file :)
> 0 votes

---
Tags: views, theming
---


title: Programmatically update a field's value

text:
# Question
Title: Programmatically update a field's value
I want to update a node field's value when a node is updated.

Tried using the code mentioned here Programmatically updating a node Drupal 8

```
use Drupal\node\Entity\Node;

    function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

      $check = \Drupal::routeMatch()->getParameter('node');

      if ($check) {
      $node = Node::load($check->nid->value);
      $node->title->value = 'testing';     //set value for field
      $node->save();
      }
    }

```

but it did not work. I get a 500 error after saving the node. I also tried taking out the if statement and specifying a node id `$node = Node::load(1);`

I also tried using Update a node / Entity programmatically in Drupal 8

```
use Drupal\node\Entity\Node;

function hello_world_node_update(Drupal\node\NodeInterface $node) {

$node = Node::load(1);
$node->set("title", 'New value'); // also tried $node->setTitle('The new Title');
$node->save();

}

```

but no luck either.

In addition, I tried using different hooks entity\_presave, entity\_update, node\_update, but did not make any difference.

# Answer
> 31 votes
You can try this code:

```
function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('new Title');
  $node->set('body', 'this is body');
}

```

# Answer
> 10 votes
This is another variation with using the hook you originally tried to use.

I think the problem with your code is that you try to load a new instance of the node, but you should use the node that is provided as paramater `$entity`:

```
use Drupal\node\NodeInterface;

function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity)   {
  if ($entity instanceof NodeInterface) {
    $entity->title->value = 'testing';     //set value for field
    // $entity->save(); (not needed)
  }
}

```

**Edit:**

Added the use statement to the code.

# Answer
> 4 votes
Titles in Drupal 8 are not set like standard fields; they have their own function. Use `$node->setTitle('New Title');` for a node or `$entity->setLabel('New Title');` for a generic entity. See Node::setTitle for more info.

---
Tags: 8
---


title: How do I use a sub-string of a field?

text:
# Question
Title: How do I use a sub-string of a field?
How do I convert `SELECT title , SUBSTRING(title,13,4) as num FROM node_field_data ORDER BY ABS(num)` to the format for Drupal 8?

I tried this code.

```
 $query = $db->select('node_field_data', 'nfd')
  ->extend('\Drupal\Core\Database\Query\TableSortExtender')
  ->extend('\Drupal\Core\Database\Query\PagerSelectExtender');
  $query->limit('50');
  $query->fields('nfd',array('title',substring(title,13,4) as num,'changed','nid'));
 ->orderBy('num', 'ASC')

```

# Answer
You need to add an expression with `SelectInterface::addExpression`:

```
$query = $db->select('node_field_data', 'nfd')
  ->fields('nfd', ['title'])
  ->extend(\Drupal\Core\Database\Query\TableSortExtender::class)
  ->extend(\Drupal\Core\Database\Query\PagerSelectExtender::class);

$expr_alias = $query->addExpression('SUBSTRING(title, 13, 4)', 'num');

$query->orderBy($expr_alias, 'ASC')->limit('50');

```
> 6 votes

---
Tags: 8, database
---


# Question
Title: Allow content builder to 'disable' a content type form
I have a site that allows users to submit a 3d print job to a lab.

The role of the site builder is: technician The content type in question is: print job

Users can submit a print job (i.e. create a print job node).

What I'd like is to enable the technician to be able to prevent/disable/stop the user from being able to use the form at node/add/print-job when they want to prevent new print jobs from coming in (i.e. too busy at the lab).

I can use the Content Access module, but I'm hoping for something a bit less complex for the technician and that doesn't result in a 403.

I'm hoping that there is a way to do this with rules or workflow. Preferably one button/checkbox with a confirmation. Disabling the content type form will display a message written by the technician on the form path.

Any help would be greatly appreciated.

# Answer
I think you'll have to do this with code. My quick take on this would be:

* Create a content type with an "Disallow jobs" check box and the body field.
* Allow the technician role to view and edit this content type.
* Create a node and add it to your menu with a "Disable/Enable jobs" link.

Use hook\_form\_alter() to:

* check for the job content type form
* load your Disable / Enable jobs node
* Check if the disable jobs checkbox is ticked.
* Replace the $form array with a markup entry using the text from the node.

Note if you need to have this turned off automatically (e.g. lab closed), you probably can use rules to modify the disable jobs node.
> 0 votes

---
Tags: 7, rules, workflows
---


# Question
Title: What are the differences between Search API/Views and regular Views?
What are the differences between setting up Search API (with the Search Views module) and creating a particular set of results with Search Views against using Views is the normal manor?

The big difference I can see straight away is the Search Facets and being able to easily create the blocks that filter/facet the search results.

# Answer
This question is pretty vague and probably should be blocked.. but I'll take a stab at it.

Search API views have a bunch of different features. They allow full text search across multiple fields. E.g. title and body and possible extra text fields all combined in one search filter.

You can set your search api setting to also deal with stemming (e.g. search for learn and also get learning, learns, and the like.

Search API views also allow you to sort by Relevancy. E.g., if the search terms are found more times, the relevancy is higher. You can also set up boosts for different fields. E.g. if the term is in the title or product fields, it has a score of 10 rather then in the body where it has a score of 0.5.

This allows you more control over what shows up at the top of the search.

Search API views can also be set up to return 'excerpts' from the content with the search terms highlighted. This can be useful in helping people decide if the content is what they want.

There are a bunch of other things that Search API / Views can do, like synonym setups (e.g. orthopedic is the same as orthopaedic). Weighting specific nodes higher. Many of them may be at the search engine level (e.g. Solr) or require some extra modules (DB Server).

There is also the possibility of setting up auto completion suggestions as well.
> 3 votes

---
Tags: views, search
---


# Question
Title: Drush needs a higher bootstrap level to run
Do you have any idea on what might be causing this error when I execute:

```
drush si geoslate --db-url='mysql://root:root@localhost/geoslate' --site-name=Geoslate

```

> Command site-install needs a higher bootstrap level to run - you will need to invoke from a more functional Drupal environment to run this command.
> The drush command 'si vimn\_geoslate' could not be executed.
> A Drupal installation directory could not be found

?

# Answer
> 19 votes
This particular error happens when drush cannot find the settings.php file to read in and "bootstrap" itself.

You need to cd into the drupal directory (Document root) of your drupal install in order for it to read in a settings.php file.

# Answer
> 2 votes
For that error: Drush needs a higher bootstrap level to run

Write on your terminal: `mysql`

if you see something that:

> Unknown command 'mysql'

Then the problem comes from mysql, that's why your drush commands don't work.

Install MySql by Brew: https://brew.sh

```
Brew install mysql

```

# Answer
> 1 votes
When I wanted to install and enable some modules I encountered with this error. by changing the line `'host' => 'localhost'` in settings.php file of my site to `'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost'` now I can install my modules through Drush.

# Answer
> 1 votes
I have encountered this issue and I tried the accepted answer, which didn't work for me. As this question turns up high on Google results, I'm offering my solution in the hope that it helps others in my situation.

In my case, the mysql-client package was not installed. `apt-get install mysql-client` fixed Drush for me.

Why didn't I have the mysql-client package installed on a Drupal development machine? I'm developing on Windows and using WSL for Drush purposes.

# Answer
> -1 votes
Setup an alias for your site in the alias.drushrc.php file. Make sure MySQL executable is in your path variable.

---
Tags: drush
---