# Question
Title: How to avoid calling performRequiredValidation() for custom element
I'm trying to integrate Selectize plugin within Drupal 8 Form API. The important thing that I want to create 'optgroup' options.

I've used Selectize module and created a custom `FieldWidget` Field plugin.
Almost everything works, but I got some troubles with validation of my element.
Every time my form element submitted I receive an validation error:

> "An illegal choice has been detected. Please contact the site administrator."

I've found the function, which sends me that error - performRequiredValidation().
I've found lines, so I can hack the core and add a case for my widget. But it's not a case for me.

```
if ($elements['#type'] == 'select') {
  $options = OptGroup::flattenOptions($elements['#options']);
}
else {
  $options = $elements['#options'];
}

```

So the only way I see - I have to avoid this validation somehow.
Plase help. Any suggestions would be appreciated.

Here is a simplified code of my widget:

```
namespace Drupal\my_fields\Plugin\Field\FieldWidget;

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

/**
 * Plugin implementation of the 'my_selectize_widget' widget.
 *
 * @FieldWidget(
 *   id = "my_selectize_widget",
 *   label = @Translation("My Selectize Widget"),
 *   module = "my_fields",
 *   field_types = {
 *     "entity_reference"
 *   },
 *   multiple_values = TRUE
 * )
 */
class MySelectizeWidget extends OptionsSelectWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    // Get our types.
    $grouped_types = _getTypesGrouped();

    // Override select form element.
    $element['#settings'] = [
      'plugins' => ['optgroup_columns'],
    ];
    $element['#type'] = 'selectize';
    $element['#options'] = $grouped_types;

    return $element;
  }

  /**
   * Get types grouped (options).
   */
  protected function _getTypesGrouped() {
    /**
     * // For example:
     * return [
     *   '1' => $this->t('One'),
     *   '2' => [
     *     '2.1' => $this->t('Two point one'),
     *     '2.2' => $this->t('Two point two'),
     *   ],
     *   '3' => $this->t('Three'),
     * ];
     */
  }

}

```

# Answer
> 1 votes
That error is caused from the following code.

```
  if (isset($elements['#options']) && isset($elements['#value'])) {
    if ($elements['#type'] == 'select') {
      $options = OptGroup::flattenOptions($elements['#options']);
    }
    else {
      $options = $elements['#options'];
    }
    if (is_array($elements['#value'])) {
      $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
      foreach ($value as $v) {
        if (!isset($options[$v])) {
          $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
          $this->logger->error('Illegal choice %choice in %name element.', array('%choice' => $v, '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']));
        }
      }
    }
    // Non-multiple select fields always have a value in HTML. If the user
    // does not change the form, it will be the value of the first option.
    // Because of this, form validation for the field will almost always
    // pass, even if the user did not select anything. To work around this
    // browser behavior, required select fields without a #default_value
    // get an additional, first empty option. In case the submitted value
    // is identical to the empty option's value, we reset the element's
    // value to NULL to trigger the regular #required handling below.
    // @see \Drupal\Core\Render\Element\Select::processSelect()
    elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
      $elements['#value'] = NULL;
      $form_state->setValueForElement($elements, NULL);
    }
    elseif (!isset($options[$elements['#value']])) {
      $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
      $this->logger->error('Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']));
    }
  }

```

It means that the value set for `$elements['#value']` (which could also be a value submitted from the users) is not contained in `$elements['#options']`. In fact, your code contains the following code.

```
$grouped_types = _getTypesGrouped();

// Override select form element.
$element['#settings'] = [
  'plugins' => ['optgroup_columns'],
];
$element['#type'] = 'selectize';
$element['#options'] = $grouped_types;

```

Since there isn't a `_getTypesGrouped()` function, you are essentially setting `$element['#options']` to `NULL`, which means you are removing all the possible values the form field for that widget can have.
The correct code you want to use is the following one.

```
$grouped_types = $this->_getTypesGrouped();

// Override select form element.
$element['#settings'] = [
  'plugins' => ['optgroup_columns'],
];
$element['#type'] = 'selectize';
$element['#options'] = $grouped_types;

```

As for avoiding Drupal runs `FormValidator::performRequiredValidation()`, that is a bad idea. The purpose of that method is avoiding users submit a forget form; removing it means to mine the site security.

As side note, protected method don't need an underscore at the beginning of their name, as per Drupal coding standards.

# Answer
> 0 votes
For those which create a custom element based on the Select one and want to have OptGroup work, here's the trick:

```
class MyElement extends Select {

  #[...]

  public static function processSelect(&$element, FormStateInterface $form_state, &$complete_form) {
    $element = parent::processSelect($element, $form_state, $complete_form);
    $element['#type'] = 'select'; // trick to have OptGroup in our element

    #[...]
  }
}

```

Now this will work as expected in FormValidator::performRequiredValidation():

```
if ($elements['#type'] == 'select') {
  $options = OptGroup::flattenOptions($elements['#options']);
}
else {
  $options = $elements['#options'];
}

```

---
Tags: forms, 8
---


title: Trying to programmatically redirect

text:
# Question
Title: Trying to programmatically redirect
I’m trying to redirect users in Drupal 8 as I was used to do in Drupal 7 with a simple `drupal_goto()`.

This is my code.

```
$response = new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url($url_redirect));
$response->send();

```

Executing it, I get the following error:

> Symfony\Component\Routing\Exception\RouteNotFoundException: Route `http://mydomain.es/participar?utm_source=RTB&utm_campaign=&utm_medium=banner&utm_term=1` does not exist.

The alias /participar exists. What am I doing wrong?

# Answer
> 5 votes
See drupal\_goto() has been removed.

> ### Drupal 8 (procedural)
>
> ```
> use Symfony\Component\HttpFoundation\RedirectResponse;
>
> function my_menu_callback_foo() {
>   //....
>   return new RedirectResponse(\Drupal::url('user.page'));
> }
>
> ```
>
> ### Drupal 8 (properly injected)
>
> ```
> use Drupal\Core\Controller\ControllerBase;
>
> class MyControllerClass extends ControllerBase {
>
>   public function foo() {
>     //...
>     return $this->redirect('user.page');
>   }
> }
>
> ```
>
> If the route name is not known use `RedirectResponse` with a URL. When redirecting to an external location, use `TrustedRedirectResponse`.
>
> ```
> use Drupal\Core\Controller\ControllerBase;
>
> class MyControllerClass extends ControllerBase {
>
>   public function foo() {
>     //...
>     return new TrustedRedirectResponse('https://example.com/some/path'); // for eg. Url::fromUserInput(\Drupal::destination()->get())->setAbsolute()->toString();
>   }
> }
>
> ```

---
Tags: redirection
---


title: Programmatically creating a node

text:
# Question
Title: Programmatically creating a node
I am trying to create content from a cron job with a custom node type that contains just a title and body; the content type is mycontent (for argument sake).

I am trying to use the Entity API module because apparently it is supposed to be simpler.

Working from examples, I wrote the following code.

```
$values = array(
    'type' => 'mycontent',
    'uid' => $user->uid
  );
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('My Title');

```

Clearly I am missing something here because I get an exception (*EntityMetadataWrapperException: Unknown data property title*).

So I changed it to the following.

```
$values = array(
    'type' => 'mycontent',
    'uid' => $user->uid
  );
$entity = entity_create('mycontent', $values);
$ewrapper = entity_metadata_wrapper('mycontent', $entity);
$ewrapper->title->set('My Title');

```

Now I get a different error, an obtuse *Invalid data value given*.

Why cannot I get the Entity API module to work as advertised?

The current user in this case is user 1, not the anonymous user. If I add the content using Drupal standard functions, it works. So I know I am not having a permission issue.

I looked at this example, to write my code, and then proceeded to google a lot.

# Answer
> 7 votes
This will work for you:

```
$node = new stdClass();
$node->title = "My title";
$node->type = "mycontent";
node_object_prepare($node);
$node->uid = $user->uid;
$node->status = 1;
$node = node_submit($node);
node_save($node);

```

More details you can see at https://www.drupal.org/docs/7/howtos/create-a-node-in-code

---
Tags: 7, nodes
---


title: Programmatically generate orders

text:
# Question
Title: Programmatically generate orders
I am trying to programmatically generate orders in Drupal 8.

```
$order = Order::create(array(
  'uid' => $uid,
  'order_status' => uc_order_state_default('in_checkout'),
));
$order->save();
$product = Drupal::entityTypeManager()->getStorage('uc_order_product')->create(array(
  'qty' => 1,
  'order_id' => $order->id(),
  'nid' => $product_nid,
  'title' => $product_node->get('title')->value,
  'model' => '1001',
  'cost' => $product_node->get('display_price')->value,
));

$product->save();
uc_order_product_save($order->id(), $product);
$order->save();

```

Can someone please suggest what I am doing wrong? Do I need to extend to some class in particular? This order is not generated.

# Answer
> 0 votes
I was able to resolve this by adding these to my file:

```
//for order
use Drupal\Core\Form\FormBase;
use Drupal\uc_order\Entity\Order;
use Drupal\user\Entity\User;
//for products
use Drupal\uc_order\EditableOrderPanePluginBase;
use Drupal\uc_order\Entity\OrderProduct;
use Drupal\uc_order\OrderInterface;

```

---
Tags: 8, ubercart
---


title: How do I fetch the ID from the URL?

text:
# Question
Title: How do I fetch the ID from the URL?
I have a view which has 2 displays i.e 'page' and 'attachment'.

I am trying to fetch the id from the url and want to display it on 'attachment' display but having difficulty.

On the 'attachment' display, I want to display a text with link to another page alongwith the url id.

If I use 'Contextual filters' then what is the next step to display above text alongwith this id as tag? or perhaps any other solution.

# Answer
> 0 votes
I found following solution which works for me.....

VIEW \> ADVANCED \> Contextual filters

Add filter and look for WHEN THE FILTER VALUE IS NOT IN THE URL section.

Select 'Provide default value' \> Type: Raw value from url \> Path component: \____ (set url id value path number)

e.g if this is url, to get 239066 I will set Path component: 3

(https://drupal.abc.com/questions/239066)

VIEW \> Attachment settings \> HEADER \> Add: Text area \> Replacement patterns section will display your url id i.e {{ arguments.url\_id }}

---
Tags: views, 8
---


# Question
Title: How to check if maintenance mode is enabled in Drupal 8?
I've been searching for a way to check in PHP if the maintenance mode of my Drupal website is enabled, but I only found some solutions for Drupal 7, which doesn't seem to work on D8.

Have got any ideas?

Thank you.

# Answer
> 7 votes
The maintenance mode of the site is a boolean value stored in a state. You can access it like this:

```
$state = \Drupal::state()->get('system.maintenance_mode');

```

---
Tags: 8
---


title: Hide view results with hook

text:
# Question
Title: Hide view results with hook
I am trying to not show a certain view result using **hook\_views\_pre\_render** but I didn't find the correct way to not display the result.

I did manage to have access to the view and change each result title to a test title, code:

```
function MODULENAME_views_pre_render(\Drupal\views\ViewExecutable $view) {

  if($view->id() == 'tasks') {
    foreach($view->result as $task) {
      $task->_entity->set('title', 'test - ' . time());
    }
  }
}

```

I want to use something like **$task-\>show = false;**, is there any way?

Thank you!

# Answer
Solved my problem with the following:

```
function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'tasks') {
    $i = 0;
    foreach($view->result as $value) {
      if($i == 2)
        unset($view->result[$i]);
      $i++;
    }
  }
 }

```

The code above does not show the 3rd result from the view results. Add logic as you need.
> 3 votes

---
Tags: views, 8
---


# Question
Title: Filtering view by content author OR referenced field
I have a user that is author and is referenced on a certain content type, I want to be able to filter a view to show all nodes where the user is referenced, example field\_user and where the user is the author.

I can have access to the current user from my view and I did had a group with the OR operator so it can be filter to content author and from referenced field.

When I do things separately both work, I mean, I can get the nodes where the user is author and then I can get the nodes where he is referenced but when I add the two filters simultaneously with the OR operand this does not work, any idea?

In the image below are my settings to the view, I think that you may understand what I am doing.

Thank you.

# Answer
As no one answered and I couldn't find a way to solve this trhough UI, I used views\_pre\_render hook to solve my problem.

You can see the solution I found here.
> 0 votes

---
Tags: views, 8
---


title: if string contains substring twig

text:
# Question
Title: if string contains substring twig
I feel a bit dummy as I can't make it work..

I'm trying to check if a string contains substring in my twig.

```
{% set url = url('<current>') %}
{{ url }}

{% if 'my-delivery' in url %}
    //print something
{% endif %}

```

The url is printed outside the if statement but it doesn't enter the if statement and the url contains 'my-delivery'.

Any idea why it doesn't work?

# Answer
> 30 votes
The twig function `url()` returns a render array, when you render it with the twig filter `|render` you get a markup object and when you render it again you get a string, which you can check whether it contains a substring:

```
{% set url = url('<current>') %}
{% if 'test' in url|render|render %}
  <p>url contains "test"</p>
{% endif %}

```

# Answer
> 3 votes
`url()` returns an array, as 4x4 says. You can see this if you do a for loop on the variable.

`path()`, however, seems to return a string that you can do your operation on. But it won't include hostname.

---
Tags: theming, 8
---


# Question
Title: Custom language negotiation module not working
I'm writing a custom module to allow the use of language a language suffix (of the form -eng or -fra) rather than the standard prefix.

I'm using the language's configured prefix and have a number of functions in place.

I've implemented hook\_language\_negotiation\_info, and have a language selector, switcher and rewriter in place.

Paths with the suffix are working except that urls aren't being updated with the suffix when they're printed in the menus, or other places.

I confirmed that the rewriter callback is being called by placing a dsm() call in the function and it seems to be taking "node/45" and returning "page/45-eng" based on the alias. That aliased path works, but a url to "node/45" prints returns "page/45"

```
function custom_lang_language_negotiation_info() {
 return array(
    'custom_language_provider' => array(
      'callbacks' => array(
        'language' => 'custom_lang_language_getter',
        'switcher' => 'custom_lang_language_switcher_url',
        'url_rewrite' => 'custom_lang_url_rewriter',
      ),
      'file' => drupal_get_path('module', 'custom_lang') . '/custom_lang.inc',
      'weight' => -10,
      'types' => array(LANGUAGE_TYPE_CONTENT, LANGUAGE_TYPE_INTERFACE, LANGUAGE_TYPE_URL),
      'name' => t('Custom path suffix'),
      'description' => t('Determine the language from the URL suffix.'),
      'cache' => 0,
    ),
  );
}

```

Thoughts or something I can try?

I may be missing something in the way urls are generated or maybe the path is being reverted somewhere.

# Answer
I did the configuration with yml file.. try this solution

https://www.drupal.org/node/2775809#comment-11502283

It worked for me.
> 1 votes

---
Tags: uri, i18n-l10n
---


# Question
Title: Menu link that is author nodeid specific
When a user creates an account i have a rule that creates a node and set them as author for it.

I need a user specific link in the menu that varries from user to user.

User 1 may need the link: "Edit your node" -\> Links to node/1/edit User 2 may need the link: "Edit your node" -\> Links to node/5/edit

So its something like:

If content type = FOO, and node author = logged in user, show link "Edit your node" that links to -\> node/%/edit.

# Answer
You should use tokens in your menu-item for it to change dynamically. Install Menu Token module. From the module page-

> Menu Token allows to use both global tokens and entity ones: node, user, term, etc.

Then allow your menu path to use tokens and set something along `node/[node-id]/edit` as your path.
> 0 votes

---
Tags: hooks, navigation
---


# Question
Title: How to alter single custom field value in views?
I have a view with field Global: Custom Text, which is modified as a link. I want to change replacement tokens for generating this link, dependent on a value of other field.

Tried to modify this in hook\_views\_pre\_render but I can't find a way to do this.

In hook\_views\_post\_render there are two arrays:

```
$view->style_plugin->render_tokens
$view->style_plugin->row_tokens

```

which contains generated links for every row, but they are not present in pre\_render, and changing them in post\_render doesn't work.

I've also tried to do that in template\_preprocess\_views\_view\_fields but for that specific view this function does not firing (for other views it does), and I don't know why.

# Answer
> 16 votes
```
function hook_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
      //  override the global custom text field value
      $view->field['nothing']->options['alter']['text'] = 'My custom text';
    break;
  }
}

```

Check the link for more details How to insert values into Global custom text field of views programmatically?

add nid as field in view and use that field for condition you can add condition as follows: `if ($nid == '124') { $view->field['nothing']->options['alter']['text'] = $nid}`

Simple way is to create a new field field\_waga which will have field\_waga\_1 as new name if you check in the view and then you can change the label and override that field with your custom value

```
if($view->result[0]->field_waga[0]['raw']['value'] == '10') {
//here you can create the field to act as custom text field and enter the custom //value
$view->result[0]->field_waga_1[0]['#markup'] = 'alter';
}

```

# Answer
> 0 votes
As an update to the above answer, I had to set 'alter\_text' to TRUE in order for this to work, e.g.:

```
function hook_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
    //  override the global custom text field value
    $view->field['nothing']->options['alter']['text'] = 'My custom text';
    $view->field['nothing']->options['alter']['alter_text'] = TRUE;

    break;
  }
}

```

---
Tags: 7, views
---


# Question
Title: Remove default tab from login page ( Simple Fb Connect)
I am using Simple FB Connect module for Facebook login in my site. It adds a tab for facebook login, by default in my Login page. I want this tab to be removed and add a button instead. How can I remove this?

# Answer
> 1 votes
Create a hook\_menu\_alter function like this in a module:

```
function my_module_menu_alter(&$items) {
  unset($items['user/simple-fb-connect']);
}

```

---
Tags: 7, social-network
---


# Question
Title: How to apply a custom class to a .field__item in an entity reference display?
I have an entity reference field with multiple values, referencing various content using a custom view mode.

I need to apply the same custom class to each (delta) row.

By default Drupal (twig?) is applying a class of .field\__items to each row, but this is not specific enough, as this is also used for other fields within the view mode.

What is the best way to achieve this?

# Answer
You can add classes in the twig template directly, or through a preprocess function.

## Preprocess

Docs provide some patterns to follow: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template\_preprocess\_field/8.2.x

```
function HOOK_preprocess_field(&$variables) {
  $element = $variables['element'];

  switch ($element['#field_name']) {
    case 'MY_FIELD_NAME':
      $delta = 0;
      while(!empty($element[$delta])) {
        $variables['items'][$delta]['attributes']->setAttribute('class', 'custom-class-name');
        $delta++;
      }

      break;
  }
}

```

This applied the class to the entire entity, alongside field\__item.

## Template

If you have twig debugging enabled, you can see quickly what's a good template name. I tested with field--node--FIELD-NAME.html.twig. Using the field template from classy for example, just add the class at the end of the list.

```
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'custom-class-name',
  ]
%}

```

This applied the class just to the field, not the label. But you could modify the template to print the classes elsewhere.
> 3 votes

---
Tags: theming
---


title: Variation of Node Add Screen?

text:
# Question
Title: Variation of Node Add Screen?
How do I create a second version a node add page?

For example if have node/add and I want node/add-quick?

Some fields of the required fields form node/add would be missing or not required on node/add-quick.

I know node add fields can be hidden based on user role or other variables but how do I create an entirely new page with a select set of fields.

# Answer
with panels module you can select witch fields display and just do not add fields that you dont want, do not place "complete node form", also you can control what contentypes node/add form overrides. If you do not use panels module you can add a custom module with the following code (D7), replace uppercase letters with your data. This code only affect "your\_form\_id", to find your form\_id, inspect an element (right click on your form) and look for it.

```
 //if form id is YOURFORM_form hide elements
 function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
      global $user;
        $uuid = $user->uid;
  /*  check that user is NOT admin (No1) */
     if ($uuid !='1') {

        if ($form_id == 'YOUR_FORM_ID') {
            hide($form['field_YOUR_FIELD']); // hides field to all but admin user
            $form['body']['#format'] = 'plain_text'; // forces body format to plain text
            //displays field in form, but disabled
            $form['YOUR_SECOND_FIELD']['#disabled'] = TRUE;
        }
    }
 }

```
> 0 votes

# Answer
If D7, try Advanced Form Block module (AFB) for add-quick ajax node creations where forms can be a block in sidebar or content block, top or bottom of region, displayed only for admin. Cheat and hide some fields with css, or tweak the module as alternate to building from scratch. I have used it for 4 different content type creation forms, side by side in a 4 column footer region, for rapid content creation.
> 0 votes

---
Tags: 7, nodes
---


title: Admin Menu Permissions

text:
# Question
Title: Admin Menu Permissions
I want to allow my editors to add taxonomy terms to vocabularies. But to do so, I need to give them the permission "Use the administration pages and help", but as soon as i do that, they also can see the menu item "Configuration" in addition to the menu item "Structure".

How can I avoid that?

# Answer
The taxonomy fact was just an example. I also need this for webforms, so it would be better to have a general solution for that then just for a single module since this problem will occure for every configuration that is stored below "Structure".

It got this fixed using: Admin Links Access Filter
> 0 votes

---
Tags: users, navigation, toolbar
---


# Question
Title: How to get the number of registrants (RNG module) from the theme layer
In my theme I want to display not only the maximum number of registrants on the full view of a node but also the number of seats still available.

What is the easiest way to get the number of registrants? In Drupal 7 I retrieved this number by passing the node id into the registration\_event\_count() function, does RNG provide a similar function?

# Answer
> 1 votes
You can access the event manager service to grab an event meta object. The event meta object contains a bunch of helpers to manipulate registrations and registrants. In your template preprocess functions add whatever data you want from the event meta object.

```
function mymodule_preprocess_HOOK(&$variables) {
  $event_entity = $entity; // Provide your entity

  /** @var \Drupal\rng\EventManagerInterface $event_manager */
  $event_manager = \Drupal::service('rng.event_manager');
  $event_meta = $event_manager->getMeta($event_entity);
  $mydata = $event_meta->whatever();
   // See \Drupal\rng\EventMetaInterface for methods. e.g:
   // $event_meta->getRegistrants()
   // $event_meta->getRegistrations()
   // $event_meta->countRegistrations()
   // $event_meta->getCapacity()
   // $event_meta->remainingCapacity()
  $variables['myvariable'] = $mydata;
}

```

For nodes, replace `mymodule_preprocess_HOOK` with `mymodule_preprocess_node` and `$entity` with `$variables['node']`.

---
Tags: 8, rng
---


title: Contest with unique vote

text:
# Question
Title: Contest with unique vote
My users can submit Recipes (a custom content type). I want to create a contest to let my users vote for their unique favorite recipe.

To vote, users (anonymous users) have to go to the page of the recipe they want to vote for and clic on "I vote for this one" to vote for it. If they go to another recipe page, they won't be able to vote for it because they would have already voted for another recipe.

Do you have any idea about how to do it ?

I know how to do it with a poll inside a block but I want to have a vote button inside each recipe page.

# Answer
> 0 votes
I didn't find a way to do it with Rate or Five Stars.

My solution is pretty simple : webforms. You can allow only one "vote" per ip with this module and you can create a view / block to display it on each node.

It does everything I needed !

---
Tags: rating
---


# Question
Title: How do I upload files in docx and doc format?
I have added my code below which is used to upload a resume in CSV format, but now the requirement changed, and it is required I add the resumes in all formats (docx and doc). I have tried adding '#file\_validate\_extensions' =\> array('csv,docx'), but that gives me an error *Incorrect string value for title*. What are the modifications that should be done in the code to upload the resumes in all formats?

```
/**
 * @file
 * Contains \Drupal\custom_migration\Form\UploadForm.
 */

namespace Drupal\custom_migration\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\Core\Form\FormState;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;

class CsvUploadForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'csv_upload_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $file_size = t('Maximum file size: %size MB.', array('size' => file_upload_max_size()));
    $form['file_upload'] = array(
      '#type' => 'file',
      '#title' => t('File'),
      '#size' => 40,
      '#description' => t('Select the CSV file to be imported. ') . $file_size
    );
    $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), );
    // set the form encoding type
    // $form['#attributes']['enctype'] = "multipart/form-data";
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $destination='public://csv';
    if (!file_exists($destination)) {
      mkdir($destination, 0777, true);
    }
    $validators = array('file_validate_extensions' => array('csv'));
    $file = file_save_upload('file_upload', $validators, $destination, $replace = FILE_EXISTS_RENAME);
    // check file uploaded OK
    if (!$file) {
      $form_state->setErrorByName('file_upload', t('A file must be uploaded'));
    }
    else {
      // set files to form_state, to process when form is submitted
      $form_state->setValue('file_upload', array($file));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('candidate_name'))));
    /* Fetch the array of the  file stored temporarily in database */
    $line_max = \Drupal::state()->get('user_import_line_max', 1000);
    ini_set('auto_detect_line_endings', true);
    $filepath = ($form_state->getValue('file_upload')[0]->getFileUri());
    $handle = @fopen($filepath, "r");
    $job_id=\Drupal::request()->query->get('job_id');
    $row = 1;
    if ($handle !== FALSE) {
      while (($data = str_fgetcsv($handle, $line_max, ','))!==FALSE) {
        if ($row == 1) {
          $row++;
          continue;
        }
        $node = Node::create(array(
          'type' => 'job_application',
          'title' => $data[1],
          'langcode' => 'en',
          'uid' => \Drupal::currentUser()->id(),
          'status' => 1,
          'field_fields' => array(),
        ));
        $node->field_email= $data[2];
        $node->field_notice_period = $data[5];
        $node->field_phone_number = $data[6];
        $node->field_i_agree_terms_and_conditio=1;
        $node->field_job_list=$job_id;
        $node->field_resume_status=$this->getTidByName('Applied');
        $location_vocabulary = 'location';
        $tid_l1 = $this->getTidByName($data[3]);
        if (!empty($data[3]) && $tid_l1 === 0) {
          $term = $this->createNewTerm($data[3],$location_vocabulary);
          $node->field_current_location = $term;
        }
        else{
          $node->field_current_location=$this->getTidByName($data[3]);
        }
        $tid_l2 = $this->getTidByName($data[4]);
        if (!empty($data[4]) && $tid_l2 === 0) {
          $term = $this->createNewTerm($data[4],$location_vocabulary);
          $node->field_preferred_location = $term;
        }
        else {
          $node->field_preferred_location = $this->getTidByName($data[3]);
        }
        $field_values = array(
          'uri' => file_create_url('sites/default/files/'.$data[7]),
          'uid' => \Drupal::currentUser()->id(),
          'status' => 0,
        );
        $file = File::create($field_values);
        $file->save();
        $node->field_resume->setValue([
          'target_id' => $file->id(),
        ]);
        $skills_vocabulary = 'skill_sets';
        $skills = $data[8];
        $node->field_applicant_skills = $skills;
        $node->save();
        $row++;
      }
      fclose($handle);
    }
    drupal_set_message($this->t('You have sucessfully uploaded resumes.'));
    $form_state->setRedirect('view.review_requirements.review_jobs_page');
  }

  /**
   * Utility: find term by name and vid.
   * @param null $name
   *  Term name
   * @param null $vid
   *  Term vid
   * @return int
   *  Term id or 0 if none.
   */
  public function getTidByName($name = NULL, $vid = NULL) {
    $properties = [];
    if (!empty($name)) {
      $properties['name'] = $name;
    }
    if (!empty($vid)) {
      $properties['vid'] = $vid;
    }
    $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties($properties);
    $term = reset($terms);
    return !empty($term) ? $term->id() : 0;
  }

  public function createNewTerm($value, $categories_vocabulary) {
    $term = Term::create(array(
      'parent' => array(),
      'name' => $value,
      'vid' => $categories_vocabulary,
    ))->save();
    return $term;
  }

}

```

# Answer
> 0 votes
I think you have to replace the file types in the following line.

```
$validators = array('file_validate_extensions' => array('csv'));

```

Change it to this.

```
$validators = array('file_validate_extensions' => array('docx','doc'));

```

Also, in `submitForm()` you are parsing the CSV file using `str_fgetcsv()` and importing the data in a node. So you have to find another way parsing your new data and creating this node.

---
Tags: nodes
---


title: How can I give paid access to content?

text:
# Question
Title: How can I give paid access to content?
I am looking to manage user access to website content using Rules and the suggested access control module i.e. ACL, TAC etc.

There 3 levels of access to manage:

* Unregistered - No access to any Course Content
* Registered - Access to certain Preview nodes (see Preview Module below)
* Paid - Access to the content to which they have paid (as well as Preview nodes)

## Unregistered

* Unregistered users will have no access to any Course Content nodes
* However there may be pages on the site (Cookie, Terms etc.) which anonymous will need access to to keep the site functioning during registration/payment etc.

## Registered Users / Preview Module

* For each Course, 1 or more Modules (taxonomy term) will be marked as a Preview Module
* Preview Modules are identified by the term with a boolean check box: field\_module\_preview
* This should allow access to Registered uses to access the nodes within this Module.

Content types: Course – setup as a product Content

Taxonomy: Topic Module

Example:

```
> Course
> - Module
> - - Topic
> - - - Course Content NO Access
> - Module (Preview checked)
> - - Topic
> - - - Course Content: Access
> - - - Course Content: Access
> - - Topic
> - - - Course Content: Access
> - - - Course Content: Access
> - Module
> - - Topic
> - - - Course Content NO Access

```

## Paid Access

* Payment processing will be carried out using Drupal Commerce and PayPal. The setup of this is not required. Drupal install will be supplied with Commerce and product types setup.
* Once a course is paid, then access is granted to the entire Course and all its nodes

I have tried to integrate rules but no hope to make it working.

Can anyone help me to apply this scenario in my drupal 7?

Thank you in advance.

# Answer
> 1 votes
You should be able to get this to work using the Rules module, using a variation of the rule shown/explained in the answer to "How to make the permissions of a module more granular?". I.e in your case:

* you can use the same Rules Event (Drupal is initializing), which to my knowledge is the only Rules Event you can use for this (for any other Rules Event you're just "too late", i.e. the content is already being displayed).
* you can perform similar Rules Actions (to perform an appropriate redirect and display a message that fits your needs).
* you should use one or more of these Rules Conditions (combined with "OR", not with "AND"!):

+ check if the current user's role is "anonymous".
    + related to your field `field_module_preview`.

# Answer
> 1 votes
I would use roles and permissions based on roles. Two roles you get without doing any thing:

* Anonymous User
* Authenticated User

Use the first for Unregistered and the second for Registered. You can create a Paid Role for registered users that pay up.

You can use the rules module to add/remove the Paid role when users pay and lapse payment.

# Answer
> 0 votes
There is a per-configured package in Drupal known as Telekonsum . by default this has the possibility to sale the user roles. I hope this will helpful for you.

---
Tags: views, commerce, rules, taxonomy-terms
---


# Question
Title: States visibility in type select and radio in drupal 7
I have a custom form

```
$form['basic']['legal_form'] = array(
  '#type' => 'select',
  '#options' => array(
    'option1' => 'option1',
    'option2' => 'option2',
    'option3' => 'option3',
  ),
  '#title' => 'My Dropdown',
);
//radio button to show if selected option3
$form['basic']['bearer_shares'] = array(
  '#type' => 'radios',
  '#title' => 'Radio Button to show',
  '#options' => array(1 => t('yes'), 2 => t('no')),
  '#states' => array(
    'visible' => array(
    ':input[name="legal_form"]' => array('value' => 'option3'),
    ),
  ),
);

```

I try too

```
':input[name="legal_form"]' => array('selected' => 'option3'),

```

If I change type to textfield it works as expected but not when I try to use radio. Can anyone suggest me what I am doing wrong.

# Answer
> 1 votes
Try this code

```
$form['basic']['legal_form'] = array(
  '#type' => 'select',
  '#options' => array(
    'option1' => 'option1',
    'option2' => 'option2',
    'option3' => 'option3',
  ),
  '#title' => 'My Dropdown',
  '#attributes' => array('id' => 'selection_id'),
);

//radio button to show if selected option3
$form['basic']['bearer_shares'] = array(
  '#type' => 'radios',
  '#title' => 'Radio Button to show',
  '#options' => array(1 => t('yes'), 2 => t('no')),
  '#states'           => array(
    'visible' => array(
      'select[id="selection_id"]' => array('value' => 'option3')
    )
  )
);

```

---
Tags: 7, forms
---


# Question
Title: How do I add field collection unlimited items from hook_form_alter()?
I am trying to implement what described in Add unlimited field collections in a from of drupal and Field collection with unlimited cardinality pre-populate fields, but the *Add more* and *Remove* buttons don't work. I have issues with `drupal_rebuild_form()`.

The code in `hook_form_alter()` is the following.

```
$items_count = 3;
$field_name = 'field_story_technology';
$form_theme = $form[$field_name][LANGUAGE_NONE]['#theme'];
// Remove delete and add more buttons
//~ $form_state['field'][$field_name][LANGUAGE_NONE]['items_count'] = $items_count;
$items = &$form_state['field'][$field_name][LANGUAGE_NONE];
$form[$field_name]['und'][0]['remove_button']['#access'] = TRUE;
$form[$field_name]['und']['add_more']['#access'] = TRUE;
// Generate required number of fields collection
if ($items_count > 1 and $items['items_count'] != $items_count) {
  $items['items_count'] = $items_count;
  $items['field']['cardinality'] = FIELD_CARDINALITY_UNLIMITED;//$items_count;
  $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
  // Reset theme function, as field_multiple_value_form hijacks it
  $form[$field_name][LANGUAGE_NONE]['#theme'] = $form_theme;
  $rebuild_p = TRUE;
  //~ $form_state['rebuild'] = TRUE;
}
// Fill generated fields with data
for ($delta = 0; $delta < ($items_count-1); $delta++) {
  $form['field_story_technology'][LANGUAGE_NONE][$delta]['field_technology_photo_title'][LANGUAGE_NONE][0]['value']['#default_value'] = 'new value';
}
if ($rebuild_p) {
  $form['#after_build'][] = 'tttttt';
}

function tttttt($form, &$form_state) {
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

```

`drupal_rebuild_form()` will change my other functionality.

# Answer
> 0 votes
here in my below example i want to attach 5 images which will save in admin field collection , so here is code for it . here `109`is node id in which i want to save field collection value. `field_manager_update` is my field collection name.

```
<?php $images = array(//images to attach to node
    '0' => 'http://cf.juggle-images.com/matte/white/280x280/drupal-logo-primary.jpg',
    '1' => 'http://cdn.flaticon.com/png/256/37187.png',
    '2' => 'https://www.drupal.org/files/project-images/logo-128x128.jpg',
    '3' => 'http://guillermocerezo.com/sites/default/files/field/image/drupal-logo_0.jpg',
    '4' => 'http://drupalcrafters.org/sites/default/files/DrupalCraft-logo_0.png'
  );

$node = node_load(109);

$field_collection_value = entity_create('field_collection_item', array('field_name' => 'field_manager_update'));

// Attach to the node
$field_collection_value->setHostEntity('node', $node);

for ($i = 0; $i < sizeof($images); $i++) {
    $file_info = system_retrieve_file($images[$i], 'public://pictures/', TRUE, FILE_EXISTS_RENAME); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      //$node->field_prop_land_image[LANGUAGE_NONE][$i]['fid'] = $file_info->fid; //assign
      $field_collection_value->field_prop_update_image[LANGUAGE_NONE][$i]['fid'] = $file_info->fid;
    }
}
// Save field-collection item.
$field_collection_value->save();  ?>

```

Hope it helps :)

---
Tags: forms
---


# Question
Title: 10,000+ nodes vs. 1 node with 10,000+ field collection items
I need a sort of term database with around 3 fields that won't be used during normal site operations.. Only when I, the administrator, add content.

I'm wondering about how to minimise performance impact for regular users.. My intuition tells me that a field collection would be better so the nodes table is smaller.

I will be likely be using some code to add data from APIs and Rules to fetch the data by property.

Which should i use? I don't have much interest in creating a custom entity type unless it's really easy.. I want image and audio fields and I don't know if that complicates things.

# Answer
> 3 votes
Loading 1 node with like 10,000+ field collection items sounds like performance suicide if you don't limit the amount of items being loaded and displayed initially. And having to open a node with 10,000+ field collection items only to maybe add or edit one item will be really big pain then.

With nodes, much likely you'll never display all of them at once. You very likely will have them organised in Views. Limited display, pagers, filters, lots of caching possibilities. When you want to add a node, you'll have a fresh node form, loaded in milliseconds. Plus you will have a much larger number of contrib modules available dealing with sortability, searchability, orderability and a lot of other -abilities that come in handy when organising content. Also when it comes to content import.

Go for 10,000+ or even 1,000,000+ nodes. That's what Drupal is made for.

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


# Question
Title: How can I add an image field to a block?
I want to add a block containing an image field to Drupal to add it to the page layout.

I can see the image gets uploaded (because it appears in my file system), but the block forgets the image; next time I configure the block, the image I just uploaded has disappeared.

What I've got so far is the following code.

```
/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['image']['#markup'] = '';

  return $build;
}

/**
 * {@inheritdoc}
 */
public function blockForm($form, FormStateInterface $form_state) {
  $form['image'] = array(
    '#type' => 'managed_file',
    '#upload_location' => 'public://images/',
    '#title' => $this->t('Image'),
    '#description' => t("Image to show on the contact form"),
    '#default_value' => $this->configuration['image']['value'],
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_size' => array(25600000),
    ),
    '#states' => array(
      'visible' => array(
        ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
      )
    )
  );

  return $form;
}

public function blockValidate($form, FormStateInterface $form_state) {}

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $image = $form_state->getValue('image');
  $this->configuration['image'] = $image;
  $file = \Drupal\file\Entity\File::load($image[0]);
  $file->setPermanent();
  $file->save();
}

```

How do I display a user-uploaded image?
How do I make the block remember this picture?

# Answer
> 5 votes
With help from "Ambidex" on Drupal Slack, I post here the complete plugin-file.

I could not find an example for this use case, and I believe it might benefit others:

file: \[drupalroot\]/modules/custom/ourcustomername\_tweaks/src/Plugin/Block /ContactBlock.php

.

```
<?php

namespace Drupal\ourcustomername_tweaks\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

/**
 * Provides a 'Contact' Block.
 *
 * @Block(
 *   id = "contact_block",
 *   admin_label = @Translation("Image Contact block"),
 * )
 */
class ContactBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [

        'image' => [
          'value' => ''
        ],

        'label_display' => FALSE,
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function build(){
    $build = [];

    if (  isset($this->configuration['image']) && !empty( $this->configuration['image'] )  ) {

      $image_field = $this->configuration['image'];
      $image_uri = File::load($image_field[0]);

      $build['image'] = [
        '#theme' => 'image_style',
        '#style_name' => 'ourcustomername',
        '#uri' => $image_uri->uri->value
      ];
    } else {
      $build['image']['#markup'] = '['.t('Picture').']';
    }

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $form['image'] = array(
      '#type' => 'managed_file',
      '#upload_location' => 'public://images/',
      '#title' => $this->t('Image'),
      '#description' => t("Image to show on the contact form"),
      '#default_value' => $this->configuration['image'],
      '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
        'file_validate_size' => array(25600000),
      ),
      '#states'        => array(
        'visible'      => array(
          ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
        )
      )
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {

    /* Fetch the array of the file stored temporarily in database */
    $image = $form_state->getValue('image');

    $this->configuration['image'] = $image;

    /* Load the object of the file by it's fid */
    $file = \Drupal\file\Entity\File::load( $image[0] );

    /* Set the status flag permanent of the file object */
    $file->setPermanent();

    /* Save the file in database */
    $file->save();
  }
}

```

---
Tags: 8, blocks
---


# Question
Title: How long will the previous core version supported?
I want to start a new project at the beginning of 2018 but I don't know if it is better to start this project with Drupal 7 or Drupal 8. Actually, I am not familiar with Drupal 8 coding and template engine.

Even though there are lots of modules that aren't available in Drupal 8 right now, such as admin menu, Date Converting module and others, I finally decided to start my project with Drupal 7, but the point that disturbs me is not knowing how long Drupal 7 will be supported. Is it 2020, 2021, or later?

# Answer
> * Drupal 7 is currently on LTS.
> * Drupal 7 LTS will end when Drupal 8 enters LTS, at which point Drupal 7 enters security fixes only mode.
> * Drupal 7 security fixes only mode ends when Drupal 8 enters security fixes only mode, and Drupal 9 enters LTS.
> * Essentially: Drupal 7 won't be EOL before development has started on Drupal 10.

Source: Has the EOL (end of life) for Drupal 7 been announced?

**The simple answer is: We don't know, yet, exactly.**

Check out the following articles:

> Drupal 7 will likely get bug-fixes until October 2017, and official security support until 2019 or 2020 at least.
> 3 votes

---
Tags: updating
---


# Question
Title: How do I update without using the parameter --with-dependencies in "composer update --with-dependencies"?
I just finished my first Drupal 8 project, and I want to have it up-to-date before submitting it to the remote server. I read that it's better not to use `composer update --with-dependencies`. I understand why this is. I will do this for the core and modules, so I updated core with `composer update drupal/core --with-dependencies` and one drupal/module but then when I run `composer outdated` I still see a large list of symfony/twig/phpunit/zendframework/and more.

Do I really need to update them one by one? It seems a lot of work to do this every time. There are maybe 30 or 40 to update.

Hope someone can explain me how this works.

# Answer
I just use `composer update --no-dev` from the directory containing the composer.json file and the core directory, and I get all updated.

```
Loading composer repositories with package information
Updating dependencies
Package operations: 0 installs, 21 updates, 0 removals
  - Updating twig/twig (v1.33.2 => v1.34.3): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/yaml (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-mbstring (v1.3.0 => v1.4.0): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/translation (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/validator (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-php55 (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/serializer (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/routing (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-php54 (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/http-foundation (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/process (v2.8.21 => v2.8.22): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-iconv (v1.3.0 => v1.4.0): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/event-dispatcher (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/debug (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/http-kernel (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/dependency-injection (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/console (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-apcu (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/class-loader (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating guzzlehttp/guzzle (6.2.3 => 6.3.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating drupal/core (8.3.2 => 8.3.4): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

```

I put drupal/core in the *require* section, so it gets updated too.

As for the output of `composer outdated`, I get the following.

```
doctrine/annotations            v1.2.7      v1.4.0      Docblock Annotations Parser
egulias/email-validator         1.2.14      2.1.2       A library for validating emails
symfony-cmf/routing             1.4.1       2.0.1       Extends the Symfony2 routing component for dynamic routes and chaining sever...
symfony/class-loader            v2.8.22     v3.3.2      Symfony ClassLoader Component
symfony/console                 v2.8.22     v3.3.2      Symfony Console Component
symfony/debug                   v2.8.22     v3.3.2      Symfony Debug Component
symfony/dependency-injection    v2.8.22     v3.3.2      Symfony DependencyInjection Component
symfony/event-dispatcher        v2.8.22     v3.3.2      Symfony EventDispatcher Component
symfony/http-foundation         v2.8.22     v3.3.2      Symfony HttpFoundation Component
symfony/http-kernel             v2.8.22     v3.3.2      Symfony HttpKernel Component
symfony/process                 v2.8.22     v3.3.2      Symfony Process Component
symfony/routing                 v2.8.22     v3.3.2      Symfony Routing Component
symfony/serializer              v2.8.22     v3.3.2      Symfony Serializer Component
symfony/translation             v2.8.22     v3.3.2      Symfony Translation Component
symfony/validator               v2.8.22     v3.3.2      Symfony Validator Component
symfony/yaml                    v2.8.22     v3.3.2      Symfony Yaml Component
twig/twig                       v1.34.3     v2.4.3      Twig, the flexible, fast, and secure template language for PHP

```

That is normal, though, since the core/composer.json file has some restrictions for the package versions that don't allow to update to the versions shown from `composer outdated`. For example, see the following lines in core/composer.json.

```
"doctrine/annotations": "1.2.*",
"egulias/email-validator": "1.2.*"

```

1.2.\* is telling Composer that any version greater or equal to 1.2.0 and lower than 1.3 are acceptable. doctrine/annotations version 1.4.0 falls outside that range.
> 0 votes

---
Tags: composer
---


# Question
Title: How do I define an external URL in settings.php and call it in a custom module?
In the settings.php file, there are (for example) `$base_url`, `$settings['hash_salt']`.

I defined `$settings['external_url'] = "google.com";`

In my custom module, I want to get the `$settings['external_url']` value.

```
<?php

namespace Drupal\my_custom_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Site\Settings;
use Drupal\Core\Form\FormStateInterface;

/**
* Contribute form.
*/
class MyCustomClass extends FormBase {

   private $base_url;
   public function __construct(){
       $this->base_url = Settings::get('external_url') . '/maps';

   }

   public function validateForm(array &$form, FormStateInterface $form_state) {
      $pb= $form_state->getValue('pb');
      $url = $this->base_url . '?timeline' . $pb;
   }
}

```

Then I got this error:

`Notice: Trying to get property of non-object`

I am using Drupal 8 and PHP 7.

# Answer
Trying using the full path of the class:

```
\Drupal\Core\Site\Settings::get('external_url')

```

In Drupal 8, an ideal place for custom variables is in config files. Create a yml file in the config directory and import the configuration.

my\_variables.settings.yml

```
external_url: 'url-string-here'

```

Then to fetch the values, it's:

```
\Drupal::config('my_variables.settings')->get('external_url')

```

https://www.drupal.org/docs/8/converting-drupal-7-modules-to-drupal-8/step-4-convert-drupal-7-variables-to-drupal-8
> 1 votes

---
Tags: configuration
---


# Question
Title: How to have OutboundPathProcessorInterface change the URL of the loading page
I have a page my/topics. The page presents content based on the user's selection from another page. Having made the selection, it and other information is passed to the page via a query string:

```
mydomain.com/my/topics/?choice=topic1...

```

I have no control over the creation of the incoming path. For the processing of the path and for SEO I need the path to instead be:

```
mydomain.com/my/topics/topic1

```

In both cases the target is my/topics, but the processing I need from that point depends on being able to access the additional information as part of the URL instead of as a query string.

The available topics are a large non-static list. It might be possible to do some regex magic in .htaccess to handle it as a redirect, but I'd rather handle it within Drupal, if possible.

To that end I've used OutboundPathProcessorInterface. The class is listed, below. The problem I am having is that the path is not changed in the browser address bar. If I put my/topics in a menu link on the page, or a link in the body text, it does become my/topics/topic1 in each of the links, and in the address bar on a subsequent click, but not in the address bar of the page that is rendered as part of the altering of the path... it appears as my/topics.

I have commented out the 'if' statement that limits the change to just that path, and the result is the same on admin/structure, for example. The browser shows admin/structure, but the link to it in the admin menu when hovered over shows admin/structure/topic1.

You'll note that I have the priority of the module being -32766 (I've also tried just -1). No difference.

**url\_remap.services.yml**

```
services:
  url_remap.path_processor:
    class: Drupal\url_remap\UrlRemapOutboundPathProcessor
    tags:
      - { name: path_processor_outbound, priority: -32766 }

```

**UrlRemapOutboundPathProcessor.php**

```
namespace Drupal\url_remap;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;

class UrlRemapOutboundPathProcessor implements OutboundPathProcessorInterface {
  function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    $append = '';
    if ($path == "/my/topics") {
      if (sizeof($options['query']) > 0) {
        if (array_key_exists('choice', $options['query'])) {
          $append = substr($path, strlen($path) - 1, 1) != '/' ? '/' . $options['query']['choice'] : $options['query']['choice'];
        }
      }
    }
    return $path . $append;
  }
}

```

# Answer
> 3 votes
You need three components for this task:

Your outbound path processor `UrlRemapOutboundPathProcessor::processOutbound` is the first step to get this started.

Second add an inbound path processor `UrlRemapOutboundPathProcessor::processInbound` to the class similar to `Drupal\system\PathProcessor\PathProcessorFiles\processInbound`:

```
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;

```

Your path processor won't change the URL in the browser, this is by the way the same with other path processors, for example you can access nodes still by their internal paths (/node/\[id\]) after you've entered an alias.

So third you need a request event subscriber which redirects the unwanted internal URLs.

An example would be how Redirect does this in `RouteNormalizerRequestSubscriber::onKernelRequestRedirect`:

```
 /**
   * Performs a redirect if the URL changes in routing.
   *
   * The redirect happens if a URL constructed from the current route is
   * different from the requested one. Examples:
   * - Language negotiation system detected a language to use, and that language
   *   has a path prefix: perform a redirect to the language prefixed URL.
   * - A route that's set as the front page is requested: redirect to the front
   *   page.
   * - Requested path has an alias: redirect to alias.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The Event to process.
   */
  public function onKernelRequestRedirect(GetResponseEvent $event) {

```

http://cgit.drupalcode.org/redirect/tree/src/EventSubscriber/RouteNormalizerRequestSubscriber.php

Probably this global redirect catches the internal paths from step one/two as well. If you don't want to redirect all URLs globally or find issues with the alpha version of this module, you can use this event subscriber as example to write custom code to target only the specific URLs.

---
Tags: routes
---


title: page not found on install

text:
# Question
Title: page not found on install
So i wanted to install Drupal on my local mac. I download drupal 7.12 put its content into my htdocs (i'm running MAMP) goto localhost got through all the steps and his save and it took me to "http://localhost/install.php?profile=standard&locale=en" where i get this message

then if i goto localhost i get this

I can't seem to figure out what went wrong Could some one point me in the right direction ?

# Answer
I'm not sure exactly what your problem is, but it's probably faster to simply try re-installing again from the start than to troubleshoot your installation. It's hard to estimate how much time it will take to troubleshoot when you don't know what's wrong but you know roughly how long trying to install it again will take.

Although I use MAMP with Drupal myself, if you're a first-time user it might be easier to try Acquia Dev Desktop, which is an "Apache server in a box" like MAMP but already includes the latest version of Drupal and is ready to go as soon as you install it. Acquia is a company run by the founder of Drupal so you know you're in good hands.

Alternately, although not specifically a Drupal company, Bitnami offers Drupal as an "Apache server in a box" like MAMP as well as as a virtual machine and as a cloud server on Amazon cloud.

There's also Pantheon, which is a Drupal platform that will let you register an account and create Drupal sites in the cloud for free (note that Pantheon will, however, charge you if you decide to take your site live on their service).

I listed many options; of them all, Acquia Dev Desktop is the simplest to set up and get running.
> 1 votes

# Answer
Check the directory name. I had the similar issue, resolved once I changed the directory name from camel case to lower case.
> -1 votes

---
Tags: installation
---


title: eCommerce : Definitions?

text:
# Question
Title: eCommerce : Definitions?
Where can I find the definition of the meaning of terms in eComerce and Drupal iself . It is a bit confusing. F.e. there is :

```
Product
product type
product attribute
product variation
product variation type
product field
entity reference

```

and then :

```
 display field
 display form field

```

what are they and how they interact. I understand some of it ... but how do the COMPOSE and interact that is abit confusing.

===========

I read abit and here is the flow of creating product as I understand it.

1. Create Product attributes
2. Bundle attributes in Product variation types
3. Make Product types out of PVT
4. In the Create Product create the final Product-Variations, out of PT

Why so convolved !???

# Answer
> 1 votes
It's very open structured, and adaptable ..

Think of it like this: You sell *variations* of a *product* to a customer. Where *attributes* handle the actual variation. Products and variations can be arranged by types (like content types)

> Different types can have different properties (ie. fields) a variation can be referenced to a product no matter of their types. So here the attributes come into place and should available for all variation referenced to a instanciated product.

A product field can be on a content type to show your product on a regular node. (and is a referenced entity) Otherwise products can be shown with the search api.

The variations are also referenced entites on the product. But provide already good AJAX and add to cart functionalities out of the box.

**Regarding display:** *Fields* can be everywhere ... and are in the end displayed. (a basic drupal concept: fieldable-ness) *Forms* are only used in the backendfor composing the content.

Maybe the doc from the commerce guys gives you the point (it's d7):

**Product Types. (and variation types for d8)** A product type is a specific bundle based on a custom product entity. Each bundle can have fields attached to it, including pictures and other kinds of information.

**Product "Informational" Fields. (and variation fields for d8)** Any field on a product can be a simple "informational" field. Typical informational fields include an image of that specific configuration of a product. For example, if you sell a tshirt with a cool print in multiple colors, each product with a different color could have an image field that, when displayed on the product display node, will change when you select different attributes (like color).

**Product "Attribute" Fields. (actually variations attributes for d8)** Any field on a product type with a defined list of options (list of text options, list of taxonomy terms, list of colors). The attribute fields are special because of the way they turn into selection widgets on a product display. Often you will pair an attribute field (like a color dropdown) with an information field (like an image field) to let the user "select" the blue tshirt and the Drupal Commerce system will quickly load the picture associated with the blue product.

**Product Displays.** If needed at all, these are groupings of products. You can reference any type and number of products on a product display. In order to make use of product displays, we recommend only showing one type of product per product display. The product display is where you typically see the product with drop downs to "configure" or "order" the right kind of product.

taken form here https://drupalcommerce.org/user-guide/product-attributes-variations

---
Tags: commerce
---


title: Did the updated module actually update?

text:
# Question
Title: Did the updated module actually update?
Just performed an update to Drupal 7.56. In the process I updated all modules, including Google Analytics. The weird thing is that on my machine, where I performed the update, Google Analytics updated just fine.

But, after placing the files onto the server, and updating the DB with a copy of my own, the server is saying Google Analytic is still in need of an update. Everything else appears fine.

I checked the files for the Google Analytics module, and they are indeed the updated version.

Any ideas?

Thanks, Cy

# Answer
> 0 votes
Try to run **http://serversite.com/update.php**.

You may have forgotten to **clear the cache** before you download the Database you upload to the server.

Next Time try try to clear the cache before you export your database file. Also I will recommend you use Backup and Migrate Plugin, that should be efficient in the future without error

---
Tags: updating
---


# Question
Title: Installing with Composer causes unit tests to fail
I installed with Drupal with Composer (using drupal-scaffold) with Drupal files placed inside the web directory. When I run unit tests, two of them fail because Drupal expects to find the composer.json file inside the web directory whereas in my case composer.json is in the project root (which is obvious place for it).

Is this an issue with my configuration, or is it a problem with unit tests that make wrong assumptions?

The failing tests are `Drupal\Tests\ComposerIntegrationTest::testComposerJson` and `Drupal\Tests\ComposerIntegrationTest::testComposerLockHash`. Both fail with the following error message.

> file\_get\_contents(web/composer.json): failed to open stream: No such file or directory

# Answer
Drupal with Composer uses the drupal-scaffold script which you mentioned. It seems that it does not include the composer.json and composer.lock files by default.

But the files are there: http://cgit.drupalcode.org/drupal/plain/

Looking at the plugin documentation on github in the Configuration section reveals that the `composer.json` and `composer.lock` files are not on the list to be included by default.

But the plugin is configurable, and you can actually specify the name of the files that should be additionally included.

So adding this in the `extra` section of your `composer.json`:

```
"drupal-scaffold" : {
    "includes" : [
        "composer.json",
        "composer.lock"
    ]
}

```

followed by running `composer drupal-scaffold` OR removing `web/core` directory and running `composer install` should get you the required files and make the tests pass.x
> 1 votes

# Answer
It looks like there's no way to override $this-\>root in /web/core/tests/Drupal/Tests/ComposerIntegrationTest.php (unless you add a patch to change the path to the main composer on line 45).

But you could use two symlinks so that /web/composer.json points to /composer.json and /web/composer.lock points to /composer.lock.

from /web directory:

```
ln -s ../composer.json composer.json
ln -s ../composer.lock composer.lock

```
> 0 votes

---
Tags: 8, testing
---


title: Query does not change

text:
# Question
Title: Query does not change
I've got a problem with `hook_views_query_alter()`. I want to override the view's query with a rather complex one. In the first step, I placed the hook in my views.inc and tested it. The hook is called. But none of my tests to alter the query worked.

```
function glass_lagermanagement_views_query_alter(&$view, &$query) {
  if ($view->name == 'lagerbestand') {
    $query = db_select('materials');
    $query->condition('materials.ID', 1, '==');
  }
}

```

To test the function, I want to show only one entry which has got the ID "1", but nothing happens at all in the view. What am I doing wrong?

I'm using Drupal 7 here. It is an old project I need to update.

# Answer
> 1 votes
I got it. I used this code to alter the query and it worked.

```
$query->where[1]['conditions'][0] = array('field'=>"materials.ID","value"=>'1',"operator"=>"LIKE");

```

# Answer
> 0 votes
Based on the documentation of hook\_views\_query\_alter you can change the condition by using the following code :

```
foreach ($query->where as &$condition_group) {
  foreach ($condition_group['conditions'] as &$condition) {
    // If this is the part of the query filtering on title, change the
    // condition to filter on node ID.
    if ($condition['field'] == 'node.title') {
      $condition = array(
        'field' => 'node.nid',
        'value' => $view->exposed_raw_input['title'],
        'operator' => '=',
      );
    }
  }

```

Which means that in your case :

```
//foreach
if ($condition['field'] == 'materials.ID') {
  $condition = array(
    'field' => 'materials.ID',
    'value' => 1,
    'operator' => '=',
  );
}

```

You can also check this post for another way.

---
Tags: views, hooks
---


# Question
Title: Cache_render table grows extremely fast, is there a way to remove the url.query_args cache context from ALL pages?
I'm noticed on a clean Drupal installation, the cache context url.query\_args is present on ALL requests, that cause **one entry on cache\_render table per each request** (if we change some query params, think about analitycs queries), and that table grows extremely fast. I don't know if this is necessary for ALL pages. Can I disable this behaviour from a config? Is this neccesary for Drupal to work properly?

# Answer
No, in a clean Drupal installation this should not happen. These are the default cache contexts set in core.services.yml:

```
parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

```

What you might have found are cache entries from the Internal Page Cache for anonymous requests, which doesn't use cache contexts. Instead it stores the cache entries with the complete URL including the query string as cid. There are a lot of complaints that the Internal Page Cache fills up the database even for sites with moderate traffic. Not only because of the variations by the query string, also because the entries have no expire date and there is no way to configure one in UI. But you can easily replace the Internal Page Cache with Varnish or a CDN. You only have to configure the third party solution to invalidate the Drupal cache tags. Another option is to replace the cache backend with a solution that provides an automatic expiration like Memcache or Redis.

---
> 3 votes

---
Tags: 8, caching
---


# Question
Title: When using the StringTranslationTrait in a service why should you inject the 'string_translation' service aswell?
I was reading the code comments in the StringTranslationTrait trait and saw the following:

> If the class is capable of injecting services from the container, it should inject the 'string\_translation' service and assign it to $this-\>stringTranslation.

So I created a simple service, used the StringTranslationTrait, injected the `string_translation` service and assigned it to `$this->stringTranslation`. I found that when I don't inject the `string_translation` service the `$this->t()` function still works as I expected.

Why should one inject said service into his own service? Is it good practice or are there other benefits such as speed? The comments in the StringTranslationTrait file offer no explanation.

**My service for completeness:**

```
<?php

namespace Drupal\wow\Service;

use Drupal\Core\Url;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Class RedirectService.
 *
 * @package Drupal\wow\Service
 */
class RedirectService {

  use StringTranslationTrait;

  /**
   * The redirect object.
   *
   * @var \Symfony\Component\HttpFoundation\RedirectResponse
   */
  private $redirectResponse;

  /**
   * RedirectService constructor.
   *
   * @param \Drupal\Core\StringTranslation\TranslationInterface $stringTranslation
   *   The string translation service.
   */
  public function __construct(TranslationInterface $stringTranslation) {
    $this->stringTranslation = $stringTranslation;
  }

  /**
   * Sets the redirect.
   *
   * @param string $routeName
   *   Drupal route name to redirect to.
   * @param string $message
   *   Message to show after redirecting. If not provided no message will be
   *   shown.
   * @param string $messageType
   *   Message type of message shown after redirecting.
   */
  public function setRedirect($routeName, $message = NULL, $messageType = 'status') {
    $uri = Url::fromRoute($routeName);

    if ($message) {
      drupal_set_message($this->t($message), $messageType);
    }

    $this->redirectResponse = new RedirectResponse($uri->toString());
  }

  /**
   * Gets the redirect object.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   The redirect object.
   */
  public function getRedirect() {
    return $this->redirectResponse;
  }

  /**
   * Returns the response object.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response object.
   */
  public function send() {
    return $this->redirectResponse->send();
  }

}

```

# Answer
If you didn't inject the string translation service into `$this->stringTranslation`, the trait would get it from the static `\Drupal` wrapper

```
  /**
   * Gets the string translation service.
   *
   * @return \Drupal\Core\StringTranslation\TranslationInterface
   *   The string translation service.
   */
  protected function getStringTranslation() {
    if (!$this->stringTranslation) {
      $this->stringTranslation = \Drupal::service('string_translation');
    }

    return $this->stringTranslation;
  }

```

and this should be avoided in OOP code. The main reason for this is to be able to inject mock-up services for code tests.
> 6 votes

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


# Question
Title: Access row value in template_preprocess_views_view_fields(&$variables)
In `template_preprocess_views_view_fields(&$variables)`, when I print `$variables['row']`, I get the following object.

How can I access `values` inside the node entity?

I tried with the following code, but it is not working.

```
$variables['row']->_entity->values['field_file_pdf_upload']->target_id

```

# Answer
`values` is protected, so you have to use the `get()` method:

```
$variables['row']->_entity->get('field_file_pdf_upload')->target_id;

```

For the field object this shortcut is available (this is not standard OOP and works for fields only):

```
$variables['row']->_entity->field_file_pdf_upload->target_id;

```
> 2 votes

---
Tags: theming, 8
---


title: Custom text between webform elements

text:
# Question
Title: Custom text between webform elements
Is is possible to insert user-editable text as a form component?

I would need some custom text between the "email" and "name" fields. How do I achieve this?

# Answer
Assuming you are talking about the Webform module, you can create an element with type of "markup". There are a few options for this, including input format. If you have everything configured properly, you can use a WYSIWYG editor on the fields, too.

If you are using the Form API, then you can use `#type = "markup";` to put pretty much whatever HTML you want in your custom form.
> 11 votes

# Answer
In Drupal 8, you now have *Markup elements* you can look for by *Category* when adding elements to your webform. This is confusing at first since the *markup* element is no longer called so in the Drupal 8 version.
> 1 votes

---
Tags: webforms
---


title: Why can't I install this module?

text:
# Question
Title: Why can't I install this module?
I installed the Commerce Shipping module (using Drupal 8), but when I try to install it, I can't do anything, neither install it nor uninstall it. The check-box is gray.

I can't find anything to configure it. Also, I can't even uninstall it to try the development snapshot version.

What should I do?

# Answer
> 1 votes
The module depends on the Physical Fields module. Since commerce sites are strongly strongly recommended to be managed by composer, you should be using just `composer require drupal/shipping` from the document root and be done with it.

---
Tags: 8, commerce
---


# Question
Title: How do I define a route and controller for the home page?
A custom module called TSA contains almost all of the functionality for the /tsa subsite on my Drupal 8 multisite.

*I want to define a route for http://localhost/tsa/, so that I can serve up dynamic content on the homepage depending on who the authenticated user is.*

Here's tsa.routing.yml:

```
tsa.homepage:
  path: '/'
  defaults:
    _title: 'TSA Home'
    _controller: '\Drupal\tsa\Controller\HomepageController::content'
  requirements:
    _permission: 'access content'

```

And here's src/Controller/HomepageController.php:

```
<?php

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

class HomepageController extends ControllerBase {
  public function content() {
    return [
      '#type' => 'markup',
      '#markup' => 'Hello World from the HomepageController',
    ];
  }
}

```

But when I navigate to http://localhost/tsa, I just get **Page Not Found**.

Why doesn't it work? How should I go about doing this?

# Answer
This is a classic case of trying to do something in the non-Drupal way -- conceptually, defining a custom route for your home page route makes sense, and it's possible in other frameworks, but Drupal has a different way of doing things that makes this approach completely unintuitive.

Here's how to do it:

1. Define your route as something other than '/' (i.e. '/students/overview')
2. In /admin/config/system/site-information, set your "Default Front Page" to whatever your route was:

Voila!
> 6 votes

# Answer
Also looking at your code you presented above, you have a typo.

'acess content' should be 'access content'
> 0 votes

---
Tags: routes, page-controller
---


# Question
Title: How to add existing fields to a custom form?
I have a custom form which shows the title field and a view embedded into the form. Both form and the view are updated via Ajax. I am trying to add the body field, but it is not showing up.

This is my form

```
/**
 * Provide a form.
 */
function MYMODULE_form($form, &$form_state) {

  $form['wrapper'] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'mywrapper',
    ],
  ];

  $form['wrapper']['node_form'] = [
    '#type'  => 'fieldset',
    '#title' => t('Add article'),
  ];

  $form['wrapper']['node_form']['node_title'] = [
    '#type'     => 'textfield',
    '#title'    => t('Article title'),
    '#required' => TRUE,
  ];

  $form['wrapper']['submit'] = [
    '#type'   => 'submit',
    '#value'  => t('Save'),
    '#submit' => ['MYMODULE_form_submit'],
    '#ajax'   => [
      'callback' => 'MYMODULE_MYCALLBACK',
      'wrapper'  => 'mywrapper',
    ],
  ];

  $form['wrapper']['view_display'] = [
    // view machine name && display/block name
    '#markup' => views_embed_view('nodes', 'block'),
  ];

  return $form;
}

/**
 * Do some validation.
 */
function MYMODULE_form_validate($form, &$form_state) {
  // Better do some validation.
  // Here or via #element_validate.
  // @see https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#element_validate
}

/**
 * Form submit. Node creation.
 */
function MYMODULE_form_submit($form, &$form_state) {

  global $user;
  $node = new stdClass();

  $node->type     = 'article';
  $node->title    = $form_state['values']['node_title'];
  $node->language = LANGUAGE_NONE;
  $node->uid      = $user->uid;

  node_object_prepare($node);
  node_save($node);

  // Empty out title field on rebuild.
  $form_state['input']['node_title'] = '';

  // Rebuild form.
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback to return the whole wrapper.
 */
function MYMODULE_MYCALLBACK($form, &$form_state) {

  return $form['wrapper'];
}

```

# Answer
The field system in Drupal is a bit complex, but I will try to explain.

It starts with the field type. This is the same `#type` you are referring to in your form, or the type a field instance will refer to. The field types are defined in `hook_field_info()`. This defined the options a field can have, the default form render mode (widget) and the default display render mode (formatter).

The attachment of such a field to an entity is performed by a field instance. A specific implementation of a specific field for a specific entity, which can have an overridden widget or formatter and its own settings.

Since you are creating a custom form, you have no association with the entity form. This also means that you do not have access to the field instances that one would normally find on an entity.

You can try to:

* Load the node\_form to obtain a part of the original entity form.
* Attach the original field instances to your form with `field_attach_form('node', $node, $form, $form_state, entity_language('node', $node));`
* create a custom form element of type `text_with_summary` to replicate the default body field.
> 3 votes

---
Tags: 7, views, forms
---


# Question
Title: Custom POST Resource Not Working but GET is
I created a custom resource and my GET Resource works but my POST does not:

```
<?php

namespace Drupal\xeno_dashboard\Plugin\rest\resource;

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

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

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

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

    $this->currentUser = $current_user;
  }

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

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {
    $response = ['message' => 'Hello, this is a rest service'];
    return  new ResourceResponse($response);
  }

  /**
   * Responds to entity POST requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function post() {
    $response = ['message' => 'Hello, this is a POST response!'];
    return  new ResourceResponse($response);
  }

}

```

This is the response from the POST:

```
{
    "message": "No route found for \"POST /snapshots\": Method Not Allowed (Allow: GET, HEAD)"
}

```

# Answer
> 1 votes
This is the code we are using to determine the POST path:

`$create_path = isset($definition['uri_paths']['create']) ? $definition['uri_paths']['create'] : '/' . strtr($this->pluginId, ':', '/');
 // BC: the REST module originally created the POST URL for a resource by
 // reading the 'https://www.drupal.org/link-relations/create' URI path from
 // the plugin annotation. For consistency with entity type definitions, that
 // then changed to reading the 'create' URI path. For any REST Resource
 // plugins that were using the old mechanism, we continue to support that.
 if (!isset($definition['uri_paths']['create']) && isset($definition['uri_paths']['https://www.drupal.org/link-relations/create'])) {
 $create_path = $definition['uri_paths']['https://www.drupal.org/link-relations/create'];
 }`

This would mean it is `/snap_shots_resource` as path, but you probably want to set a 'create' uri path to the value you want.

---
Tags: 8
---


# Question
Title: Add more info to entityreference autocomplete widgets
I'm using a simple entityreference field with "autocomplete" widget on a content type.

When I start to search something, the autocomplete function returns me only the title of the node. Is there a way to add some information? I would like to add created time, or nid.

I tried to create an "entityreference" view as widget, but It useful only to select contents with filter or others configurations.

How can I do?

# Answer
Maybe take a look at the Entity Browser module: https://www.drupal.org/project/entity\_browser

Or Content Browser, which is specifically designed for nodes: https://www.drupal.org/project/content\_browser

I haven't used it yet, but it's on my want-to-learn list. I think it does what you want.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Can I define the minimum php version for my module in my .info.yml file?
I need to define the minimum PHP version in my module.info.yml file but I don't know if this is posible using:

```
php: 5.6

```

If you search about this in the drupal.org documentation you will only see the reference about this in the theme.info.yml file: Defining a theme with an .info.yml file

> **php (optional)**
>
> The minimum version of PHP required. Defaults to value of `DRUPAL_MINIMUM_PHP` constant.
>
> `php: 5.5.9`

But in the documentation about the module.info.yml file there is nothing about the php version: Let Drupal 8 know about your module with an .info.yml file.

So, really I can't define the minimum php version in my module.info.yml file?

# Answer
Sometimes the answer to a question is best found by trying. If you add `php: 8.0` to your module.info.yml file you will see this:

So it can still be used. (I have updated the linked documentation as well.)
> 4 votes

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


# Question
Title: Embedding a webform inside a node content
I need to embed a webform inside content, which is a node. How can this be implemented?

# Answer
> 7 votes
There are several ways to do this. The method I normally use it to make a custom Panel page for my node. The content area will contain the "node being viewed" as well as a custom block that renders out my form.

The easiest way, though, is to use the Webform module, and you can build your forms with the UI and easily attach them to a content type.

# Answer
> 7 votes
I think this function (embed webform in a node) is available in the latest Webform module.

Goto content \> your-webform-node \> edit \> webform \> form settings \> advanced settings \> available as block.

# Answer
> 4 votes
In case you are using the webform module mentioned by the others (i prefer that solution too) and want to **render the form manually in php** use this snippet:

```
$block = module_invoke('webform', 'block_view', 'client-block-370');
print render($block['content']);

```

with 370 being the node\_id of your webform, the rest of the parameters don't have to be changed.

# Answer
> 3 votes
To embed a webform inside content, you can create a token which can return a webform content programatically. Or create a block which can render a webform and place the block next or inside the content.

### Drupal 8

Here is example how to render a webform:

```
$output = \Drupal::entityManager()->getViewBuilder('webform')->view($my_form);

```

You can also embed it as a block entity:

```
$block = \Drupal\block\Entity\Block::load('myBlockID');
$block_content = \Drupal::entityManager()
   ->getViewBuilder('block')
   ->view($block);

```

Source: How to embed a Webform?

# Answer
> 0 votes
If I understand your requirement correctly I think this module will be useful - Webform Template

And using this patch from http://drupal.org/node/1430752(even for version 7.x-1.2) and following the few changes as mentioned in comment #4 you can even select a default template for each content type.

Hope this helps.

---
Tags: webforms
---


title: Setting multisite in WAMP

text:
# Question
Title: Setting multisite in WAMP
I have created folder structure like below:

Main Drupal: www\_d8multisite\_com

```
Subsite1: www_d8multisite_com/sites/default/ms1
Subsite2: www_d8multisite_com/sites/default/ms2

```

And put the sites.php inside

```
www_d8multisite_com/sites/sites.php

```

and defined my multisite like below:

```
$sites['www.d8ms1.com'] = 'ms1';
$sites['www.d8ms1.com'] = 'ms2';

```

And put the settings.php in both subsite folders like below:

```
Subsite1: www_d8multisite_com/sites/default/ms1/settings.php
Subsite2: www_d8multisite_com/sites/default/ms2/settings.php

```

Then I setup my virtual host like below:

```
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "H:/wamp/www/www_d8multisite_com"
    ServerName www.d8ms1.com
    ServerAlias www.d8ms1.com
    ErrorLog "logs/www.d8ms1.com.error.log"
    CustomLog "logs/www.d8ms1.com-access.log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "H:/wamp/www/www_d8multisite_com"
    ServerName www.d8ms2.com
    ServerAlias www.d8ms2.com
    ErrorLog "logs/www.d8ms2.com.error.log"
    CustomLog "logs/www.d8ms2.com-access.log" common
</VirtualHost>

```

Still my multiste is not working. If I'm trying to access any of the subsites(www.d8ms1.com or www.d8ms2.com) it only pointing to base site. I mean site is still loading from base www\_d8multisite\_com. not from sub folders.

Am I doing something wrong in the configuration? or I missed any step?

# Answer
> 0 votes
I have never really used multi site much, but I have read the documentation multiple times nevertheless.

It always was my understanding that the `default` folder was reserved for the default site, and that all other folders should be placed next to it, not inside of it.

Next to that, the documentation implies that your folder name should match a certain pattern, based on the site url.

Instead of using `www_d8multisite_com/sites/default/ms1` I'd try using `www_d8multisite_com/sites/d8ms1.com` instead.

---
Tags: multi-sites
---


# Question
Title: Instantiate and load a block programmatically in twig template
I created a simple block that shows some text grabbed from an external source, and it renders as expected when I place it from the back-end (Structure-\>Block Layout).

But I want to be able to place it via code only inside a twig template from the theme directory. I thought I would use {{ drupal\_block('id defined in Block.php') }} from the Twig tweak module but it never works unless the block is first placed from the back-end which assigns it a machine name then I can display it anywhere using that machine name in drupal\_block() instead of the id I defined in its source code.

So how can I instantiate it programmatically first and then place it the the twig template I want?

During my search I came across Plugin Derivatives, I don't know if it is the solution I want, or how to use it.

# Answer
I am sure there are other ways to solve this problem, but here is how I would do it.

Create your block, then go to admin/structure/block and place your block under "Disabled" list. You can then implement hook\_preprocess\_node in your .theme.php file.

### theme file:

```
/**
 * Implements hook_preprocess_node()
 */

function mytheme_preprocess_node(&$variables) {
 $block = \Drupal\block\Entity\Block::load('block_id');
  if ($block) {
    $variables['my_custom_block'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
  }
}

```

### In your template twig file:

```
{% if my_custom_block %}
 {{ my_custom_block }}
{% endif %}

```

You just have to make sure that your block\_id correct.
> 1 votes

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


# Question
Title: How to display default image in Drupal 8
I have an image field that has a default image if no image is uploaded. In mytheme.theme file I am trying to get the default image and display it. Here is the code that I am using:

```
$field = $entity->get($fieldName); // Loading from field definition
if ($field) {
  $default_image = $field->getSetting('default_image');
  if ($default_image && $default_image['uuid']) {
    $entityrepository = Drupal::service('entity.repository');
    $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
    if ($defaultImageFile) {
      $image_uri = $defaultImageFile->getFileUri();
    }
  }
}

```

The issue is that the $default\_image\['uuid'\] is empty. I am not sure how that can be if the default image is set. Since the image uuid is empty, the image cannot be loaded and now I am stuck.

What is wrong with the code that I am using? Or is there another way to accomplish this that works?

# Answer
Instead of doing this in code, the Drupal core image fields provide a default image setting in the UI as well.

If you navigate to an image field in the UI (Structure \> Content types \> \[Add/Edit a content type\] \> Manage fields \> \[Add/Edit image field\]), you can upload a default picture that will be used by Drupal in case no image was provided.
> 1 votes

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


# Question
Title: views_get_view in combination with i18nviews only translates part of header
I'm using the following code to get a view and render it

```
  $view = views_get_view('viewname');
  $view->set_display('page');

  $view->set_arguments(array($type));

  $view->pre_execute();
  $view->execute();

  return $view->render();

```

Works great but some fields of the exposed filters and the header are not getting translated. I'm using the i18nviews modules.

Any ideas?

Thanks

# Answer
> 0 votes
Using the following code triggers i18nviews correctly:

```
$view = views_get_view('viewname');
$view->set_display('page', array($type));

```

---
Tags: 7, views, i18n-l10n
---


title: drupal 8 block not working

text:
# Question
Title: drupal 8 block not working
```
<?php

/*
 * To change this license enter code here code here`e header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Drupal\hello_world\Plugin\MyCustomBlock;
use Drupal\Core\Block\BlockBase;
/*
 *  @block
 * id = "mycustomblock"
 * admin_label = @Translation("mycustomblock"),
 */
class MyCustomBlock extends BlockBase{
  /**
   * {@inheritdoc}
   */
  public function build() {
      return array('#markup' => 'test block');
  }
}

```

I just create a test block and want to place into content region from admin panel. Above is my code, but I can't see any block in the admin panel, can anybody help, what I am missing?

# Answer
I think your block definition must be like this :

```
 /*
  *  @block(
  * id = "mycustomblock",
  * admin_label = @Translation("mycustomblock")
  * )
  */

```

See : Create a custom block
> 1 votes

---
Tags: 8, blocks
---