# Question
Title: Custom module block programmatically assigning it to a specific role
I have a Custom module that implements a block how do I programmatically assign it to a specific role or roles in drupal 8?

# Answer
This is how I did it.

```
function _<module-name>_check_user_access() {
  $roles = [
    'editor',
    'admin',
  ];

  $current_role = \Drupal::currentUser()->getRoles();
  foreach($roles as $role) {
    if($role == $current_role[1]) {
      return TRUE;
    }
  }

  return FALSE;
}

```

See my blog post for more information about it
> 0 votes

---
Tags: blocks
---


# Question
Title: Updating core with Composer doesn't work
I am on D 8.3.0-rc2 and want to update to D 8.3.0 stable. Composer is my only option (requirement of address module). Composer core update doesn't bring me beyond 8.3-0-rc2, not even forcing it. Running `drush composer require "drupal/core:^8.3@stable"` gives me the following output:

> ./composer.json has been updated
> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Nothing to install or update

The content of composer.json is the following.

```
{

"name": "drupal/drupal",
"description": "Drupal is an open source content management platform powering millions of websites and applications.",
"type": "project",
"license": "GPL-2.0+",
"require": {
    "composer/installers": "^1.0.21",
    "drupal/core": "^8.3@stable",
    "wikimedia/composer-merge-plugin": "~1.3",
    "drupal/address": "~1.0",
    "drush/drush": "^8.1"
},
"replace": {
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "preferred-install": "dist",
    "autoloader-suffix": "Drupal8"
},
"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
},
"autoload": {
    "psr-4": {
        "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
    }
},
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},
"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
}
}

```

I read about deleting vendor and composer.lock, but I don't understand why this would work.

# Answer
> 3 votes
Instead of trying to update Drupal directly with Composer, instead try starting with drupal-composer/drupal-project as a starting point. This project definitely works with Drupal 8.3.0.

Set up a new project with drupal-composer/drupal-project, and use `composer require` to add any modules you need. Once your code is the same in the new project as the old, you should be able to just copy the database over (or just point to your existing database with settings.php) and run updatedb.

# Answer
> 0 votes
You already have the right version in your composer.json. Then it's just `composer install` (in your case it's `drush composer install`).

If that not works, delete your lock file and/or the vendor folder prior to calling `composer install` (or `drush composer install`).

And I guess `composer update drupal/core` (in your case `drush composer update drupal/core`) might work as well (since the version in your lock file or in the vendor folder is different from that in your composer.jon).

---
Tags: 8, drush, updating
---


title: Drupal 8 Valid_url()

text:
# Question
Title: Drupal 8 Valid_url()
In Drupal 7 we use `valid_url`, but what is the replacement in Drupal 8 for it? I tried it but it the function is undefined. Finally I found the solution, see my answer.

# Answer
Visit this to find an answer of this question. https://drupaltreasure.blogspot.in/2017/04/drupal-8-validurl.html

The content of the provided link:

1. First, include class namespace `use Drupal\Component\Utility\UrlHelper;`
2. then use this function, No need to create the object because it is a static function so we can call it by its class name: `UrlHelper::isValid($url, $absolute = FALSE);`

Parameters:

$url : The URL to verify bool

$absolute: Whether the URL is absolute
> 0 votes

---
Tags: 8
---


# Question
Title: Multi-step and multipage Registration Form with Field_group module
My drupal is 7 .

I use field\_group module For grouping field and multipage registration form.

When I Add multipages to account fields only 2 groups of these fieldgroups work and other field groups show on bottom of first step. I set field group and multipage group and multipage widget on field settings. For content type everythings is work correctly but for user registration Form Some steps ignored.

Have anybody same problem?

Have any idea for multistep registration form with Drupal.?

# Answer
You can have a look at these modules:

https://drupal.org/project/ctools https://drupal.org/project/mforms

Make sure to go through their documentation for more information on how to create the multistep registration page.

You may also want to take a look at this tutorial:

http://www.grasmash.com/article/building-multistep-registration-form-drupal-7-using-ctools

And you might also have a look at this module: https://www.drupal.org/project/step

Regards,
> 0 votes

# Answer
I reinstall My drupal site and use field\_group module for secound time , this time everything is normal and steps are added to forms.

Thank you for responses.
> 0 votes

---
Tags: users, commerce, entities
---


title: Autocomplete 403s when behind a proxy

text:
# Question
Title: Autocomplete 403s when behind a proxy
I've got a virtualbox VM setup as a proxy server between Drupal to try to replicate a CDN causing errors on a client's machine.

My current port is as follows: `http://site-name.dd:9999`

When I go to the proxy-enabled site, and try to use a given entity reference, I get a 403 error:

```
An AJAX HTTP error occurred.
HTTP Result Code: 403
Debugging information follows.
Path: http://site-name.dd:8086/index.php?q=entityreference/autocomplete/single/field_guardians/participant/player/NULL
StatusText: Forbidden
ResponseText:
Access denied | Site Here
Skip to main content
Site Title Here
Main menuName
Another Name
A Third Name
Products
Access denied                                        You are not authorized to access this page.

```

My guess is that this is due to me trying to access via port 9999, and the direct site being on 8086.

I believe a similar (though perhaps not exact issue) is also facing the client. How do I deal with this AJAX error? Has anyone seen anything like this?

This is for a D7 site.

EDIT:

I have also tried changing these settings in settings.php:

```
$conf['reverse_proxy'] = TRUE;

```

And alternatively setting one of these two and testing with each, with no success:

```
$conf['reverse_proxy_addresses'] = array('10.1.0.157');

$conf['reverse_proxy_addresses'] = array($_SERVER['REMOTE_ADDR']);

```

EDIT 2:

From what I can find, the error is because it is getting the original server port from the autocomplete field input element value. So either I need a way for the 8086 port to recognize the 9999 port as legitimate or I need to switch to the 9999 port as correct.

# Answer
Here are some pointers:

* Set a global `$base_url = 'http://example.com:9999'` as mentioned by Clemens Tolboom. This should be the easiest.
* Implement hook\_url\_outbound\_alter and change the `options.base_url` as per your requirements (for every internal request).
* Configure the server to work with both the ports? I wonder why are you using 2 ports for the same site though
> 0 votes

# Answer
You should set your Base URL to

```
$base_url="http://site-name.dd:9999";

```

From default.settings.php

> If Drupal is generating incorrect URLs on your site, which could be in HTML headers (links to CSS and JS files) or visible links on pages (such as in menus), uncomment the Base URL statement below (remove the leading hash sign) and fill in the absolute URL to your Drupal installation.
> 2 votes

# Answer
You can set your reverse proxy settings in your web server configuration with the port details. It will work and will not cause any error on autocomplete field.

For apache:

```
<IfModule mod_proxy.c>
SSLProxyEngine on
ProxyRequests Off
ProxyPreserveHost On

SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
RequestHeader set X-Forwarded-Proto 'https'

ProxyPass "/" "https://base-url/"
ProxyPassReverse "/" "https://base-url/"
ProxyHTMLURLMap "https://base-url/" "/"

<Location />
    ProxyPassReverse /
    ProxyHTMLEnable On
    ProxyHTMLURLMap / /
    RequestHeader unset Accept-Encoding
</Location>

```
> 0 votes

---
Tags: 7, entities, ajax
---


# Question
Title: Way to have a theme-settings form input to accept numbers only?
I am creating some theme settings and am creating a form to populate them in `theme-settings.php`. I am using the hook `hook_form_system_theme_settings_alter()`.

I would like to restrict or verify that only numbers can be entered into a field. I've searched online but have not found how to do this. Would anyone know what I ought to add to my code?

Code currently looks like:

```
$form['mysite_theme']['mysite_contact_phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Contact Number'),
    '#default_value' => $default['mysite_contact_phone'],
    '#description' => t('Enter the main contact number for this site.'),
    '#required' => TRUE,
  );

```

# Answer
> 1 votes
You should be able to add your own validation handler. After the code you've shown, add this:

```
$form['#validate'][] = 'my_validation_handler';

```

Then in your handler, you can add your own validation:

```
function my_validation_handler($form, &$form_state)
{
  if(!is_numeric($form_state['values']['mysite_contact_phone']))
  {
    form_set_error('mysite_contact_phone', t('Contact number must be numeric'));
  }
}

```

# Answer
> 0 votes
You can use Elements module to get a HTML5 number field.

---
Tags: 7, forms
---


title: Fatal error on content save

text:
# Question
Title: Fatal error on content save
I recently set up a local version of a remote site. The remote site is allowing me to create content fine, but for some reason the local version is throwing the following error upon save:

`Drupal\Core\Entity\EntityStorageException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) ORDER BY users_field_data_2.name ASC' at line 4: SELECT base_table.uid AS uid, base_table.uid AS base_table_uid, users_field_data_2.name AS name FROM {users} base_table INNER JOIN {users_field_data} users_field_data ON users_field_data.uid = base_table.uid INNER JOIN {user__roles} user__roles ON user__roles.entity_id = base_table.uid LEFT JOIN {users_field_data} users_field_data_2 ON users_field_data_2.uid = base_table.uid WHERE (users_field_data.status = :db_condition_placeholder_0) AND (user__roles.roles_target_id IN ()) ORDER BY users_field_data_2.name ASC; Array ( [:db_condition_placeholder_0] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).`

This error also crops up on some admin pages, which seems to be related: `Warning: Invalid argument supplied for foreach() in Drupal\Core\Database\Query\Condition->compile() (line 227 of core/lib/Drupal/Core/Database/Query/Condition.php).`

I've done a handful of updates to the site since creating the local version but haven't tried creating new content until now, so it's hard to tell what started causing the error. Any suggestions on how to move forward with diagnosing this?

# Answer
I realized that it must have been a database issue since the live and local sites were in sync except for some module installs -- same with the code. I pulled the live database and imported it into local and re-installed the modules one at a time. Everything is now working fine. All that I can figure is that there was an installation error somewhere along the way that didn't want to show itself.
> 0 votes

# Answer
This is a database issue and one method is to replace the `settings.php` file for d8 .

* Update your changes on the new file with local database details.
* Clear cache using drush. `drush cr`
> 0 votes

---
Tags: 8, nodes
---


title: Updating a module field schema

text:
# Question
Title: Updating a module field schema
I'm currently working on a project created by someone else. I have a textfield called "city". Currently the maximum limit is 255 characters. I want to update the maximum character to be 100. Looking at the code, it looks like the field was created using the features module. When I try to update the field, I got the FieldUpdateForbiddenException. I understand this is because I have value in the database. Is there a way update the field even if there is value in there? If I can't modify the database, can I change textfield max length in the form to be 100?

Thanks!

The website doesn't have CCK, so I'm not sure how to modify these fields. I'm using Drupal 7.

What I did: 1. I upgraded registration\_page.info to upgrade the version from 7.x-1.0 to 7.x-1.1 2. I changed the field max length to 100 in registration.features.field.info

When I tried to deploy, I got this error

```
  [sshexec] WD php: FieldUpdateForbiddenException: field_sql_storage cannot          [error]
  [sshexec] change the schema for an existing field with data. in
  [sshexec] field_sql_storage_field_update_forbid() (line 229 of
  [sshexec] /var/lib/www.mine.com/deploys/site_20140515_140323/modules/field/modules/field_sql_storage/field_sql_storage.module).
  [sshexec] Cannot modify header information - headers already sent by (output     [warning]
  [sshexec] started at
  [sshexec] /var/lib/www.mine.com/deploys/site_20140515_140323/sites/default/drushrc.php:2)
  [sshexec] bootstrap.inc:1212
  [sshexec] FieldUpdateForbiddenException: field_sql_storage cannot change the schema for an existing field with data. in field_sql_storage_field_update_forbid()

```

This is what the code look like in registration.features.field.info

```
 // Exported field: 'node-registration-page-field_city'.
  $fields['node-registration_page-field_city'] = array(
    'field_config' => array(
      'active' => '1',
      'cardinality' => '1',
      'deleted' => '0',
      'entity_types' => array(),
      'field_name' => 'field_city',
      'foreign keys' => array(
        'format' => array(
          'columns' => array(
            'format' => 'format',
          ),
          'table' => 'filter_format',
        ),
      ),
      'indexes' => array(
        'format' => array(
          0 => 'format',
        ),
      ),
      'locked' => '0',
      'module' => 'text',
      'settings' => array(
        'max_length' => '255',
      ),
      'translatable' => '0',
      'type' => 'text',
    ),
    'field_instance' => array(
      'bundle' => 'registration_page',
      'default_value' => NULL,
      'deleted' => '0',
      'description' => 'Please enter your city',
      'display' => array(
        'default' => array(
          'label' => 'above',
          'module' => 'text',
          'settings' => array(),
          'type' => 'text_default',
          'weight' => 31,
        ),
        'teaser' => array(
          'label' => 'above',
          'settings' => array(),
          'type' => 'hidden',
          'weight' => 0,
        ),
      ),
      'entity_type' => 'node',
      'field_name' => 'field_city',
      'label' => 'City',
      'required' => 0,
      'settings' => array(
        'text_processing' => '0',
        'user_register_form' => FALSE,
      ),
      'widget' => array(
        'active' => 1,
        'module' => 'text',
        'settings' => array(
          'size' => '60',
        ),
        'type' => 'text_textfield',
        'weight' => '26',
      ),
    ),
  );

```

# Answer
> 0 votes
As you mentioned, you already have textfield with 255 character length and also contains data. If you want reduce length of this field then you need to make sure that there is no data within this field having more than 100 character length. Because if this field contains any data more than 100 character length then you can't alter it in this way. My suggestion to you is first take backup of this table and empty this table. Then you would be able to change its length and then you can import this table data. If there is any data more than 100 character either it will stored in truncated way or give you any warnings for this. One thing you need to remember you need to do this offline, this question is specific to database and take care of every piece of data. There is possibility you might need to make some changes manually, so should take data base backup first.

# Answer
> 0 votes
If you can't take the site offline, you can write custom code for validation of character length of your text field in your custom module.

Just get the value of your text field before saving to database and count the length and decide to save or generate error.

For ex field is used in node then implement hook\_node\_presave() or in hook\_form\_alter define $form\['#validation'\] function and generate error if length is greater than 100.

if you want to put this only on new addition of fields then you can check $op for new tag else just check when the user will edit the existing field it will check the length.

Hope it helps.

---
Tags: entities, features
---


# Question
Title: How do I restrict the date popup to 12 months from start date?
I have a custom module where I set two date pop-ups.

```
$form['set_start_date'] = array(
  '#type' => 'date',
  '#title' => t('set start date'),
  '#required' => TRUE,
);

$form['set_end_date'] = array(
  '#type' => 'date',
  '#title' => t('set end date'),
  '#required' => TRUE,
);

```

If I select 2017-04-12 as start date, the accepted end date should not be after 2018-04-12.

How can I achieve this?

# Answer
> 0 votes
Following Method i used to restrict the date Pop-up to 12 months

```
$form['set_start_date'] = [
      '#title' => $this->t('START DATE '),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];

 $form['set_end_date'] = [
      '#title' => $this->t('END DATE'),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Filter'),
    );

 return $form;
}

```

---
Tags: datetime
---


# Question
Title: Using File (Field) Paths with token value from Entity Reference field
I am using Drupal 8.3.1 and using the module File (Field) Paths to define the path and filename. I want to use the value of a taxonomy field (Entity reference in CCK) in the same content type as part of the filename. The machine name of the field is *field\_organization* and doing *\[node:field\_organization\]* produces an href link where I want is just the name of the single value it contains. How do I get only the term's name instead?

# Answer
> 2 votes
Try to append `:value` to the field:

```
[node:field_organization:value]

```

For a reference field something like this:

```
[node:field_organization:0:entity:name]

```

If you want to look up all available tokens install the Token module and go to */admin/help/token*.

---
Tags: 8, tokens
---


title: Get more sub level for in menu

text:
# Question
Title: Get more sub level for in menu
I'm able to get second level of the main menu by using below code.

```
$menu = '';
$menuItems = menu_tree_page_data('main-menu');
foreach($menuItems as $key => $m) {
    if ($m['link']['in_active_trail'] && $menuItems[$key]['below']) {
        $menu = render(menu_tree_output($menuItems[$key]['below']));
   }
}
print $menu;

```

If I want to get 3rd (like in image below), 4th or 5th level. how this will be done.

# Answer
It is necessary that you want to display this using code?

I have a better solution for you. You can try with this module Menu Block for above achievement
> 1 votes

# Answer
I have found a module named Nice\_Menus that works for me.
> 0 votes

---
Tags: 7, navigation
---


# Question
Title: How to change programmatically exposed filters in views
I have a page view with exposed filters. One of the filters is term vocabulary, and that's dropdown list, user can select only one category (term).

I want to set programmatically one term from dropdown list when I came from specific URL. I tried with `views_query_alter` where `$category` is `tid`.

```
 $set_exposed_input  = array();
 $set_exposed_input['field_category_tid'] = $category;

 if ($set_exposed_input) {
    $view->set_exposed_input($set_exposed_input);
 }

```

# Answer
For drupal 7 you can use

```
$view->exposed_input[$key] = $value;

```

This is

```
$view->exposed_input['title'] = 'My title is a cat';

```

For a full example you can try this:

```
$name = 'name_of_view';
$display = 'page_1';
$alter = array('exposed' =>array('title' => 'title_value'));

$view = views_get_view($name);
$view->init_display($display);
$view->preview=TRUE;
$view->is_cacheable = FALSE;

if(isset($alter['exposed'])){
  foreach($alter['exposed'] as $key => $valor){

     $view->exposed_input[$key] = $valor;

  }
}

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

print_r($view->result);

```

Other way is using the views set\_option function

```
$filters = $view->display_handler->get_option('filters');

foreach($alter['exposed'] as $key => $valor){
   $filters[$key]['value'] = $valor;
   $view->display_handler->set_option('filters', $filters);
}

```
> 15 votes

# Answer
with Drupal 7.54 when you want to process the exposed filter programmatically, this is how you do it when you have a multiple valued field. The solution to see how to pass exposed filter is to follow how the URL is made.

Here: view\_name?alias\[1\]=1

```
$view = views_get_view('view_name');
$view->init_display('display_id');

$filters = array('alias' => array('1'));
$view->set_exposed_input($filters);

$view->execute();

```

You can execute this from wherever you want. Preferably from the module file.
> 2 votes

# Answer
Set exposed filter value like this:

```
$view->exposed_input['field_category_tid'] = $category;

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: What is the correct way to organise and separate functions in a Controller into their own files?
Here is my *test.routing.yml*:

```
test.alpha:
  path: '/test/alpha'
  defaults:
    _controller: Drupal\test\Controller\TestController::testAlpha
    _title: 'Alpha'
  requirements:
    _permission: 'access content'

test.bravo:
  path: '/test/bravo'
  defaults:
    _controller: Drupal\test\Controller\TestController::testBravo
    _title: 'Bravo'
  requirements:
    _permission: 'access content'

sitelog.charlie:
  path: '/test/charlie'
  defaults:
    _controller: Drupal\test\Controller\TestController::testCharlie
    _title: 'Charlie'
  requirements:
    _permission: 'access content'

```

Here is my Controller: *TestController.php*:

```
namespace Drupal\test\Controller;

class TestController {
  public function testAlpha() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
  public function testBravo() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
  public function testCharlie() {
    return array(
      '#type' => 'markup',
      '#markup' => 'Hello, World!',
    );
  }
}

```

My Controller file is set to grow. I will be adding many more functions, and adding hundreds of lines of code to all of those functions.

**What is the correct way of organising and separating out those functions into their own files, in a Drupal 8 project?**

In Drupal 7 we used *.inc* files to keep files from getting too large. Sometimes a *common.inc* would be used to group reusable functions.

What I like about React is that functionality is broken up into separate components, into separate files. I prefer lots of files, containing a small amount of code, organised into folders.

I'd like to bring this same approach into my Drupal 8 projects, but follow the correct PHP standards/Drupal best practice. My goal being to improve: the readability of my code, ease of finding my code, and possibly, the organisation of reusable code.

# Answer
There are a few things that you can do.

1. As already suggested by Jaypan, you can have as many controllers as you like, grouped by whatever makes sense for you. You can also have a base classes/hierarchy and re-use code through that
2. You can define services and also static classes/methods to extract re-usable logic (or also not-reusable logic). I'd say that's the 1:1 replacement for functions in include files. Services are defined in a yourmodule.services.yml and you can use dependency injection to make each service self-contained with explicit dependencies to other systems, so that you can also write (unit) test for that code.
3. You can also use Traits, a relatively new PHP feature that basically allows you to put a few methods into a separate file and include it in one or several classes where you can use them internally as if they were defined on that class. Kind of like a base class except that you're not limited to a single trait, you can have as many as you want.
> 4 votes

# Answer
You're doing it correctly the way you are doing it. If you really want to split it into multiple files for readability, then you can create multiple controllers, grouping them by type. For example, I'll often have a PageController and an AjaxController in a module, putting anything that returns an AjaxResponse into the AjaxController, and anything that returns a render array into the PageController.

This isn't required, but it will keep your files shorter and more readable. That said, for controllers, the search function in any IDE makes it pretty easy to find whichever callback you need in a flash.
> 2 votes

---
Tags: 8
---


title: Alternative to field_attach_update

text:
# Question
Title: Alternative to field_attach_update
In Drupal 7 we were able to use `field_attach_update($entity_type, $entity)` to update fields without having the need to update the whole node. `$node->save()` is very heavy and calls many hooks in between.

With the coming of Drupal 8, `field_attach_update` was deprecated. Is there an alternative to it, and what is it if yes?

In my case I'm updating two image fields programatically and don't want to call `$node->save` in order to not trigger all the other hooks.

# Answer
> 3 votes
There is no alternative, saving an entity is the only supported API.

Saving will only update the configurable field tables if it detects a change, and we plan to implement similar logic for the base tables as well.

But the hooks are still called and there is no supported way to prevent that.

---
Tags: entities
---


# Question
Title: How to send a mail to a user with views rules when a date is passed?
I have created a date field for all users (in Drupal 7). This date is the end of the user's subscription. When the date of this field is passed, I want to send a mail to the user to tell him he can subscribe again (to access our website).

So, I have created a view with a display rules (with module views rules). I have listed all users who have the field date not empty and filter to have only date passed. I have 2 fields in this view (user name and date). I have edited field info and enable my 2 fields (Data type : user and data type : date) :

After, I have created a rule wich react on the event "Cron maintenance tasks are performed" and created a view loop on the display rules of my view. In the loop i have added 2 actions : change the date value to exit the user from the view, and send a mail to this user :

When I Launch the cron, nothing happen. The date is not changed, and the mail is not send. I don't know what configuration I have forgot. Do you have an idea please ?

Thank you for help me.

My rule in export format:

```
{ "rules_relance_e_mail" : {
"LABEL" : "Relance e-mail",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "cron" : [] },
"DO" : [
  { "VIEW LOOP" : {
      "VIEW" : "dates_de_relances",
      "DISPLAY" : "views_rules_1",
      "ROW VARIABLES" : {
        "name" : { "name" : "Nom" },
        "field_date_de_relance" : { "field_date_de_relance" : "Date de relance" }
      },
      "DO" : [
        { "data_set" : { "data" : [ "field-date-de-relance" ], "value" : "+1 year" } },
        { "mail" : {
            "to" : [ "name:mail" ],
            "subject" : "Test relance",
            "message" : "Test mail",
            "language" : [ "name:language" ]
          }
        }
      ]
    }
   }
  ]
 }
}

```

# Answer
### Part 1: Sending an eMail

Your view needs refinement ...You seem to have 1 Views result (row) for each user to be eMailed, which is OK. But that view must have fields (columns) for each of the fields that you want to use in your Rules Action to create your eMail. So the `[name:mail]` and `[name:language]` in your Rules Action should be replaced by some column in your view to make those available. For that you might have to also add a "relationship" in your view to the "user object" (so that eg the eMail ID becomes available).

Have a look at these answers for some more details:

### Part 2: Saving the changed date

You may have to add an extra Rules Action to "save an entity", because you need to remind the Rules module to also save the date you've updated.
> 1 votes

---
Tags: views, rules, emails, cron
---


# Question
Title: How to pass same contextual arguments to two view blocks programmatically?
I'm trying to pass same arguments to views. Here is my code:

```
$view = Views::getView('taxonomy_articles');
            if (!empty($age)) {
              $view->setDisplay('block_6');
              $view->setArguments([$term->tid, $age_args]);
              /*
               * override term name with age param
               */
              $termURL = Url::fromRoute('entity.taxonomy_term.canonical', array('taxonomy_term' => $term->tid, 'age' => $age));
              $termName = \Drupal::l(t($term->name), $termURL);
            }
            else {
              $view->setDisplay('block_1');
              $view->setArguments([$term->tid]);
            }

```

My `else` part gets executed and array of term ids goes to block\_1, my view block machine name.

What I want is similar like:

```
              else {
                  $view->setDisplay(['block_1','block_7']);
                  $view->setArguments([$term->tid]);
                }

```

Is this possible? Can we pass array to `$view->setDisplay` ???

# Answer
> 1 votes
While rendering a view you can only use on display. So it is only possible to loop through your display array and generate the view within that loop like:

```
          else {
              foreach (['block_1','block_7'] as $display) {
                $view->setDisplay($display);
                $view->setArguments([$term->tid]);
                // You need to render here.
                // The loop will overwrite the first display.
              }
            }

```

---
Tags: views, navigation
---


# Question
Title: PDOException: SQLSTATE[42S22] When adding quiz content
I am trying to implement the quiz module on a new website and it's throwing the following error when attempting to add content \> quiz. I believe the code I have was part of a feature I was trying to migrate over from a different website so I could retain the functionality involved with it, but it's proven to be less than compatible. (Going from Drupal Commons 7.50 to Plain Drupal with a demo theme built in 7.54).

Can someone interpret this error and point me in the right direction as to what the missing piece of the puzzle is here?

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'base.allow\_change\_blank' in 'field list': SELECT base.qnp\_id AS qnp\_id, base.vid AS vid, base.nid AS nid, base.uid AS uid, base.number\_of\_random\_questions AS number\_of\_random\_questions, base.max\_score\_for\_random AS max\_score\_for\_random, base.pass\_rate AS pass\_rate, base.summary\_pass AS summary\_pass, base.summary\_pass\_format AS summary\_pass\_format, base.summary\_default AS summary\_default, base.summary\_default\_format AS summary\_default\_format, base.randomization AS randomization, base.backwards\_navigation AS backwards\_navigation, base.keep\_results AS keep\_results, base.repeat\_until\_correct AS repeat\_until\_correct, base.quiz\_open AS quiz\_open, base.quiz\_close AS quiz\_close, base.takes AS takes, base.show\_attempt\_stats AS show\_attempt\_stats, base.time\_limit AS time\_limit, base.quiz\_always AS quiz\_always, base.time\_left AS time\_left, base.max\_score AS max\_score, base.allow\_skipping AS allow\_skipping, base.allow\_resume AS allow\_resume, base.allow\_jumping AS allow\_jumping, base.allow\_change AS allow\_change, base.allow\_change\_blank AS allow\_change\_blank, base.build\_on\_last AS build\_on\_last, base.show\_passed AS show\_passed, base.mark\_doubtful AS mark\_doubtful, base.review\_options AS review\_options, base.result\_type AS result\_type FROM {quiz\_node\_properties} base WHERE (base.vid IN (:db\_condition\_placeholder\_0)) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 351 ) in EntityAPIController-\>query() (line 187 of /Applications/AMPPS/www/example/docroot/profiles/cms/modules/contrib/entity/inc ludes/entity.controller.inc).

Here is how the process went:

* I implemented an online training feature from our current website for the new one
* It included syllabus and quiz content types, neither of which worked until I installed the Title module
* Once Title was installed, I received a new error only when trying to create content type quiz:

> EntityFieldQueryException: Unknown field: title\_field in EntityFieldQuery-\>fieldOrderBy() (line 954 of /var/www/html/example/docroot/includes/entity.inc).

* I updated the quiz from 7.x-5.0-alpha4+77-dev to 7.x-5.1 and all seemed well
* I removed a quiz field `field_syllabus_ref` and recreated it a different way, to reference the title of the syllabus page in the quiz.
* Now I get the error below unless the module is uninstalled. When it is uninstalled, I am still able to add quiz content but I get a different error instead after saving it.

# Answer
> 0 votes
The error was somehow related to the UUID module, which couldn't be disabled without derailing the entire website. Here's how I fixed it.

* uninstalled the feature that held the affected quiz module

`drush pm-disable <my_feature>
drush pm-uninstall <my_feature>`
* uninstalled the quiz module and all the modules dependent on it:

`drush pm-disable quiz
drush pm-uninstall quiz`
* moved the quiz module files to my temp backup outside the drupal root:

`mv sites/all/modules/contrib/quiz ../<temp_backups>/quiz`

* downloaded the quiz module fresh and reenabled it and all the dependent modules and reenabled the feature that contained it:

`drush dl quiz`

`drush en quiz`

That took care of this particular error.

**Please note:** I did not yet have any quiz data or content set up; this guideline is only safe for a dev environment. I have not tested it with any actual content or user data.

---
Tags: 7, features, quiz
---


title: Facebook get data

text:
# Question
Title: Facebook get data
I am not familiar in drupal 8. How do I get facebook information like posts, events, album, video? and want to be displayed as a node. can anyone help me on this.?

# Answer
You mean that you want people to register to you Drupal 8 site so they will be able to see their Facebook data? With Simple FB Connect you can give users the ability to register to Drupal by accepting the condition of your Facebook App and you'll be able to save data from their profile as nodes and display them later.

You need to use `hook_simple_fb_connect_registration` (see the function inside the module in order to understand how it works)
> 0 votes

---
Tags: 8, social-network
---


# Question
Title: Assigning roles and permissions Drupal 7
I have a hierarchy of roles which are Admin -\> shop\_admin -\> food\_manager / drink\_manager / supplies\_manager

So the Admin can edit the permissions of all the roles. Is there a way to allow the shop\_admin to edit the permissions of drink\_manager, food\_manager and supplies\_manager?

So basically my question is - Is there a way to give a user permission to manage other roles and permissions?

# Answer
> 1 votes
If you go on `www.yoursite/admin/people/permissions#module-user` you can decide witch kind of user can edit user permissions, so in your case only admin and shop\_admin.

Of course you do not want the shop\_admin to edit admin permissions, and all the pages where you can edit single user permissions are forms so you can use hook\_form\_alter in order to hide unwanted options or add conditions based on user role

---
Tags: users
---


# Question
Title: Send node as HTML formatted email to all users of a role
I have a RULE that works well:

1. After saving a new content of type DEMO
2. Send node as HTML formatted email Parameter: Send email to:doe@example.com,jane@test.com

What I need is to send the same Action but to a "users of a role", something like

1. After saving a new content of type DEMO
2. Send node as HTML formatted email Parameter: Send email to: Roles: Editor ---Rules does not allow to add roles here---

Is there any module that can expand this function in RULES? Or is there some way to achieve this directly within RULES? Thanks

# Answer
It may depend on your config. Here's a solution relying on Mime Mail and Mail System, as Mime Mail integrates smoothly with Rules.

Download and enable these 2 modules. Then you'll have a few steps configuring it :

1. **Mail System**: select *MimeMailSystem* in both "*Site-wide default MailSystemInterface class*" and "*Mime Mail module class*" drop-down list.
2. **Mime Mail**: change it from "*Plain text*" to "*Filter HTML*".

Now when you edit your rule, you'll see an action "*Send HTML mail to all users of a role*". Select editor role. You're done :)

Find even more details in this step by step tutorial: How to Send HTML Emails in D7 using Rules

**EDIT : Alternative solution**.

1. Download simplenews and enable both simplenews and simplenews rules. Set up the module.
2. Create a *editors newsletter*. Deactivate Subscription block
3. Enable "Use as simplenews newsletter" in the content type options you wish to send as HTML formatted email.
4. Create a rule : after editing a user account, condition user has role editor, subscribe user to newsletter editors (and reverse rule to unsubscribe)
5. Create a rule : after saving a node, condition content-type is..., send newsletter :The newsletter node to be sent.: \[node\]
> 1 votes

# Answer
Not exactly the same scenario, but this has step by step instructions on how to do something similar - might help guide you in the right direction.

Email users on node creation based on taxonomy reference
> 0 votes

# Answer
You can use Mime Mail module for this.

Add action rule as "Send HTML mail to all users of a role" and select the editor role from the dropdown.

Refer: https://www.webwash.net/how-to-send-html-emails-in-drupal-7-using-rules/
> 0 votes

# Answer
You could use the Views Rules to get this to work. Here is a blueprint of how to do so:

* Create a view of all users with role "Editor" (as in your question).
* Improve your existing rule to create a "Views loop", which is similar to a regular Rules loop, but allows looping over rows of view results.
* Within that "Views loop", perform a Rules Action to Send node as HTML formatted (similar to what you already have in your existing rule).

For way more details on this, refer to ("Option 2" of) my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?"
> 0 votes

---
Tags: nodes, rules, emails, users
---


# Question
Title: Is it possible to define default config entities in a single yml file?
Following drupal handbook I've created configuration entity type. All works fine except that I have to create ~100 default entities. It would be significantly easier to maintain these default entities if I could define them in a single YML file but that does not work as expected.

If I create files like this:

```
config/install/example.entity.id1.yml
config/install/example.entity.id2.yml
config/install/example.entity.id3.yml

```

The config entities are created correctly. However if I create one file `config/install/example.entity.yml`:

```
id1:
  field1: val1
  field2: val2

id2:
  field1: val1
  field2: val3

id3:
  field1: val4
  field2: val12

```

Drupal creates simple config with key `example.entity`. I'd expected it to create config entities as defined in schema file.

It would be real pain to manage those default config entities with 100 separate files instead of having everything in one yml file. Is this expected behaviour?

# Answer
According to Configuration Storage in Drupal 8:

> Configuration Entities must each be put into their own YAML files, and they should be generated by having the module write out its configuration (don't try writing them by hand).

So it sounds like what you're experiencing is indeed the expected behaviour, and for the time being at least, you'll need to separate each default entity into its own YAML file.
> 3 votes

# Answer
Little note to the yml code in the question.

In the drupal handbook looks the yml code for **example/config/schema/example.schema.yml** like this:

```
example.example.*:
  type: config_entity
  label: 'Example config'
  mapping:
    id:
      type: string
      label: 'ID'
    label:
      type: label
      label: 'Label'

```

In this case should the yml files, which are in the directory **example/config/install**, have the following names:

* **example.example.entity.id1.yml**
* **example.example.entity.id2.yml**
* **example.example.entity.id3.yml**

And the code of the yml files should contain also ids:

```
id: 1
label: Some text

```

---

(I've had similar problems as @SiliconMind and needed some time to find the correct way to add the default configuration...).
> 1 votes

---
Tags: 8
---


# Question
Title: Why am I getting redirect to node?destination=node when trying to login?
I just moved my site to another server, and when I try to login drupal redirects to a blank page. I have no idea what can I do? Please, help me. thanks for your support.

# Answer
> 0 votes
This link might able to help you. How to see the error messages when I get the white screen of death?

It might be .htacces problem. Maybe you should ask your hosting provider to help you solve this problem. My hosting provider always help me solve when this problem appear.

# Answer
> 0 votes
I assume you have placed your drupal website inside a folder in your webserver root eg. http://example.com/drupal. If that is the case in you .htaccess file uncomment `RewriteBase /drupal` and replace /drupal with name of your drupal root directory.

---
Tags: users, uri
---


title: How to set user status drupal 8

text:
# Question
Title: How to set user status drupal 8
I have tried the following code but nothing seems to be working. I have removed the other field just to make focus on status field.

```
$user = \Drupal\user\Entity\User::create();
$user->set("status", 0);
$user->activate();
// Save user
$saved = $user->save();

```

Another code is

```
$user = \Drupal\user\Entity\User::create();
$user->status= 0;
$user->activate();
// Save user
$saved = $user->save();

```

But none of the above code is working. Please guide how to set the user status. Here is my full code

```
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $user = \Drupal\user\Entity\User::create();

    $user_data = db_query("SELECT * from eberhard_users ORDER BY uid ASC limit 0,1");

    foreach ($user_data as $delta => $details) {
        // The Basics
        $password = user_password(8);
        $user->uid = $details->uid;
        $user->created = $details->created;
        $user->changed = $details->login;
        $user->access = $details->access;

        $user->setUsername($details->name);
        $user->setPassword($password);
        $user->setEmail($details->mail);
        $user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object

        // Optional settings  <-- Thanks to http://drupal8.ovh/ for these suggestions!
        $user->set("init", $details->mail);
        $user->set("langcode", $lang);
        $user->set("preferred_langcode", $lang);
        $user->set("preferred_admin_langcode", $lang);
        $user->set("timezone", 'Pacific/Wallis');
        $user->set("status", FALSE);
        $user->activate();
        // Save user
        $saved = $user->save();die;
    }

```

# Answer
> 3 votes
There are a number of issues with your code. First, you are setting status as false, then activating. You don't need to set the status as false first. Just create the user, and set activate() on it.

Next, you are trying to set properties directly, like the created. You cannot do that in Drupal 8. You need to use the methods on the user object. So you would use set(). Other properties have methods for setting the property, such as setEmail(). You can view all the methods on the User object here: https://api.drupal.org/api/drupal/core%21modules%21user%21src%21Entity%21User.php/class/User/8.3.x

One other issue is that you are setting the UID. I don't believe you can do this, as the user ID is determined by the auto-increment value in the database, and trying to manually set it, if you can get it to work, will only cause you issues.

---
Tags: users
---


# Question
Title: How to get media entity field value in twig?
Sometimes it is necessary to get the actual value of a field (not the formatted/rendered one), e.g. to check a boolean for `true` or `false`.

If I want to get a field value of a *node* or *paragraph* inside twig templates (*node.html.twig* / *paragraph.html.twig*) I can use `node.field_my_boolean.value` respectively `paragraph.field_my_boolean.value`.

How do I accomplish this in a *media* twig template? I've already tried `media.field_my_boolean.value` but it does not work.

# Answer
> 4 votes
Right now, the Media module does not pass its object in the variables like Paragraphs and Node does. This is why `media.field_my_boolean.value` does nothing.

You can correct this in your theme by implementing `theme_preprocess_media`, which adds the media object to the variables:

```
/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&$variables) {
  $variables['media'] = $variables['elements']['#media'];
}

```

You can then access `media.` in your twig template and any connected fields on it just like Paragraph or Node.

# Answer
> 1 votes
You can with `{{ content.field_my_boolean }}` and if you want the raw value without the HTML markup use `content.field_my_boolean.0`

> Both output the rendered value and not the actuall true/false. I can not use this because it is translated (e.g. "wahr"/"falsch" in German).

Then use the `|t` function and do this

```
{% if content.field_my_boolean.0 == 'Wahr'|t %}
    // do something
{% elseif content.field_my_boolean.0 == 'Falsch'|t %}
    // do something
{% endif %}

```

---
Tags: theming, 8
---


# Question
Title: Get a contextual filter for a View in Drupal 8
I'm converting a module from D7 to D8 for a client. Some of the code is working programmatically with views - something I haven't done that much in D7, since I just write my own queries.

In the code is this line:

```
$contextual_filter = method_exists($view, 'get_items') ? $view->get_items('argument', $display->id) : 0;

```

I need to convert this to D8, but I'm not sure entirely what I'm working with here.

What I do know:

* In D8, `$view` is an object of type `Drupal\views\ViewExecutable`
* In D8, there is no `get_items()` method, nor a `getItems()` method on ViewExecutable
* ViewExecutable has a property, `args`, and also a property `argument`

My questions:

1. How can I get the items from ViewExecutable
2. How can I get the contextual filter from ViewExecutable
3. Do I even need to do #1 to get #2?

Further down the code, I can see that $contextual filter is used as follows:

```
'contextual_filter' => !empty($contextual_filter) ? 1 : 0

```

So it would appear I'm just trying to get a boolean indicating whether or not a contextual filter exists.

Can anyone who has worked more with D7 Views more than I give me some insight as to what is happening with this code, and ideally how I can update it to D8? (Though insight as to what is happening in D7 may be enough for me to figure it out in D8).

# Answer
In D8 the settings of a view are stored in a configuration entity. You can load the entity with View::load() or get it from the view executable directly and then load a display and check the contextual filters (stored in the key `arguments` of the display options):

```
$storage = $view->storage;
$display = &$storage->getDisplay('default');
$arguments = $display['display_options']['arguments'];

'contextual_filter' => !empty($arguments) ? 1 : 0

```
> 3 votes

---
Tags: views, 8
---


# Question
Title: Change "Add new node" and "Add existing node" button labels in inline entity reference forms
I am using inline entity forms to allow users to add or reference existing location content to event content from the front end and am very pleased with how this works. I would really like for the buttons to be labeled slightly different here with the labels reading, for example, "Add new location" rather than "Add new node" which is currently a bit confusing for users. Is this possible, even if this was a theme hook that only changed the label in the front end? The solutions for Drupal 7 don't seem to work in 8.

# Answer
> 1 votes
Turns out this is really easy. Under "Manage form display" in your content type, make sure that the widget is set as Inline entity form (simple or complex) and check "Override labels" then define your node type label.

---
Tags: 8
---


# Question
Title: Is it possible to organize template files?
As I've gotten more familiar with Drupal, I've been utilizing template files more and more. However, the naming conventions for template files make them difficult to organize. Is it possible to organize template files into different directories within the primary templates directory? I'm using Drupal 7.

If it isn't possible, are there alternative methods to organize template files?

Thanks!

# Answer
> 2 votes
> Is it possible to organize template files into different directories within the primary templates directory?

Yes, absolutely. Drupal will recursively search the root and every subfolder in your theme for .tpl.php files.

Stick them in whatever structure suits you, Drupal will find them.

---
Tags: 7, theming, installation, configuration
---


title: Dynamic drupal webform

text:
# Question
Title: Dynamic drupal webform
I need need next functionality from webform. For example: At start I have select field, with number values from 1 to 9.

If 2 or more are selected, then list fields for Person 1, Person 2, etc.

Participant 1 First Name Last Name Email address

Participant 2 First Name Last Name Email address

Participant 3 First Name Last Name Email address

Do I need custom module for functionality like this one, or it is possible with existing modules?

# Answer
You could take a look at the "webform add more" module, it's not exactly what you're looking for, but very similar...
> 0 votes

---
Tags: webforms
---


title: How to get taxonomy by URL alias?

text:
# Question
Title: How to get taxonomy by URL alias?
I have a *grade* vocabulary with a *6. Class* taxonomy term. The taxonomy page have an URL like www.example.com/foo/6-class/bar and I can't find the taxonomy with the following code.

```
$grade = arg(2);
$term = taxonomy_get_term_by_name($grade)

```

It works when I use a string (e.g. *6. Class*), but not with `arg(2)`. How can I get the correct taxonomy with this URL alias? Problem might be, that it is a exposed filter and no contextual filter. But I can not change this fact.

Neither I can get the source path with the following code.

```
drupal_lookup_path('source', $_GET['q']);
drupal_lookup_path('alias', current_path());

```

# Answer
I know this is a pretty old question but seems unanswered yet. This Drupal 7 snippet will help you to load a taxonomy term but you need to know the name of the vocabulary it belongs to, lets say it is 'position'. Ex. www.example.com/foo/6-class/bar

```
$term_path=drupal_get_normal_path('position/'.arg(1));
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

```

If you **know** your url is an alias to your taxonomy term, just use

```
$term_path=drupal_get_normal_path(current_path());
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

```

The drupal\_lookup\_path with source and uri approach did not work for you because probably that path is not an alias, or at least not for your taxonomy.

Hope this helps someone.
> 3 votes

# Answer
I was working in Drupal 8 and for whatever reason I couldn't get any of the above solutions to work for me. Below is what I ended up using to get the url with the term id. There must better ways of doing this and I'm sure that not all of these options are required, but I hope this helps someone.

```
$term_url = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $term->tid->value], ['absolute' => TRUE])->toString()

```
> 2 votes

# Answer
`arg(2)` will return the term id of the taxonomy term not the name because the path will be `taxonomy/term/[tid]`.

You have added an alias for the term pages which the `arg()` function doesn't read as it reads the original path not the aliased path.

The function that you are using with take the taxonomy name as the argument. But what you are passing is the term id. So if you use `taxonomy_term_load(arg(2))` then you will get details about the term in the returned term object.

Check out the documentation here: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy\_term\_load/7

Hope this helps. :)
> 1 votes

# Answer
The most easy way to get taxonomy term from url is

```
$term = menu_get_object('taxonomy_term', 2);

```
> 1 votes

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


# Question
Title: Cannot use object of type EntityDrupalWrapper
I keep getting this error:

Fatal error: Cannot use object of type EntityDrupalWrapper as array in /sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code on line 29

when I use the below PHP code in rule

```
$t_exists = 0;
$etid = 0;
$vid =10;
$vname = 'emails';

$wrapper = entity_metadata_wrapper('node', $node);
$email_term = $wrapper->field_primary_email->value();

function customs_create_taxonomy_term($email_term, $vid) {
  $term = new stdClass();
  $term->name = $email_term;
  $term->vid = $vid;
  taxonomy_term_save($term);
  return $term->tid;
 }

function et_exist($vname, $email_term) {
$tid = NULL;
$vocabulary = taxonomy_vocabulary_machine_name_load($vname);
$terms = taxonomy_get_tree($vocabulary->vid);
    foreach ($terms as $term) {
      if ($term->name == $email_term) {
        $tid = $term->tid;
      }
    }
return $tid;
}

if ($wrapper->field_email_term_reference[0]->value()) {
foreach ($wrapper->field_email_term_reference->getIterator() as $index => $taxWrapper) {
  $taxWrapper->value()->name;
  $taxWrapper->value()->tid;
  $taxWrapper->value()->vid;
  $taxWrapper->value()->vocabulary_machine_name;
if ($taxWrapper->value()->name == $email_term) {
$t_exists=1;
};
}

if (!$t_exists) {
$etid = et_exist($vname, $email_term);
If ($etid) {
$wrapper->field_email_term_reference[] = $etid;
} else {
$etid = customs_create_taxonomy_term($email_term, $vid);
$wrapper->field_email_term_reference[] = $etid;
}
$wrapper->save();
};
}

```

The line that seems to be causing the problem is:

```
if ($wrapper->field_email_term_reference[0]->value()) {

```

Please advice.

# Answer
> 1 votes
The code is trying to access an `EntityDrupalWrapper` as if it was an `EntityValueWrapper`, which might suggest the field simply doesn't have a value for the entity that's throwing the error.

Since you're explicitly getting the first field item anyway, changing the `if` statement to something like this would probably fix it:

```
if ($wrapper->field_email_term_reference->value()) {

```

---
Tags: 7, rules
---


# Question
Title: node_save() not working with LANGUAGE_NONE
My question is exactly similar to the one posted here https://www.drupal.org/node/2324047.

The answer posted here is not complete and I'm looking for a solution. I'm using the below code to save a node.

```
function api_add_getabstract($node_values, $api_endpoint) {
  //initialise node object
  $ex_node = new stdClass();
  $ex_node->type = 'getabstract';
  $ex_node->language = 'en';
  node_object_prepare($ex_node);
  dpm($node_values,'node values');

  //add field values
  $ex_node->title = $node_values['bookinfo']['title'];
  $ex_node->body['en'][0]['value'] = $node_values['recommendation'];
  $ex_node->body['en'][0]['format'] = 'full_html';
  $ex_node->field_authors['en'][0]['value'] = $node_values['bookinfo']['authors'];
  $ex_node->field_sub_title['en'][0]['value'] = $node_values['bookinfo']['subtitle'];
  $ex_node->field_publisher['en'][0]['value'] = $node_values['bookinfo']['publisher'];
  $ex_node->field_ex_cover_image['en'][0]['value'] = $node_values['bookinfo']['bookcoverOriginal'];
  $ex_node->field_ex_deep_link['en'][0]['value'] = $node_values['publicURL'];
  $ex_node->field_api_info['en'][0]['value'] = $api_endpoint;
  node_save($ex_node);
}

```

I tried by changing the value 'en' to 'und' and LANGUAGE\_NONE, but none seem to save the node completely. Using 'en' at least creates the node with only Title field, but for the other 2 values, node is not even getting created.

# Answer
> 1 votes
I presume by your code example you use D7. And I presume by the error you get you don't use Entity Translation.

In D7 the built-in approach to offer multilingual content is called *'content translation'*. Meaning you translate node by node. You hit the language switch and get redirected to another node.

Whereas in D8 the Entity Translation module now became part of core and so it replaced the *'content translation'* approach by the *'entity translation'* approach. Meaning you translate field by field. By providing a language key for every field. You hit the language switch and the same node reloads, but this time rendering the field values in a different language.

To come back to your question, as you don't use Entity Translation, you only have to set a language for the node (and possibly map it to their matching nodes in other languages). You MUST NOT specify a language for each field.

Alternatively, start using Entity Translation and configure the fields you want to be multilingual. Then, if I remember it right, your code will work.

Comparing both approaches, each has its pros and cons. And I already built D8 sites where we had to somehow rebuild a custom *'content translation'* workflow (node by node translation), to get back the flexibility this has (especially in connection with Paragraphs – but that's a different story to be told).

---
Tags: nodes
---


# Question
Title: Really confusing composer error output relating to working composer.json/.lock files
Warning: this may come across a little ranty! Up until version 8.3.0, I thought I had solved all my drupal + composer related issues. With the following in composer.json:

```
"require": {
    "drupal/core": "~8.3"
}

```

I ran composer update. I got v8.3.0-rc2. After some playing around, I changed the above to:

```
"require": {
    "drupal/core": ">8.0"
},

```

which updates to the latest *stable* 8.x release. What is going on! Why would the first example not work?

Additionally, downloading Drupal in .zip form, the line reads:

```
"replace": {
    "drupal/core": "~8.3"
},

```

Why, when nearly every guide recommends putting this line in the 'require' array if you intend on updating via composer?

Furthermore, the widely recommended Drupal Composer Project has the following - perhaps crucial - line:

```
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

```

I realised early on that without this line, many of my update attempts would fail in some way. Why would this line not be absorbed into the main Drupal distribution?

So many questions, and yet most Drupal + Composer pages across the internet forward us to the general composer website. It seems clear that Drupal is not fully compatible the 'general' composer methodology

# Answer
> 1 votes
Someone else recently reported not being able to update from RC2:

Updating core with Composer doesn't work

There are two different things, drupal/drupal and drupal/core. You can't mix the two, that's why when you download drupal from drupal.org by hand, you have drupal/drupal and it contains the replace line, as it says that it replaces that.

As suggested there, I'd recommend to use the drupal-project template, I've upgraded many drupal installations to 8.3 with that without a problem.

Note that that has quite a different file structure, specifically it has a web folder that contains the public files.

---
Tags: 8, updating, composer
---


# Question
Title: 8.3: How to create a node via REST with html?
I have a Drupal 8.3 setup and working and want to add content via REST. I can create nodes fine, but only in plain text. I can't figure out and can't find any documentation for how to submit content as html so it could have formatting.

I found a comment that had examples for submitting comments with basic html with the body specified like:

```
{"content_body": {"format": "basic_html", "value": "<b>Hi</b>"}

```

But when I tried to do something similar with the 'body' tag for posting to /entity/node, it returns a 422 response with this message:

*Unprocessable Entity: validation failed.\nbody: Body: this field cannot hold more than 1 values*

For reference, this is basically the hal+json body of the post (minus the taxonomy stuff not relevant to this question):

```
{
  "body": {
    "format": "basic_html",
    "value": "<b>This is the body of the test</b>"
  },
  "title": {"value": "Test One"},
  "type": {"target_id": "Article"}
}

```

If I drop the 'format' tag from the body dictionary, everything works fine... except the tags are displayed and not interpreted as html.

Thanks in advance.

# Answer
> 1 votes
Drupal is probably expecting an array of field data, even if the field itself only accepts a single value.

When the JSON is decoded, this is still an array:

```
{
  "format": "basic_html",
  "value": "<b>This is the body of the test</b>"
},

```

But with 2 items, when only one is expected.

You should be able to fix by providing an array with just the one item:

```
"body": [{
  "format": "basic_html",
  "value": "<b>This is the body of the test</b>"
}],

```

---
Tags: nodes, 8
---


title: bandcamp embed field

text:
# Question
Title: bandcamp embed field
I'm running D8. I need to have a field to embed a bandcamp player in. I'm using media module but there doesn't seem to be a way to embed platforms not officially supported by fx media video, media audio etc. I'm not a php-coder, just html / css.

Any ideas?

# Answer
If bandcamp offers a method of embedding their players into other websites, you can open a request in the issue queue for the URL To Video Filter module (which I'm the developer of), with a link to their embed method, and I'll try to integrate it for you.
> 2 votes

---
Tags: entities, media
---


# Question
Title: What are Text Filters and Input Formats?
In views, when I add a field of type body, there are some options given: text\_default, text\_plain, text\_trimmed.

How do these options filter the contents of the field and where can they be found in the code??

# Answer
> 0 votes
These are called 'text filters', and a text filter is made up of 'input formats'. Input formats are defined in hook\_filter\_info().

You can read more about text filters here: https://www.drupal.org/node/213156

---
Tags: 7, views, entities, input-formats
---


# Question
Title: Error when trying to load taxonomy term name from tid
I am trying to replace a view name with the name of a taxonomy term that is determined from a url argument.

When I explicitly set `$tid`, the following works flawlessly:

```
function hook_views_pre_render(ViewExecutable $view) {
  $tid = 2;
  $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
  $name = $term->label();
  $view->setTitle($name);
}

```

However, if `$tid` is determined from my argument, as in:

```
function hook_views_pre_render(ViewExecutable $view) {
  $tid = $view->args[0];
  // or alternatively $tid = intval($view->args[0]);
  $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
  $name = $term->label();
  $view->setTitle($name);
}

```

...then I get the following error:

```
The website encountered an unexpected error. Please try again later.
Error: Call to a member function label() on null in hook_views_pre_render()

```

...on the line containing `$name = $term->label()`.

I am at a loss as to why this is happening. When I inspect `kint($term)` in either situation, all of the data for the loaded term appears to be available. I've also verified that:

```
if   $tid1 = 2;
and  $tid2 = intval($view->args[0]);
then $tid1 === $tid2

```

# Answer
> 0 votes
Because there is the case when no argument is passed and $tid is null. So better keep a check you have data in variable $tid and further perform the task. Even the view name condition is not mentioned so it may apply to all views.

```
  function hook_views_pre_render(ViewExecutable $view) {
      $tid = $view->args[0];
      // or alternatively $tid = intval($view->args[0]);
    if(isset($tid) && !empty($tid)){
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->label();
      $view->setTitle($name);
    }
    }

```

---
Tags: views, 8, taxonomy-terms, hooks
---


title: Using only alias URL for a page

text:
# Question
Title: Using only alias URL for a page
If I've got a page that originally has a node (ie node/20) for the URL and then if I've assigned its own custom URL (ie website.com/landingpage) I'm finding that I can still access the page by using its node number. Ideally I'd like to have it so a user can only access the page via the custom URL and never the node so is there a way I can configure a node so it cant be used in the URL to reach the page?

# Answer
> 1 votes
You can use the Redirect module for this: https://www.drupal.org/project/redirect

---
Tags: nodes, uri
---


# Question
Title: Remove the special characters (like %20) from URL
Is it possible to replace the URL encoded characters for space,?,etc. with the exact character ? Because one of the content in my site takes the following URL and it doesn't looks so nice!

> https://expatchoice.asia/eat-drink/restaurants-casual/ana-intercontinental-tokyo%E3%80%80ana%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%82%B3%E3%83%B3%E3%83%81%E3%83%8D%E3%83%B3%E3%82%BF%E3%83%AB%E3%83%9B%E3%83%86%E3%83%AB%E6%9D%B1%E4%BA%AC

# Answer
> 2 votes
Please take a look at transliteration module. Together with pathauto you could get better urls. But i don't know how well this works with chinese characters.

---
Tags: uri
---


# Question
Title: Using a computed field: How to extract a field value from a referenced node into field collection. (Multiple value)
I have written this code inside a computed field, which has given me as result, the referenced entity numbers how are saved in the field as an array.

I would like to know how to extract from the entity number a specific field, such as the title.

```
foreach ($entity->field_campos as $field) {
}
foreach ($field as $index => $valores) {
$terminos[] = $valores['value'];
}
$item2 = field_collection_item_load_multiple($terminos, $reset = FALSE);
foreach ($item2 as $indice => $values) {
$entity_field[]['value'] = $values->field_nombre_2['und'][0]['target_id'];
}

// Display code (PHP).
$display_output = $entity_field_item['value'];

```

I am using Drupal 7.

# Answer
You can do something like this:

```
$referenced_titles = array();

foreach ($item2 as $indice => $values) {

  // use node_load($nid) to load the node.
  $referenced_node = node_load($values->field_nombre_2['und'][0]['target_id']);
  $referenced_titles[] = $referenced_node->title;

}

```
> 2 votes

---
Tags: entities
---


# Question
Title: What's wrong in my rule for sending e-mails using VBO?
I am trying to send a mail to a set of users when a node is created, so I made a users view including VBO field and a rule for it. You can see the settings below. It's about D7.

But when the rule gets in action, no mails sent and the following messages appear in admin/reports/dblog:

> Unable to evaluate loop.
>
> Unable to get variable entitylistem, it is not defined.
>
> Unable to evaluate action views\_bulk\_operations\_action\_load\_list.
>
> Unable to get a data value. Error: Invalid data value given. Be sure it matches the required data type and format. Value at user():

What is wrong?

# Answer
> 2 votes
Obviously "something" is wrong in what you're trying to get to work. I suggest you enable the typical the Rules debugging (to find more details about what's happening and causing your error), as detailed in "How can I display the value of a variable inside a condition?". If needed, add a copy of the Rules execution log as an update to your question.

Maybe also checkout the tutorial "How to process the results of a VBO enabled view via Rules?".

`***Plan B***`

A possible alternative that should work also, is to get the Views Rules module involved in the puzzle you're trying to solve (instead of using VBO). Some details about this module (from its project page):

> Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

1. Create a view (using Views) so that you have 1 Views result (row) for each user to be eMailed, whereas that view has fields (columns) for each of the fields that you want to use to create your eMail. So your existing view could already be pretty close (if you just remove the VBO field). Important: use a Views display type of "Rules".
2. Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop".
3. For each iteration step in your Rules loop, perform a Rules Action to ... euh ... right ... Send an eMail. At that point you'll have all data from each column of your Views results available as so called Rules Parameters. So at that point it's a piece of cake to create an appropriate eMail.
4. The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). In your case: your existing Rules Event should also be fine. Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

***Easy, no?***

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

# Answer
> 2 votes
I would suggest you to simply write your custom rules action like this

```
function mymodule_rules_action_info() {
 return array(
  '_send_new_content_mail' => array(
    'label' => t('Send Mail to users for new content'),
    'parameter' => array(
    'node' => array('type' => 'node', 'label' => t('Current Node')),
    ),
    'group' => t('custom'),
  ),
 );
}

```

Define your callback:

```
function _send_new_content_mail($node) {
  global $base_url;
  $query = db_select('users', 'u');
  $query->join('users_roles', 'r', 'u.uid = r.uid');
  $query->leftJoin('field_data_field_first_name', 'n', 'u.uid = n.entity_id');
  $query->leftJoin('field_data_field_last_name', 'l', 'u.uid = l.entity_id');
  $query->fields('u', array('mail', 'name'));
  $query->fields('n', array('field_first_name_value'));
  $query->fields('l', array('field_last_name_value'));
  $query->condition('r.rid', ROLE_ID, '=');
  $result = $query->execute()->fetchAll();

  foreach ($result as $val) {
    $alias = drupal_get_path_alias('node/' . $node->nid);
    $data = 'Hi ' . $val->field_first_name_value . ' ' . $val->field_last_name_value . ', new content has been published of your interest. ';
    $data .= 'Click ' . l('here', $base_url . '/' . $alias) . ' to see the content.';
    $key = 'new_content_mail';
    $subject = 'New content published';
    $to = $val->mail;
    _get_mail_content($data, $to, $key, $subject);
  }
}

```

Now define your mail content function:

```
function _get_mail_content($data, $to, $key, $subject) {
  $mail_content = _mail_content($data, $key);
  $params = array(
   'body' => $mail_content,
   'subject' => $subject,
  );
  $mail = drupal_mail('module_name', $key, $to, language_default(), $params, 'no-reply@info.com', TRUE);
  if ($mail['result']) {
   return TRUE;
  }
  else {
    $error_msg = 'Failed to send the email!';
    watchdog('new-content-email', $error_msg, array(), WATCHDOG_ALERT);
    return FALSE;
  }
}

```

Define \_mail\_content:

```
 function _mail_content($data , $key) {
   switch ($key) {
    case 'new_content_mail':
      return theme('mymodule_new_content_mail', array('data' => $data));
    break;
   }
 }

```

Now define the template file in your hook\_theme() and print $data inside it.

```
function mymodule_theme() {
  return array(
    'mymodule_new_content_mail' => array(
      'template' => 'mymodule-new-content-mail',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'variables' => array('data' => NULL),
    ),
  );
}

```

Now add new rule, select the event node-after publishing new content, add the node type in the condition for which you want to send mail and select \_send\_new\_content\_mail in action which will be present under 'custom'.

# Answer
> 1 votes
It is very well possible that your "issue" (the errors produced in your first Rules Action) is because of the Rules Event you're using (= "*after saving new content*"), which might simply not be the right event. Don't believe me ... yet ... read on to get surprised ...

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that `After saving something` actually happens ... `Before saving something` (which is not a bug, simply how the Rules module works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).

# Answer
> 0 votes
There seems to be a bug in the latest version of VBO.

Check out https://groups.drupal.org/node/516374#comment-1153591 for a fix

---
Tags: rules, emails, views
---


# Question
Title: Manually importing webforms and data with mysql... where is it now?
I wanted to experiment and see if I could just import all the webforms, webform data, submissions, configurations, etc. from one Drupal 7 site to a new one. The import seems to have gone well but I can't see anything, even after clearing the caches. I even performed a MySQL query on the new site to see if the tables were actually populated.

```
    mysqldump -u root -p database_name webform webform_component
webform_conditional webform_conditional_actions webform_conditional_rules
webform_emails webform_last_download webform_report webform_roles
webform_submissions webform_submitted_data webform_validation_rule
webform_validation_rule_components content_type_webform> webforms.sql

```

Then I logged into mysql, chose the correct database and imported it: `source webforms.sql`

Did I miss some other crucial table or something else? I have had a lot of success with migrating users and other info over this way even though I'm not sure it's wise and haven't found much in the way of doing data migration for Drupal without modules.

# Answer
> 2 votes
Webforms are nodes, so you'll also need to bring the node (and potentially field and other depending on your site's configuration) data across.

Make sure the node ids for the webforms are the same as they were in the original site, or you'll have to do some manual work to get the data linked back up again.

This is why it's arguably better to migrate content, rather than do a raw data export/import, as it gives you the opportunity to massage/prepare data as required for the new system.

---
Tags: 7, webforms, migrations
---


# Question
Title: Disable Radio button if default value is "inactive"
I need to **disable** other radio button(s) when **\[#default\_value\] =\> Inactive** as in below code it is? I tried with different ways but unsuccessful. Kindly let me know how to do that?

**PHP CODE**

```
foreach($form['field_complaint_status'] as $key=>$val)
{
    echo '<pre>'; print_r($val['field_complaint_status']); exit;
}

```

**Output**

```
Array
(
    [#type] => container
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => field-type-list-text
                    [1] => field-name-field-complaint-status
                    [2] => field-widget-options-buttons
                )

        )

    [#weight] => 13
    [#tree] => 1
    [#language] => und
    [und] => Array
        (
            [#entity] => stdClass Object
                (
                    [vid] => 544
                    [uid] => 754
                    [title] => Complaint/Feedback
                    [log] =>
                    [status] => 1
                    [comment] => 1
                    [promote] => 1
                    [sticky] => 0
                    [nid] => 544
                    [type] => complaint_or_feedback
                    [language] => en
                    [created] => 1492408487
                    [changed] => 1492587955
                    [tnid] => 0
                    [translate] => 0
                    [revision_timestamp] => 1492587955
                    [revision_uid] => 754
                    [field_type] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [value] => Complaint
                                        )

                                )

                        )

                    [field_complaint_status] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [value] => Inactive
                                        )

                                )

                        )
                    [cid] => 0
                    [last_comment_timestamp] => 1492408487
                    [last_comment_name] =>
                    [last_comment_uid] => 754
                    [comment_count] => 0
                    [menu_node_links] => Array
                        (
                        )
                    [picture] => 0
                )

            [#entity_type] => node
            [#bundle] => complaint_or_feedback
            [#field_name] => field_complaint_status
            [#language] => und
            [#field_parents] => Array
                (
                    [0] => field_complaint_status
                    [1] => 0
                )

            [#columns] => Array
                (
                    [0] => value
                )

            [#title] =>
            [#description] =>
            [#required] => 1
            [#delta] => 0
            [#type] => radios
            [#default_value] => Inactive
            [#options] => Array
                (
                    [Active] => active
                    [Inactive] => inactive
                )

            [#value_key] => value
            [#element_validate] => Array
                (
                    [0] => options_field_widget_validate
                )

            [#properties] => Array
                (
                    [filter_xss] => 1
                    [strip_tags] =>
                    [strip_tags_and_unescape] =>
                    [empty_option] =>
                    [optgroups] =>
                )

            [#after_build] => Array
                (
                    [0] => field_form_element_after_build
                )

        )

    [#access] => 1
)

```

# Answer
I have done with JS, See code below

```
jQuery(".inactive input").each(function(index, element) {
    jQuery(this).attr("disabled",true);
});

```
> 0 votes

# Answer
You can use the #states property to achieve that. The #states property can be applied to all Form API elements.

```
  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school' => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate' => t('Graduate'),
    ),
    '#title' => t('What type of student are you?'),
  );
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

```

References : states

form\_example\_states\_form
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How to create a custom content type with a quiz field?
I'm pretty much new to Drupal 8, is there a way of creating a custom content type with a quiz field?

# Answer
> 0 votes
You can use the Field Quiz module. It already has an alpha version for Drupal 8.

According to the module description,

> This module provides a simple field that can be used as a simple quiz or multiple choice questions. It provides a field with a textfield and a checkbox / radio selection combined. If added to any entity (node/content type, user, taxonomy term, ...) the editor of the entity can enter multiple answers in the textfields and determine which answers are correct.
>
> This module is for everybody who does not want to use the whole complex system of the quiz module, but just a simple field for multiple choice questions.

---
Tags: views, 8, nodes
---


# Question
Title: default value when adding new item of date field
i'm using drupal 7 and in my content type there is a date field has start and end value with unlimited values, i set the default value to "Now".
but the problem is when adding new item of this field there is no default value in it.

is there a way to set a default value for new items?
thanks a lot.

# Answer
> 0 votes
Try something like this:

```
//this hook or general hook_field_widget_form_alter
function hook_field_widget_date_popup_form_alter(&$element, $form_state, &$context){

  //only when field is specific name and during node creation form
  if ($element['#field_name'] == 'field_date' && !isset($element['#entity']->nid)) {

    //if default value is not set, only for second and later elements, when first item value is set
    if (!is_array($element['#default_value']) && $element['#delta'] > 0 && isset($form_state['values']['field_date']['und'][$element['#delta']-1]['value'])) {

      //set value
      $element['#default_value'] = array(
        //advance by 24 hours
        'value' => $form_state['values']['field_date']['und'][$element['#delta']-1]['value'] + 24 * 3600,
        //same timezone
        'timezone' => $form_state['values']['field_date']['und'][$element['#delta']-1]['timezone'],
        'timezone_db' => 'UTC',
        'date_type' => 'datestamp',
      );

      //if second value (date to) is set (by comparing value and value2)
      if ($form_state['values']['field_date']['und'][$element['#delta']-1]['value2'] != $form_state['values']['field_date']['und'][$element['#delta']-1]['value'])
        //set and advance second value by 24 hours also
        $element['#default_value']['value2'] = $form_state['values']['field_date']['und'][$element['#delta']-1]['value2'] + 24 * 3600;

      //#date_items needs to be same as #default_value
      $element['#date_items'] = $element['#default_value'];
    }
  }
}

```

---
Tags: 7, entities
---


# Question
Title: Move the location of "Notify user of new account" from bottom to custom section of admin/people screen?
Is it possible in **Drupal 7** to move the location of "Notify user of new account" checkbox from the bottom of the page to another location on the admin user screen? I have a custom module with hook\_form\_user\_alter. I have no problem hiding it from appearing, but I didn't know if I could move it to another location on the form and how would I go about doing that if it can be done.

# Answer
If I recall correctly, it's $form\['notify'\]. So you should be able to do this:

```
$form['notify']['#weight'] = -999;

```
> 0 votes

---
Tags: users, hooks
---


# Question
Title: How can I programmatically insert content via a script or import instead of through the UI?
I have a custom content type and I now need to create thousands of entries using that type. It would take a very, very long time to go through the interface and add these one by one. I'm hoping there is a plugin, module, or some kind of API so that I can create all of these entries in an excel and simply import them into the database. Is this possible?

I have not been able to get Drush working so that isn't really an option for me.

# Answer
The most direct answer to your question is Migrate Source XSL module for the D8 Migrate API.

Or hell, dont have Windows/Excel installed do the same with Google Sheets Migrate Plus plugin.

I'm not sure if there is a UI for Migrate yet in D8. But this would be the most flexible solution. If needed you could use the drupal api itself to code simple insertion from a php script to create Nodes from an excel script; but the above migrate plugins should be much for flexible to debug in the long run -- but may require Drush support currently.

## Edit

Ask previously, how to create a Node in D8: Programmatically create nodes
> 1 votes

---
Tags: 8, database, plugins
---


title: Add user edit form in a block D8

text:
# Question
Title: Add user edit form in a block D8
I'm trying to add the user edit form in a block. I created a custom module

```
use Drupal\Core\Block\BlockBase;
use Drupal\user\ProfileForm;

class EditUserBlock extends BlockBase{

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm(ProfileForm::class, \Drupal::currentUser());

    return $form;
  }
}

```

but it doesn't render the form.

Sorry but I'm pretty new to D8.

# Answer
> 3 votes
This is an entity form and you need EntityFormBuilder::getForm() to build this form. After you have injected the entity form builder and the necessary user storage and current user services in the block plugin:

```
<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Profile Block.
 *
 * @Block(
 *  id = "profile_block",
 *  admin_label = @Translation("Profile Block"),
 * )
 */
class ProfileBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

  /**
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $userStorage;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFormBuilderInterface $entity_form_builder, AccountInterface $current_user, EntityStorageInterface $user_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityFormBuilder = $entity_form_builder;
    $this->currentUser = $current_user;
    $this->userStorage = $user_storage;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.form_builder'),
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

```

you can build the profile form for the current user with two lines of code:

```
  public function build() {
    $user = $this->userStorage->load($this->currentUser->id());
    return $this->entityFormBuilder->getForm($user);
  }

}

```

---
Tags: 8, forms, users
---


title: Content types and modules

text:
# Question
Title: Content types and modules
I am new to Drupal and unsure how to add a module to a custom content type. I am currently trying to add the Field Quiz module to a custom content type on Drupal 8. Is it possible for someone to explain how I can do this?

# Answer
> 1 votes
In the context of the question, Field Quiz simply provides a new field type/widget, so you have to edit the content type and add a new field using that type. It will be available after enabling the module.

---
Tags: nodes, entities
---


title: Delete workflows / individual states

text:
# Question
Title: Delete workflows / individual states
Strangly I seem not to be able to delete an existing workflow as a whole, nor a state within a workflow. The admin user has all the necessary permission. No content type is assigned with the workflow. What do I not see?

# Answer
In Drupal 8 (at least), there is a "Clean up" tab in the main configuration screen of the module (/admin/config/workflow/workflow), where you can delete inactive states.

In my case, I suddenly stopped seeing the "Actions" buttons, so the only thing I could do was activate/disactivate the states.

That may solve someone's problem...It solved mine
> 1 votes

# Answer
I was just having the same issue. But I have just noticed that deleting a state from a workflow is not done in just one step.

First, you have to disable the state.

Second, on the main page of the workflow module, click on "Clean up workflow" and you will see that you can delete the inactive workflows there.
> 1 votes

# Answer
If you want to delete a workflow at all it must not be used in any node. So delete all fields pointing to this workflow first.

But I confirm: I cannot delete single states inside of a workflow at all.
> 0 votes

---
Tags: 7, workflows
---


# Question
Title: How to control field_group quantity - control field group quantity
I Cant speak english very well.So sorry if my post is not very good.

When we add a field like text input or file field , we can control number of quantity of thats field.for example if number of a text field set "unlimite",user can click on a button for add another field.

So I want to give possibility to user that after click on "ADD BUTTON" a new field group add to form fields.

If show a table bottom of form (involve added field groups) , this is very good.

example :

```
textfield1     textfield2    textfield3

```

> add button

(**after click this button or submit above fields , another 3 textfields show to me and submitted textfields show bellow on a table**)

Is any module for this work? thank you for your response beforehand.

# Answer
> 0 votes
Thank For responses. I used Filed Group multiple Module for this problem. Filed Group multiple

> This module extends the Field group module by displays and widgets which group multiple fields by there items.

# Answer
> 1 votes
Field group is used for purely cosmetic purposes. If you want to enable the functionality you describe, use Field Collection.

---
Tags: entities
---


title: How do I invalidate a page from cache?

text:
# Question
Title: How do I invalidate a page from cache?
In Drupal 7 we could clear a cached URL with the following.

```
$url = url('<front>',  array('absolute' => TRUE));
cache_clear_all($url, 'cache_page');

```

What's the equivalent in Drupal 8?

# Answer
> 4 votes
There is no equivalent in D8. What would be the closest to this is to assign a custom cache tag to the page and then invalidate it. See https://www.drupal.org/docs/8/api/cache-api/cache-tags.

But normally you don't need to invalidate cache tags in custom code. If you set the correct cache metadata this should happen automatically.

---
Tags: caching
---


# Question
Title: How do I properly remove "Powered By Drupal"?
How do I remove the "Powered By Drupal" string that is displayed on the site footer?

>

Does it involve PHP coding?

# Answer
> 6 votes
Use this technique

go to yoursite/admin/structure/block

you will see the "Powered by Drupal" as a block

Choose - None - it will go away and you can create your own block with your own footer information

# Answer
> 4 votes
Unset the "Powered by" block from the block admin (admin/structure/block). If the theme has hard-coded this, you'll have to remove it from the appropriate template.

# Answer
> 0 votes
It is just like any other block on your website:

1) Hover over it, you will find a small settings icon will appear.

2) click on that and then configure block.

3) it will take you to the configuration page of that block.

4) from here you disable the block by change its region to none.

5) Save your block. Voila!

---
Tags: 7
---


# Question
Title: How to impose a global maximum limit on two webform number fields?
I'm using a webform as an online reservation form. Apart from the name, email and phone number fields, there are two number fields to ask how many adults and how many children will be attending an event.

The thing is we want to restrict the online reservation to 8 participants (adults and children combined) For example : It can be 8 adults or 4 adults and 4 children or 6 adults and 2 children etc..

Is there a way to use some sort of rule to impose this ? thanks

# Answer
Install the Webform Validationmodule which allows you to easily set rules for fields. So in this case you could add a rule that the number can not go above 8.

You can also use hooks to add your own validation rules in code for more complex formulas like the child and adult combination.
> 0 votes

---
Tags: 7, webforms
---


title: How can I field-rewrite a URL?

text:
# Question
Title: How can I field-rewrite a URL?
I need the modified URL to call a view with contextual filter, in Drupal 8. The URL must include the value of a field, that the user's clicking on.

This works.

```
<a href="{{ url('view.testview.page_1', {'arg_0': field_example__value}) }}">Link to Testview</a>

```

How can I overwrite *Link to Testview* with the field value?

`{{field_example__value}}` works as well.

# Answer
I've seen it often that the path is simply built by concatenating strings. But if you want to do it in a D8 way, then use the route from the view.

You can investigate the routes with Drupal Console on the command line or the Devel module in UI, where you'll find the routes in */devel/routes*.

For example this view:

```
ROUTE NAME: view.testview.page_1    PATH: /testview/{arg_0}/{arg_1}

```

When you know the route name and the arguments for the contextual filters you can build the URL:

```
use Drupal\Core\Url;

  $url = Url::fromRoute('view.testview.page_1', [
    'arg_0' => $arg1,
    'arg_1' => $arg2,
  ]);

```

The URL is an object, which you put in a render array, for example in a link element. If needed you can get the path as string with the method `->toString()`, but this should be avoided.

If you want to use the route in a field rewrite you can use the twig function `url()` in a field replacement pattern:

```
<a href="{{ url('view.testview.page_1', {'arg_0': field_example__value}) }}">Link to Testview</a>

```
> 1 votes

---
Tags: views, uri
---