# Question
Title: How do I migrate only the items that previously failed?
I have a migration class that has imported 2000 items correctly, but failed to import 40 of them.

Now I have corrected the import class, but I don't want to do a rollback and a full reimport/migrate.

Is there a possibility to import/migrate only the 40 failed items?

# Answer
> 2 votes
Another possibility is to use the "--needs-update" option as "migrate-import Article --needs-update" .

You might need to status of needs-update field for these 40 records as needs\_update=1.

This option is only needed when your Drupal DB is on a different DB server from your source data. Otherwise, these records get migrated with just migrate-import.

# Answer
> 1 votes
I have found the solution. Via "drush" call the migration with "--update" and the process create the remaining items.

```
$  drush mi --update MigrateMhtLinks
Processed 2040 (40 created, 2000 updated, 0 failed, 0 ignored) in 9.5 sec (1734/min) - done with 'MigrateMhtLinks'

```

# Answer
> 1 votes
In my case, the solution I found consists in 2 queries in the source and the destination dbs:

1) In the migration class, a 1st query in the destination db selects source ids =\> `$ids = array();
$query = db_select('migrate_message_[migration_class_name]', 'm');
$query->fields('m', array('sourceid1'));
$result = $query->execute();
while($record = $result->fetchAssoc()) {
 $ids[] = $record['sourceid1'];
}`

2) Then add a condition in 2nd query, the migration source query: `$query->condition([map_id], $ids, 'IN');`

# Answer
> 0 votes
The reason when "drush mi some\_d6\_migration\_name" runs again, and it migrates nothing new is drush considers this migration has been finished/completed already. There should be 2040 records in table "migrate\_map\_some\_d6\_migration\_name", including those 40 failed items.

If a message such as '2000 items has been migrated, 40 items are not processed' is returned when drush mi runs for the first time, and then when "drush mi some\_d6\_migration\_name" runs again, it should process those 40 'unprocessed' items.

So for those failed items, I think you can delete failed records from this table "migrate\_map\_some\_d6\_migration\_name", with something as

```
DELETE FROM migrate_map_some_d6_migration_name where source_ids_hash in (select source_ids_hash from migrate_message_some_d6_migration_name)

```

or this one if this migration has only one destid.

```
DELETE FROM migrate_map_some_d6_migration_name WHERE destid1 IS NULL

```

Above commands will make those failed items become 'unprocessed' items. Then run "drush cr" to clear cache(this step may be needed or not) and run "drush mi some\_d6\_migration\_name" again. This time it should only migrate previously failed items.

---
Tags: 7, migrations
---


# Question
Title: Show custom view before input entered on exposed form
I have a page that displays a map with results based on an exposed search field, which is a required field.

I would like to display a custom view when the user visits the page and has not yet entered anything into the field - similar to this question but another view rather than a custom result set. At the moment, the map shows all results when the page is first loaded, and I can't figure out how to change that behaviour.

I know that if I set the form to "Input required" I can enter custom text to be shown before the form is submitted, but I'd like to go a step further and be able to set a custom view to be shown much like the "No results behaviour" option.

Interestingly, with a "no results" view set, I can submit the form with an empty search field and my custom view will show. This is what I also need to be shown before anything has been submitted.

Is there a configuration where this is possible in views, or any way this can be achieved in code?

# Answer
Looks like the required\_filter\_input module is the way to go, as it requires one exposed filter to have a value before returning results, which triggers the custom "no results" view without any input by default.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Is it possible to create a list of pages in a view even if a user doesn't have access to those pages?
I'm creating a set up in Drupal 7 using Organic Groups and the Subgroups module where there is a Company group, and each company can have multiple Project groups. I'd like to allow users that have access to a Company Group to see all Projects underneath that company in a View, regardless if they're part of the project group or not. From there, a user can either view the project page, or they can subscribe to the project group.

Is it possible to give a user access to a parent group and allow to see all of its child groups in a View, but restrict viewing a page in a child group?

# Answer
> 0 votes
Have you tired disabling SQL Rewriting?

In the advanced fieldset in the right column when editing the view, click Query Settings

There is a checkbox "Disable SQL Rewriting" which has help text "Disabling SQL rewriting will disable node\_access checks as well as other modules that implement hook\_query\_alter()."

Try checking that checkbox and saving the View

---
Tags: views, organic-groups
---


title: How do I access the user email?

text:
# Question
Title: How do I access the user email?
I am using Drupal 8 to create a website for training purposes. The user roles are Trainer, Trainee. I have content type session where I get to allocate the trainer for a particular date. It is done by user reference.

By using rules I want to sent notifications to the trainer regarding the scheduled session. But I am not able to achieve this.

Is there any other way I can sent notifications to the trainer other than using Rules module? Please help.

# Answer
I am not sure if you can send a mail without any custom coding, but you can definitely do this via custom code. Refer examples module, which has an example on how to send mail.
> 0 votes

---
Tags: rules
---


# Question
Title: Views filter based on value in referenced entity
I'm attempting to use a view to display the body of a content type that is referenced based on a field referencing another content type as long as that content type is referenced by another field. Confusing I know. Here's a diagram of what I'm trying to accomplish.

I need to display the body and title of all 'news' that reference a 'horse' that an 'owner' references as long as that 'owner' is referencing the current user.

I understand that there would be much better ways to structure my content type fields to get them to play more nicely, and I understand that I could easily accomplish this by not using views and making a custom module but that isn't an option available to me. I am required to use views. I wouldn't mind creating a custom views filter plugin, or use a hook though. I understand how to perform entity queries that can accomplish this task. However I'm not sure how view filter plugins work.

Is there a way to accomplish this specifically with views?

# Answer
> 1 votes
So assuming there's a content type with machine name new for News, owner for Owner, horse for horse.

The news content type has a field named field\_horses referencing horses

The owner content type has an instance of the same field field\_horses and a reference field to User, field\_user

Create a view listing Content of type News

Add a relationship

Entity Reference: Referenced Entity A bridge to the Content entity that is referenced via field\_horses

require this relationship

add a second relationship

Entity Reference: Referencing entity A bridge to the Content entity that is referencing Content via field\_horses

have this second one use the first relationship "Content Entity referenced from field\_horses"

require this relationship

add a third relationship

Entity Reference: Referenced Entity A bridge to the User entity that is referenced via field\_user

have this third relationship use the second relationship "Content referencing content from field\_horses"

require this relationship

For filters you need two content type filters One for Content type = News, using no relationships another for Content Type = Owner using the "Content referencing content from field\_horses" relationship

One user filter, Current User (yes), using the "User entity referenced from field\_user

```
$view = new view();
$view->name = 'news';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'News';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'News';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['field_horses_target_id']['id'] = 'field_horses_target_id';
$handler->display->display_options['relationships']['field_horses_target_id']['table'] = 'field_data_field_horses';
$handler->display->display_options['relationships']['field_horses_target_id']['field'] = 'field_horses_target_id';
$handler->display->display_options['relationships']['field_horses_target_id']['required'] = TRUE;
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_horses_node']['id'] = 'reverse_field_horses_node';
$handler->display->display_options['relationships']['reverse_field_horses_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_horses_node']['field'] = 'reverse_field_horses_node';
$handler->display->display_options['relationships']['reverse_field_horses_node']['relationship'] = 'field_horses_target_id';
$handler->display->display_options['relationships']['reverse_field_horses_node']['required'] = TRUE;
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['field_user_target_id']['id'] = 'field_user_target_id';
$handler->display->display_options['relationships']['field_user_target_id']['table'] = 'field_data_field_user';
$handler->display->display_options['relationships']['field_user_target_id']['field'] = 'field_user_target_id';
$handler->display->display_options['relationships']['field_user_target_id']['relationship'] = 'reverse_field_horses_node';
$handler->display->display_options['relationships']['field_user_target_id']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'news' => 'news',
);
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type_1']['id'] = 'type_1';
$handler->display->display_options['filters']['type_1']['table'] = 'node';
$handler->display->display_options['filters']['type_1']['field'] = 'type';
$handler->display->display_options['filters']['type_1']['relationship'] = 'reverse_field_horses_node';
$handler->display->display_options['filters']['type_1']['value'] = array(
  'owner' => 'owner',
);
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['relationship'] = 'field_user_target_id';
$handler->display->display_options['filters']['uid_current']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'horse-news';

```

---
Tags: views, 8, entities
---


title: Calendar View Remove Duplicate Items

text:
# Question
Title: Calendar View Remove Duplicate Items
I'm using Calendar module to display a list of nodes with fields related to that specific days. I am handling multiple date fields using contextual filters. For example, if an item has a Preview Date of 7/1 and a Review Date of 7/2, the node item will show for each date. The problem is each node item is showing for each date, i.e. 7/1 and 7/2 show the item twice.

How do I remove the duplicate items? So each date only shows one of each node? I've tried aggregated fields/Count Distinct and Query Distinct but had no sucess.

# Answer
> 0 votes
you can try views distinct module from module page:

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

I hope it helps, be carefull in features, the module settings are not exported in features. If you use features, once you push your code, on production site, set your view UI settings again, it's easy and simple.

---
Tags: 7, views, datetime
---


# Question
Title: Contrib statistics: Reported installs and downloads
I've noticed that the number of reported installs is usually (not always) somewhat larger than the number of downloads. I figured maybe this is because of multi-site installations in which one download runs on several sites. On the other had, there have to be cases where a module is downloaded and not implemented in production, which perhaps would account for cases where there are more downloads than installs.

But I just noticed that "CKEditor Link" has over 50,000 reported installs and only 658 downloads. That doesn't make any sense. Does anyone know what's going on there?

These statistics are relevant to the decision of which modules and themes to use in a system. (Edit: They are relevant for me because I can't afford to be in a situation where my sites go down because a Drupal revision breaks a module and the module maintainers don't get it fixed pronto. This is much less likely to happen with an installed base of 50,000 than 500.)

# Answer
> 1 votes
EDIT: The problem is with a bug in the statistic module. Some information about sampling methods follows.

The number installs comes from the Project module used on drupal.org. On the project usage page, it links off to documentation about usage statistics which states:

> As always with statistics of this sort, they don't tell the whole story. For example, the results shown for "Drupal" are a poor estimate of the number of Drupal sites on the internet. This is because only sites running the Update Status module report data back to drupal.org.

Downloads are likely to have heavier bias, compared to installations, due to a number of factors limiting installation reporting (e.g. modules never installed, modules uninstalled, sites without Update Status running, etc.)

# Answer
> 5 votes
This is simply due to a bug with the statistics module - see Project Download count Decreased \- that has affected Drupal.org infrastructure since the middle of April 2015.

Prior to that bug surfacing, I did not observe a *single* project where the number of downloads were less than the number of installs.

Just now **CKeditor Link** is reported to have 487 downloads. That is *171 less* than the 658 reported by the OP in the question (asked two days ago).

Until this bug is fixed, the *download* statistics should just be regarded as a random number.

As reported by Pierre.Vriens, another bug sometimes affect the *installed* statistic on the Drupal.org. This affected many projects a couple of days ago, but seems to have been fixed for most of them today.

# Answer
> 3 votes
Something seems really wrong these days with these statistics, and this for any of the modules I've been checking lately. As a (random) sample, consider the Charts module: similar issue. But there is more: look at the "Usage Statistics" page of the Charts module (or just any module): the typical numbers there get updated somewhere on Sundays. While these updates are happening (on Sundays), the date (line) is already added, but with a counter 0. However this week (since last Sunday), it has always been 0.

Anyway, about your last phrase: be careful in "only" using these stats. Instead you may want to consider many more (like 23?) criteria to help you make decissions. As I documented in (what I call) maintenance scorecards. In this case they relate to charting modules (that's where my interest in Drupal mostly is). But you can apply them for any set of modules of course.

Note: I'd be interested in other criteria to be considered to evaluate modules. Feel free to "edit" that community page (or add comments to it) for any such criteria to be added to it.

# Answer
> 0 votes
I am also facing the same issue, The Reported installs count is not updating for https://www.drupal.org/project/domain\_googlenews\_sitemap. Can anyone please help in finding a solution to this.

---
Tags: community-official-site
---


title: Adding elements to a field widget

text:
# Question
Title: Adding elements to a field widget
What I need to accomplish is adding a link to a node to field widgets (the node contains the formatted instructions to properly compile the field).
The goal is something like this:

"What is this?" is the link to a node, to be opened in a new tab or in a popup. In this example the field is a select, but it could be any type of field.

So far I've been able to add the node reference field in the field config form, using Third Party Settings:

```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === 'field_config_edit_form' && $form_state->getFormObject()->getEntity()->get('entity_type') == 'myentity') {

    $field = $form_state->getFormObject()->getEntity();
    $help_page_id = $field->getThirdPartySetting('mymodule', 'help_page_id');

    $form['help_page_id'] = array(
      '#type' => 'entity_autocomplete',
      '#title' => t('Help page'),
      '#target_type' => 'node',
      '#selection_handler' => 'default',
      '#selection_settings' => array(
        'target_bundles' => array('help_page'),
      ),
      '#default_value' => $help_page_id ? Node::load($help_page_id) : NULL,
      '#weight' => 100,
    );

    $form['#entity_builders'][] = 'mymodule_form_field_config_edit_form_builder';
  }
}
```

Now I'm having troubles retrieving this information when showing the form, and altering the field widget in order to display the link. Using hook\_field\_widget\_form\_alter, I cannot get the custom configuration value from the arguments I have:

```
function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {

}

```

I guess I have to load the field configuration entity, but I don't know how.

# Answer
Make sure you include the following:

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;

```

I'm assuming your function `mymodule_form_field_config_edit_form_builder()` looks something like this:

```
/**
 * My module form builder to map values to third party settings.
 */
function mymodule_form_field_config_edit_form_builder($entity_type, FieldConfig $field, &$form, FormStateInterface $form_state) {
  $field->setThirdPartySetting('mymodule', 'help_page_id', $form_state->getValue('help_page_id'));
}

```

In your widget form alter you'd access the settings with with FieldConfig. This would add it to all field types, you can check `$field_name` if you want to filter it a bit.

```
function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_name = $context['items']->getName();
  $field = FieldConfig::loadByName('node', 'myentity', $field_name);
  $help_page_id = $field->getThirdPartySetting('mymodule', 'help_page_id');
}

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Creating/registering a user (of a custom profile type) when a certain webform is submitted?
Before all else - Here's my current code.

```
function hook_webform_submission_insert($node, $submission) {

  $password = user_password(8);

  //set up the user fields
  $new_user = array(
    'name' => $form_state['values']['e_mail'],
    'mail' => $form_state['values']['e_mail'],
    'pass' => $password,
    'status' => 0,
    'init' => $email,
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      6 => 'custom role',
    ),
    'field_dealer_fname'=> $form_state['values']['first_name'];
    'field_dealer_lname' => $form_state['values']['last_name'];
    'field_dealer_company' => $form_state['values']['company_name'];
    'field_dealer_phone' => $form_state['values']['phone'];
  );
 $account = user_save(null, $new_user)

    ->execute();
}

```

I'm very new to Drupal, but intermediate experienced in Web dev in general. I just recently inherited a client from a previous employee before I joined, and he exclusively used Drupal (7, at that.)

Anyways, he previously had a system to set up a new user through this user-submitted webform, but that functionality apparently died 2 months ago in some sort of host migration. Now, I'm trying to figure out a way to accomplish this task with the already existing webform (v 3.27) and database.

That being said, from what I've found, I'm trying to use a webform Submission Hook to call the (Webform) values

```
first_name,
last_name,
company_name,
phone,
e_mail

```

to fill the adjacent (Custom) user profile fields of "Dealer\_profile" (along with the default ones)

```
field_dealer_fname
field_dealer_lname
field_dealer_company
field_dealer_phone

```

So, referring back to my code, my thought process is:

```
//create a random 8 char password
  $password = user_password(8);

```

I was thinking this would be the equivalent of saying "these profile values = this user submitted value"

```
//set up the user fields
  $new_user = array(
    'name' => $form_state['values']['e_mail'],
    'mail' => $form_state['values']['e_mail'],
    'pass' => $password,
    'status' => 0,
    'init' => $email,
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      6 => 'custom role',
    ),
    'field_dealer_fname'=> $form_state['values']['first_name'];
    'field_dealer_lname' => $form_state['values']['last_name'];
    'field_dealer_company' => $form_state['values']['company_name'];
    'field_dealer_phone' => $form_state['values']['phone'];
  );

```

and ultimately, save this information and execute the hook?

```
 $account =    user_save(null, $new_user)

    ->execute();

```

However, I feel like the hook itself is also wrong. This whole hooking thing in Drupal is a little odd to me, coming from mostly Wordpress use. Unfortunately the documentation is a little barebones, or in some way difficult for me to figure out how these things actually work. I was also just kind of thrown into this, and just have to figure everything out! Help is appreciated!

# Answer
> 0 votes
First you can add your code and add inside sites\all\modules\webform\includes\webform.submissions.inc in functions named "webform\_submission\_insert" , and check if it works or not , also as per below image in $submission variable you will get all webform submitted values .

Also , if you want to Get Webfrom submitted data by userid wise use below code anywhere.

```
module_load_include('inc', 'webform', 'includes/webform.submissions');
$values = webform_get_submissions($nid, null, $user->uid, 1);

```

if you want to Get Webfrom submitted data by node id , as below code 105 is node id.

```
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(105);

```

---
Tags: 7, entities, users, webforms
---


title: What is a placeholder?

text:
# Question
Title: What is a placeholder?
Drupal uses the concept of a placeholder quite a lot during form creation and theming, and also has a Placeholder Strategy in its the response event of its Render Pipeline.

What wasn't explained is what is a Placeholder?

# Answer
> 2 votes
In the render pipeline placeholdering is used together with lazy building, see this example from the status messages:

*\Drupal\Core\Render\Element\StatusMessages*

```
  /**
   * #pre_render callback to generate a placeholder.
   *
   * @param array $element
   *   A renderable array.
   *
   * @return array
   *   The updated renderable array containing the placeholder.
   */
  public static function generatePlaceholder(array $element) {
    $element = [
      '#lazy_builder' => [get_class() . '::renderMessages', [$element['#display']]],
      '#create_placeholder' => TRUE,
    ];

    // Directly create a placeholder as we need this to be placeholdered
    // regardless if this is a POST or GET request.
    // @todo remove this when https://www.drupal.org/node/2367555 lands.
    return \Drupal::service('render_placeholder_generator')->createPlaceholder($element);
  }

```

Then, before caching, the renderer puts instead of the content a static placeholder, which will be, on delivery, replaced with the actual content from the lazy builder.

The placeholdering is done here right away, see the last comment in the code. Which is good for demonstration purpose. If you run this code the result will look like this:

```
<drupal-render-placeholder callback="Drupal\Core\Render\Element\StatusMessages::renderMessages" arguments="..." token="..."></drupal-render-placeholder>

```

By the way, the content of the placeholder tag in the markup is not important, it only has to be unique to be replaceable. The details are for debugging purpose only. The response event subscriber uses the information attached to `['#attached']['placeholders']`.

A placeholder strategy is for example BigPipe, which uses another strategy to deliver the placeholder content after page load.

---
Tags: theming, 8
---


# Question
Title: Allow the user to send emails to all or selected rows in a particular views display
Salut!

I have been working on a 100% non-profit project for 1 month and now I am facing a problem with the main feature that this project offer for free.

The project is a website about people willing to help other for free so there are two roles on the website: **Job helper** and **Job Seeker**

When someone register under the role of **Job helper**, he will be asked to verify his phone number and email address because at any time he might receive email/sms asking him for help.

When someone register under the role of **Job seeker**, he will be able to see a list of all available **Job helper** using a view display and then choose one from two options:

1. A button or link to Send emails to all the available listed **Job helper** profiles, or
2. A button or link to send email to only *selected* **Job helper** profiles.

**Problem:**

How to create such functionality, note that the view is already created and displaying all available users which are registered under the **Job helper** role but I cannot find a way to place a **button or link** within the view as well as check box near to every user so a **Job Seeker** can select all or select few profiles and send a customized email.

**Solutions:**

1) Using VBO, is possible to do the above, however after selecting users to send emails for them, I want the **Job Seeker** to be able to customize only the message body being sent, but VBO will display all the field shown in the picture below which will confuse the user of the website.

I want to display only the message text body so the **Job Seeker** can customize his own message like:

*"We need help in cleaning the beach of Florida from any garbage at 14:00 tomorrow 15/Jun/2017, please be there for the beach"*

Note the **Job Seeker** will have to write no recipient and no subject just a message text about the job.

2) I have an idea about using flag module with views, and so the **Job Seeker** will have to flag every single **Job Helper** and then write a customized message body to be send via email... But I really have no ideas from where I should start ?

Please note that I need to integrate rules with the solution because if every **Job Seeker** has the right to send **1000 emails** per weeks and so I want to use rules to **"-1"** for every email being sent by a specific **Job Seeker** user.

Any suggestion and help will be much appreciated ! Thank you,

# Answer
> 0 votes
I wrote an answer somewhat similar to this functionality.

https://drupal.stackexchange.com/a/195228/53677

Basically, you could create an entityform with an entityreference field for emailable users and a field for your email message.

Then on your view page, provide an email button and use jQuery to create a link to pre-populate the users you want to email. Use Rules to loop this on entityform save.

The link to the form would have to look like `/eform/submit/email-form?field_email_uids=10,12,15,201`

It's a bit more work but can give a really nice interface if done right. Your view can be anything as long as you can grab the UIDs.

Or you could just hide the fields you don't want with css / jQuery.

**Edit: Adding instructions for the jQuery part**

Here's a very basic example of the finished result. This can be added to any view setup.

You can of course decide to not use checkboxes and perhaps add a border or background etc. to the whole row. You can do anything you like with jQuery and `.parent()`etc. to go up the DOM and add/remove classes.

Views Custom Text Field: (The UID and Name fields are hidden above. I use font-awesome on this install. You can use ✓ or something else instead of the )

```
<a href="#" class="email_box" value="[uid]">
<i class="fa fa-check"></i></a>
<span> [name] </span>

```

Views Footer Custom Text Field:

```
<a href="/eform/submit/email-form" id="email_link">Send Email</a>

```

jQuery:

```
$('.email_box').click( function() {

    // Check if it's clicked + add / remove classes
    if ( !$(this).hasClass('email_checked') ) {
        // Add Class
        $(this).addClass('email_checked');
    } else {
        // Remove Class
        $(this).removeClass('email_checked');
    }

    // Call function below for Email Link
    build_link();

});

// Get all boxes that are clicked and add their value tags to the link
var build_link = function() {
    var email_uids_array = [];
    // Loop checked and add UIDs to array
    $('.email_checked').each( function() {
        email_uids_array.push( $(this).attr('value') );
    });
    // Split array into uids
    var uids = email_uids_array.toString();
    // Create link
    var link = '/eform/submit/email-form?field_email_uids=' + uids;
    // Alter the Email link's href
    $('#email_link').attr('href', link);
};

```

Some CSS so it makes sense to the user:

```
.email_box {
  border: solid;
  border-width: 1px;
  border-color: #c2c2c2;
  color: #ddd;
}
.email_checked {
  color: #444;
}
/* Fix Hover / Focus */
.email_box:focus,
.email_box:hover {
  color: #ddd;
}
.email_checked:focus,
.email_checked:hover {
  color: #444;
}

```

The benefits here are total customization and it should work pretty well.

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


# Question
Title: Drupal equivalent of WordPress' page templates
I'm developing my first Drupal site, having built my CMS experience on WordPress. I've managed to wrap my head around many of Drupal's paradigms, but I can't figure out how Drupal accomplishes the functionality of page templates in WordPress.

By "page templates" I mean the option in WordPress to set a specific template (written in PHP) to use for a given page:

For reference, I use the templates in multi-site deployments to create standardized pages for subsites (e.g. "contact", "about us"), but a subsite has the ability to disable the template and create their own content.

What would be the best practice to accomplish this?

# Answer
There are several ways to suggest/override theme of a page in Drupal.

**1. Override core theme files:**

Firstly there are core themes defined by Drupal, which can be overridden from your theme. For example, the default user profile page uses `user-profile.tpl.php`. Though this is defined in Drupal Core, you can override it by copying it to your theme folder and modifying. The list of core file can be found here.

**2. Default Theme Suggestions in Core**

Drupal has implemented some default theme suggestion patterns in the core. It helps us write a specific theme for a page, path or even a particular article without having to write code. For example, if your about page has a node id 1. You write a template for just that page by creating a template file `page--node--1.tpl.php` in your theme folder. Similarly, you can suggest a theme for a node, user, block etc. You can see available core suggestions in this page under respective heading.

**3. From UI using context module:**

Context module allows you to manage contextual conditions and reactions for different portions of your site. You can, for example, choose 1 or more conditions like path, user type etc and then add theme suggestion as a reaction to that condition/s.

1. Using context module.
2. Also, see ThemeKey module.

**4. From code:** You can also write custom theme suggestion based on your own logic from code, either in template.php file of your template from a custom module.

An example from documentation:

// Add a single suggestion for nodes that have the "Promoted to front page" box checked.

```
function drop_preprocess_node(&$variables) {
  if ($variables['promote']) {
    // looks for node--promoted.tpl.php in your theme directory
    $variables['theme_hook_suggestions'] = 'node__promoted';
  }
}

```

A lot of code example can be seen if you scroll a bit down on this page.

**Additionally,** change the theme debug settings in setting.php to get additional information in HTML markup with respect to the theme. The setting to change is `$conf['theme_debug'] = TRUE;`. Once done, you'll get a lot of valuable suggestion in the HTML markup of each page.
> 0 votes

---
Tags: theming
---


title: Logging in with email and not username

text:
# Question
Title: Logging in with email and not username
I tried the module LoginToboggan to log in entering the email and not the username (that I use as Facebook ID). The problem is that the module allows to log in with either the email or the username.

How can I log in with just the email?

# Answer
> 0 votes
There is a module for that, try Email Registration, from module description:

> Allow users to register and login using only an email address. Users can then log-in using their email address and password for authentication.
>
> A username is generated and assigned based on the user name part of the email address and their user ID

is avilable in D7, D8

# Answer
> 0 votes
you can use this module https://www.drupal.org/project/login\_email

Also this module is very useful https://www.drupal.org/project/email\_registration

hope it helps you.

---
Tags: users, emails
---


# Question
Title: How to programmatically get node ID in custom Rules Action
Need to create a custom Rules Action. How do I pragmatically get the node ID for an action such as when a node is saved?

# Answer
You can pass parameter node then you will get full node object into your action.

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

```
> 1 votes

---
Tags: 7, nodes, rules, hooks
---


# Question
Title: Use sass variable and mixins from base theme in sub theme
I need some help regarding sub theming with sass. The sub theme setup is as follows :

1. There is a base theme `base` which has sass variables and mixins defined.
2. I run grunt and compile the sass.
3. There is a subtheme of `base` called `microsite` with similar sass structure as `base` but no styles as presently it uses only the base styles.

Q. How do I use the sass variables and mixins defined in `base` theme inside `microsite` theme?

Eg - 1 : Inheriting the base color palette.

I have a color palette defined under base theme with my color variables. `themes/custom/base/sass/core/variables/_palette.scss`

I want to use these palette variables in defining styles in my `microsite` subtheme at `themes/custom/microsite/sass/base/color/_buttons.scss`.

Eg - 2 : Inheriting the base gradient mixin.

I have a linear-gradient mixin defined under base theme at `themes/custom/base/sass/core/abstractions/_linear-gradient.scss`

I want to use this mixin in defining styles in my `microsite` subtheme at `themes/custom/microsite/sass/base/color/_buttons.scss`.

# Answer
> 2 votes
There's no special process because it's Drupal or sub/parent theme relationships, just import what you need. E.g.

```
@import '../../../../base/sass/core/abstractions/_linear-gradient.scss';

```

---
Tags: theming
---


title: Pager with EntityQuery

text:
# Question
Title: Pager with EntityQuery
how can I make a pager with the pager class? I could not find anywhere how to do this with the EntityQuery class. I have a `pager(10)` that displays the last 10 items. I want to make a pager with numbers like \< 1, 2, 3, 4, 5, 6 \>.

This is the code I have now:

```
class NewsArchive extends BlockBase {

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

    // Query for newest articles and return max 3 results.
    $query = \Drupal::entityQuery('node');
    $news = $query->condition('type', 'news')
      ->condition('status', 1)
      ->sort('created', 'DESC')
      ->pager(10)
      ->execute();

    // LoadMultiple News in $nodes variable
    $nodes = Node::loadMultiple($news);

    $path = base_path();

    // Return $nodes variable with name items to the module.
    return array(
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
    );

  }
}

```

I have read somewhere that this was possible with the following code:

```
      $build['pager'] = [
        '#type' => 'pager',
      ];

```

How does this build pager (render) fit into my code? Can someone show me how to start?

# Answer
Add the pager to the build array in which you return the results:

```
  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
    ],
    'pager' => [
      '#type' => 'pager',
    ],
  ];

```

Or extend the theme with a variable `#pager` if you want to theme this in one place:

```
  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
      '#pager' => [
        '#type' => 'pager',
      ],
    ],
  ];

```

Then you can print the pager in twig:

```
{{ pager }}

```
> 3 votes

---
Tags: database, paging
---


# Question
Title: Adding pager to queried content in a custom module Drupal 8
I've created a custom module to get X items using entityQuery, and then display them as a list. I need to limit these and add a pager to click through to the next page, but I cannot find how best to do this. Examples I've found either use external search sources, or are depreciated functions of older versions of Drupal.

I've added the pager option in the query, initialized the pager, and added the `#type = pager` to the content block, but it's not showing up. I know I am missing something but I cant figure out what it is.

```
class MyPageController extends ControllerBase {

public function myPage1() {

    $query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'page')
    ->range(0, 10)
    ->pager(3)
    ->sort('created', 'DESC');

    $nids = $query->execute();
    $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

    pager_default_initialize($query->total, '7');

    $list = array();

    foreach ($nodes AS $node){
        $list[] = $node->get('title')->value;
    }

    $content = [
        '#theme' => 'item_list',
        '#list_type' => 'ul',
        '#title' => 'Page list',
        '#items' => $list,
        '#attributes' => ['class' => 'my_page1_list'],
        '#wrapper_attributes' => ['class' => 'container'],
        '#type' => ['pager'],
    ];

    return $content;
}
}

```

# Answer
> 1 votes
The format of the render array is wrong, you have to place the pager in its own render element (see this question, which was almost at the same time Pager with EntityQuery) or if you want to have it in the theme in a variable, but then a name other than `#type`.

---
Tags: 8, paging
---


# Question
Title: Add new existing field for existing content type
I have a development site (let be site 1) and a site where I check my code (site 2). My goal was to add a new existing field to a paragraphs type (/admin/structure/paragraphs\_type), so I did the following:

On site 1:

* I re-used an existing field in one of the paragraphs type
* I exported the configuration
* I deleted uuid and \_core.default\_config\_hash from the configuration files (from those which was relevant for me)
* I wrote an update hook which will create the same config file (except order), when my module will be updated on other sites, where it was previously installed my module
* I put the exported 3 files to my module's config/optional dir

Than I moved this module to the site 2 where I run the update hooks. But the newly added field wasn't showed up on the paragraphs type's page under the correct paragraphs type. All the configuration's dependencies are right and enabled. Configuration file is same except the order. If I want to add the field on site 2 manually again, after config import I get this error: There was a problem creating field : 'field\_config' entity with ID 'paragraph.text\_boxes.field\_text' already exists.

Note: before I added the new field, I had a configuration export under git, so after I added a new field and exported the configuration I saw exactly which configs was touched.

What am I doing wrong? How can I add a new existing field to a paragraphs (or a content type)? What's missing?

# Answer
Well finally I found a working solution for me, however I don't know why doesn't show up by default after config save.

First I need to connect my existing field (which I want to re-use) to the selected content type/paragraphs type:

```
\Drupal\field\Entity\FieldConfig::create([
  'entity_type' => 'node',
  'bundle'      => 'page',
  'field_name'  => 'field_text',
])->save();

```

This code will add a new field which machine name is field\_text (needs to be exist in the system) into page content type which is a node.

Than if I edit the configuration (with `configFactory`) I can set the field name, view and form settings, etc. However you are able to set field settings with `FieldConfig`. (but not display and form)
> 0 votes

# Answer
if I am not wrong, I believe, Site 1 is your local development environment, and site 2 is your production environment.

`I wrote an update hook which will create the same config file (except order), when my module will be updated on other sites, where it was previously installed my module` Why would you write an update hook ? You can simply export the configs, and import them on prod. If this does not suit you, I would suggest you to use Features module for this. It will make sure you get a working module which can be installed even without features module in place on Prod.
> 0 votes

---
Tags: 8, entities, configuration
---


title: How can I get the image URL in a field?

text:
# Question
Title: How can I get the image URL in a field?
The image formatter has only one option: Image. I would like to get the URL, not the full markup, for a field output.

Do I need to make a custom formatter? Also, I don't see any way to rewrite the text using tokens to get the image URL.

# Answer
When setting up your view, under the *advanced* section you can create a *relationship* for the image field.

After you added the relationship, you can then add a *File URI* field, select the created relationship and you are good to go.
> 14 votes

# Answer
This is the magic, without the "Image URL Formatter" module:

1. You have to add a relationship in your view to your image field (It's under Advanced)
2. Now you can add a 'File URI' field to your fields
3. In your views-view-fields.html.twig template (Or one of the appropriate alternatives for your specific view) add this:

`{{ file_url(fields.uri.content|striptags|trim) }}`
> 8 votes

# Answer
Is the module "Image URL Formatter" maybe helpful for you? https://www.drupal.org/node/1162614/release?api\_version%5B%5D=7234

There is a second one: https://www.drupal.org/project/image\_raw\_formatter

I never did a feature comparison to find out which is the better one ...
> 2 votes

# Answer
1. Install the module twig\_tweak
2. Create a relationship in a View
3. Add *File URI* field, exclude it from display
4. Overwrite result, with the next twig code:

{{ uri | image\_style('thumbnail') }}

Where *uri* is the token of the *File URI* field and *thumbnail* is the desired image style.
> 1 votes

# Answer
Here is my solution that doesn't require a relationship:

* Add your image field to your view
* Set these properties:
    + Formatter: Image
    + Image style: None (original image)
    + Link image to: File

This gives you an output like this: `<a href="http://domain/path/to/file.jpg" ...`

* Under Rewrite results, check "Override the output of this field with custom text"
* In the text box put this: `{% if field_image|trim is not empty%}
{{ field_image|split('"')[1] }}
{% endif %}`

This splits the string on the `"` character and the index of 1 is your url in the href. It is kinda hacky but this actually gave me what I wanted. Going the relationship route I could only ever get a link with `public:/path/to/file.jpg` not the absolute URL
> 1 votes

---
Tags: views, 8
---


# Question
Title: Update image in image widget (automatically upload?) on another ajax reference field's autocompleteclose event
So I have a few fields that are automagically populated when an entity reference field is 'autocompleted'. Text and Image data (path, etc)

```
...field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
    $element['target_id']['#ajax'] = [
      'event' => 'autocompleteclose',
      'callback' => 'ajax_callback',
    ];

```

This is not an issue with text, but how do I update my image-widget (upload field) with a new image path and automagically upload?

```
...function ajax_callback(array &$form, FormStateInterface $form_state) {

// For text field this is pretty straightforward.
$response->addCommand(new InvokeCommand('input[name="field_....[' . $delta . '][subform][field_..._name][0][value]"', 'val', [$text]));

```

Is it possible to pass a path and filename to an image upload input(image-widget) and maybe mock .click() (or something) to trigger an automatic upload when selecting said field reference autocomplete?

Use case (total of 3 fields): User completes autocomplete field and two additional fields, say description and image (upload input) are automatically populated/image uploaded. (But I can go back if the user wants and update the image (separately) using normal options on the image upload input, if needed.)

# Answer
> 0 votes
No that isn't possible. You can't automate completion of a file input field, it would be a massive security hole (I think browser plugins for chrome/Firefox can do it, but they run in a different security context to website scripts anyway)

If it were possible, anyone with a website could steal any file from any visitor's computer they fancied.

---
Tags: media
---


# Question
Title: Getting "Page Not Found" After Enabling the Devel Module Drupal 7
I'm trying to install the Theme Developer which requires the Devel module.

I've downloaded the Devel module via the **Install new Module** page in Drupal. When I enable the module however, I get redirected to a "Page Not Found" error.

Going to **Reports** \> **Recent log messages** shows:

```
page not found  06/14/2017 - 10:23  modules/statistics/statistics.php
page not found  06/14/2017 - 10:23  modules/statistics/statistics.php
php 06/14/2017 - 10:22  User warning: The following module has moved within...
php 06/14/2017 - 10:22  User warning: The following module has moved within...
php 06/14/2017 - 10:22  User warning: The following module has moved within...

```

The three PHP messages complain that **devel\_node\_access**, **devel**, and **devel\_generate** have all been moved.

Could this be some form of permission issue?

---

**Edit**: I just tried again, but this time used a different theme. Devel was still not enabled, but I was redirected to a different page; `/q=admin/modules&filter=devel&enabled=1&disabled=1&required=1&unavailable=1`. Now I can't view any of my site. I rebooted my VM but my site is still unresponsive. Looks like enabling Devel has broken my site somehow.

---

**Edit 2**: Destroyed and rebuilt my VM. This time I **did not** change the theme to my custom theme, and instead left the default theme enabled. I refreshed all caches, and attempted to enable Devel (I didn't have to re-download anything since the modules were still in my VM directory). This time it worked! Devel is now enabled. I'm not going to write an answer to this until I know exactly what changed and why it's now working fine.

---

**Edit 3**: After enabling Devel, SimpleHTMLDom Api, and Theme Developer, I now see the following error on **any** of my pages.

# Answer
> 0 votes
the theme developer module has not been touched in years and it is unsupported. You should not expect it to work at all and it is certainly plausible that it will have detrimental effects on your site.

Unfortunately I suspect that you are out of luck unless you want to dig into the code yourself and attempt to get the module into a working state that does not blow up your site.

---
Tags: debugging
---


title: time in wrong time zone when using get

text:
# Question
Title: time in wrong time zone when using get
I have a date/time field, when I save it as 1:00:00 AM, it displays in the edit form as 1:00 am, however when I do a get of that field value in my module with `$posted_date=$static_media->get('field_pup_posted')->getValue();` , it comes out as\`Array ( \[0\] =\> Array ( \[value\] =\> 2017-06-14T05:00:00 )

)\`

Why is it being stored as a 5 when it should be a 1? and how can i get it programatically in the correct time zone

# Answer
> 2 votes
drupal stores in UTC have to convert this to current time zone

```
$dt=new \DateTime($changed_date, new \DateTimeZone('UTC'));
$dt->setTimeZone(new \DateTimeZone('America/New_York'));
$correct_date =  $dt->format('Y-m-d H:i:s');

```

---
Tags: 8
---


title: Image Styles and Progressive Images

text:
# Question
Title: Image Styles and Progressive Images
I am specifically asking for a D7 site, however I wouldn't mind know for D8 as well.

**Scenario**

1. Save an image in Photoshop as a progressive image.
2. Upload this to an Drupal image field that utilizes image styles.

**Question**

When doing this image styles creates a new image, is the new image still progressive or is there something I would need to configure to make sure that image styles does this automatically?

# Answer
Basically Drupal does not change that kind of attribute on an image. But I thinkg you can check this way : 1- Make a **very large image** with Photoshop ; 2- Save it without making it progressive ; 3- Upoad it on the website and try displaying it.

**NB** : Very large image because for this test you want to make sure the image will display slowly.

4- save your image again with Photoshop, making it progressive this time. And then : 5- Upload the new one ; 6- Try to display it in a new tab and compare. Certainly you will see if there is a difference.

That's what I would do....
> 1 votes

---
Tags: 7, media
---


title: Form submit : how to pass parameters?

text:
# Question
Title: Form submit : how to pass parameters?
I have a form with a submit button :

```
$form['my-custom-submit'.$i] = array(
    '#name' => $nid,
    '#type' => 'submit',
    '#value' => 'Delete Node',
    '#submit' => array('::deleteNode'),
);

```

This submit button calls this function :

```
public function deleteNode(array &$form, FormStateInterface $form_state, $nid)
{
    // My Delete function($nid)
    drupal_set_message('Delete : '.$nid, 'status');
    $form_state->setRedirect('my-route');
}

```

How can I pass the $nid parameter to my deleteNode function ?
Or if there is a way to get the '#name' in my function, it could be perfect too.
I cannot pass it through a $form\_state-\>getValue('abc') because it is a list of incremented ids : $form\['my-custom-submit'.$i\].

I have searched google for 4 hours without finding, but I'm pretty sure that there is a simple way to accomplish this (newbie).

Thanks in advance.

Edit : I found that the '#name' and value of the submit are passed to my function, I can get it like this :

```
public function deleteNode(array &$form, FormStateInterface $form_state)
{
    $last_nid = '';

    foreach ($form_state->getValues() as $key => $value) {
      $last_nid = $key;
    }
    // My Delete function($last_nid)
    drupal_set_message('Delete : '.$last_nid, 'status');
    $form_state->setRedirect('my-route');
}

```

Which isn't really elegant but does the job.
Is there a better way to get it ?

# Answer
You can try this. Set the node id in the form element

```
    '#nid' => $nid,

```

and use FormState::getTriggeringElement to get the triggering element and the property `#nid`:

```
  public function deleteNode(array &$form, FormStateInterface $form_state) {

    $trigger = $form_state->getTriggeringElement();
    $nid = $trigger['#nid'];

```

In some cases you have to get the triggering button from the parent property:

```
    $clicked_button = end($form_state->getTriggeringElement()['#parents']);

```
> 1 votes

# Answer
The form state contains which node was submitted using the `$form_state->getFormObject()`

```
$nid = $form_state->getFormObject()->getEntity()->id();

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to programmatically add a field to all product types?
In Drupal 7, I need to programmatically add a file field to all product types. I've tried the following in the enable hook for my module, but to no avail:

```
$field = array(
  'field_name' => 'my_name',
  'type' => 'file',
  'cardinality' => -1
);
field_create_field($field);

// Create the instance on the bundle.
$instance = array(
  'field_name' => 'my_name',
  'entity_type' => 'product',
  'label' => 'label',
  'bundle' => 'product',
  'required' => TRUE,
  'settings' => array(),
  'widget' => array(
    'type' => 'file_generic',
  ),
);
field_create_instance($instance);

```

What am I doing wrong?

# Answer
The entity as defined by drupal commerce should be `commerce_product`:

```
function commerce_product_entity_info() {
  $return = array(
    'commerce_product' => array(
      'label' => t('Commerce Product'),
      ...
    ),
  );
  ...

  return $return;
}

```
> 1 votes

# Answer
first of all you must get a list of all existing product type, `commerce_product_types()` is the function which will do the job , next for each product type you can add an instance of the created field. final code looks like this :

```
$field = array(
  'field_name' => 'my_name',
  'type' => 'file',
  'cardinality' => -1
);
field_create_field($field);
$product_types = commerce_product_types();
// Create the instance on the bundle.
foreach ($product_types as $key => $type) {
  $instance = array(
    'field_name' => 'my_name',
    'entity_type' => 'commerce_product', //commerce_product is true
    'label' => 'label',
    'bundle' => $key', //Bundle name replaces dynamically
    'required' => TRUE,
    'settings' => array(),
    'widget' => array(
      'type' => 'file_generic',
    ),
  );
  field_create_instance($instance);
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Why is an entity reference view field only showing one view result?
I have a form field on a node create form that is an entity reference, referencing a view that displays all of the appropriate results. The view displays *users* with a relationship to a content field on the user, so the fields returned are all content. There is also an argument that takes the logged-in user ID. On the node create form, the field in question, when set to show unlimited results, only shows the last result from the view. I feel like I've gone over any technical reason this could happen, now I'm wondering if this is a bug with user views, or elsewhere. I haven't found anyone reporting this yet in my searches, so I thought I'd post it here.

# Answer
> 0 votes
I was having this issue as well, and it came down to the view returning a different entity\_id than the one(s) I thought it should be returning. This happens because of incorrectly formed relationships.

A way to check this is to add a "dpm($options);" (if you're using the devel module) in the entityreference\_options\_list function of entityreference/entityreference.module file (just after the $options are returned from entityreference\_get\_selection\_handler) to see what options it is retrieving from the view.

I started a new Entity Reference view that just returned the entities that I wanted, and then I built my relationships backwards from there to finally get the correct number of entities in my form.

I hope this helps!

---
Tags: views, 8, entities
---


# Question
Title: Execute a custom function on 'user register' or 'login'
I am new to Drupal. I want to execute my custom function every time when user registers or logins to my site. How can I do this?

# Answer
> 6 votes
You can do this using the following hooks in your module.

1. hook\_user\_login
2. hook\_user\_register (In D7 we had `user_insert` hook.)

**Examples:**

User Login Hook:

```
function mymodule_user_login($account){

   //your code here
}

```

User Register Hook:

```
function mymodule_user_insert(Drupal\Core\Entity\EntityInterface $entity){

   //your code here

}

```

# Answer
> 0 votes
You can also use rule module for user login/register.

---
Tags: 8, hooks, console
---


# Question
Title: How to compare form value in an ajax call
I have a date picker in my custom form. 'from\_date'. When I change the value in this, I need to call a function and compare the date value with another custom value and need to show a popup using custom plugin alertify. I have been succeeded up to creating an ajax\_call\_back function. But I'm stuck in retrieving form data and showing the popup. ...

```
$form['from_date'] = array(
        '#type' => 'date_popup',
        '#date_format' => 'd-m-Y',
        '#ajax' => array(
            'callback' => 'check_date',
            'event' => 'change',
        ),
        '#attributes' => array('class' => array('date_popup_frm'),)
    );

```

....

```
function check_date($form,$form_state){

//how can I compare the value with $value which I will get after calling an SP

}

```

# Answer
I found an answer for me after trying various cases. The below is the call back function which I wrote.

```
function check_date($form,$form_state){
 $current_date = $form_state['values']['from_date'];
 $custom_value = sp_call_and_extract_needed_data();
 $error_message = t('your error message');
 $current_path = current_path();
 if (strpos($current_path, 'ajax') !== false) { //if call from ajax
   $commands[] = ajax_command_after('#breadcrumbs',  $error_message);
   return array('#type' => 'ajax', '#commands' => $commands);
 } else {
   form_set_error('from_date', $error_message);
 }
}

```
> 0 votes

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


title: hook_user_login not working

text:
# Question
Title: hook_user_login not working
After user enter email and password. hook\_user\_login gets triggered and excute below code. I am placing code in "bootstap\_business.theme" file like this

function hook\_user\_login($account) {

$email = $account-\>geteMail();

echo "Email: $email";

$ch = curl\_init();

curl\_setopt($ch, CURLOPT\_URL, "http://example.com/users" );
curl\_setopt($ch, CURLOPT\_RETURNTRANSFER, 1 );
curl\_setopt($ch, CURLOPT\_POST, 1 );
curl\_setopt($ch, CURLOPT\_POSTFIELDS, "$email" );
curl\_setopt($ch, CURLOPT\_HTTPHEADER, array('Content-Type: text/plain','Authorization: ff23fdcffdgh5dsdsds'));

$result=curl\_exec ($ch);

}

But i am not getting whether this function is excuted or not. How can i debug/solve this problem. If i do echo also its not printing anything.

# Answer
> 1 votes
Only alter hooks and some specific theme-related hooks can be implemented in a theme.

`hook_user_login` isn't one of them, you need to implement it in a module.

To create a custom module see the official Creating custom modules docs. You essentially need a .info.yml file and a single .module file containing this:

```
function MYMODULE_user_login($account) {
  // Your code here
}

```

# Answer
> 0 votes
Try to implement hook in the module. Suppose you are creating new module name 'example', then this code for the module file.

```
/**
 * Implement hook_user_login
 */

function example_user_login(&$edit, $account) {
    $email = $account->mail;
    echo "Email: $email"; exit;
}

```

---
Tags: views, theming, hooks
---


# Question
Title: Contextual links for nodes displayed via views
When you create a node or a block you get a contextual link icon in top right of the item when hovering and etc. It is easy to edit content like that and etc.

When you create a view page and display multiple nodes via it, there are no contextual links hovering on those items and the only way to edit those is via Content.

I.e. I have a Panels page. It has a node at the top area of the page and it has that hovering icon for contextual links and it is easy to edit that node while viewing this panels page.

And then at the bottom area there's is a view which shows some grid-listed nodes too and none of those nodes has access to contextual links.

So is this possible somehow to add contextual links to nodes shown via Views?

# Answer
> 7 votes
Solved it myself.

# Steps:

1. Enable `Global: Contextual Links` and `Content: Edit Link` fields
2. Exclude `Content: Edit Link` from display
3. In `Global: Contextual Links` settings, select the `Content: Edit Link`

However this works correctly and fine only while in preview mode, when watching the actual page in action the links nor the cog icon does not appear. As I understand this is some kind of a bug.

To fix that, you need to add additional CSS to your theme, which is (in my case):

```
.views-field-contextual-links {
  position: relative;
}

```

And now everything works fine, every element has it's own drop down cog/link.

# Answer
> 3 votes
In Drupal 8 this is currently broken (as of 8.3.2). Until this is fixed, here is an alternative:

* Add the "Link to Edit Content" field to your view
    + Give it a label like "Edit node"
    + Choose to Exclude from display
* Add the "Global: Dropbutton" field to your view
    + Selecting the above Link to Edit Content in the settings
* Rearrange the fields to be at the top of your view
* Depending on your theme you may need to style this yourself. Here's some simple CSS you can start with:

```
.contextual-region.view .views-field-dropbutton {
    display: none;
    position: absolute;
    right: 0;
}
.contextual-region.view:hover .views-field-dropbutton {
    display: block;
}

```

---
Tags: 7, views, panels
---


title: Find Out Which Template To Edit/Create

text:
# Question
Title: Find Out Which Template To Edit/Create
I've got a Drupal 7 site with a default theme (Nuboot\_Radix). How do I find out which template files (`.tpl.php`) are being used on each page. For example, I have the following page:

How do I find out which file to change in order to change how the datasets are displayed here (in this case **Age by Economic activity 2011**, **2011 UK Borders**, **Ethnic group 2011**).

I understand that I need to make these changes in a subtheme, which I have already created. But I don't know what to call the `tpl.php` files, what the put in them, what variables I can use, etc. If I could find out where the html was being created for that section then I can figure out the rest myself.

I have been advised in another drupal post to not use Theme Developer since it is no longer supported.

# Answer
> 0 votes
`tpl.php` files are called templates in the Drupal system. They render the HTML that you see on any given page, may it be a block/view/panel or anything.

Theme Developer is a popular module used to pinpoint the template file that's in play. I suggest you try it to better understand how template system works. To understand more on customizing templates and naming conventions read through this guide on working with template suggestions.

**If its a view you want to modify**\- Use views GUI to the maximum extent(changing the sort order, re-arranging fields etc.). Still not getting what you want ? Override view templates for maximum control.

(Helpful Articles on overriding view templates)

http://www.wdtutorials.com/drupal/views/how-to-create-custom-template-view-drupal-tutorial-article

https://www.interworks.com/blog/carmstrong/2013/02/27/quick-tutorial-overriding-drupal-views-using-templates

---
Tags: views, theming, nodes
---


title: Request referer gets cached

text:
# Question
Title: Request referer gets cached
I need to grab referer and save it for the first time (I save it to sessions) and when the user gets to a specific page forward it. My problem is that after opening page with the **same** referer few times, I am not getting referer anymore. I tried it with few different browsers in private/incognito mode but after a few tries it gets cached and does not return anymore. My Code :

```
function HOOK_template_preprocess_default_variables_alter(&$variables)
{
    $request = Drupal::request();

    var_dump($request->headers->get('referer')); //stops dumping after few times

    $_SESSION['referer']['url'] = $request->headers->get('referer');
    $variables['#cache']['contexts'][] = 'headers:referer';
}

```

Is there a way to save referer for every anonymous user that comes to website?

# Answer
For doing this, i won't use a hook but the drupal eventSubscriber :

First your need to make a custom module with the file for declare to drupal your new service :

> myModule.services.yml

```
services:
  myModule.services:
    class: Drupal\myModule\EventSubscriber\MyServiceSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

```

Then in the file :

> myModule/src/EventSubscriber/MyServiceSubscriber.php

```
<?php

namespace Drupal\myModule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

    /**
     * Class myServiceSubscriber.
     *
     * @package Drupal\myModule
     */
    class MyServiceSubscriber implements EventSubscriberInterface {

        public function onRequest(GetResponseEvent $event) {
           // here your code, this method ll be call on every call request
           // so you can code your logic here
        }

      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {

          $events[KernelEvents::REQUEST][] = ['onRequest', 900];

          return $events;
      }

    }

```
> 0 votes

---
Tags: 8, caching
---


# Question
Title: Why do I get "Access Denied" on every page?
I've been trying out Drupal 8 on localhost which has been great, and I've now transferred it to a server, but every page gives me *Access Denied*. I can't even access the front page, or the user login page.

I have tried truncating the session and cache tables, and deleting cookies, but don't know what else to try. I've also installed drush, cleared the cache, and tried user-login drush command - still no access.

What things should I check? How do I fix this?

# Answer
Don't edit core code as suggested by Flounders answer. If you're not using HTTP auth then simply disable the Basic Auth module via the UI or Drush:

```
drush pmu basic_auth -y

```

Drupal has different authentication providers. The defaults are: basic\_auth and cookie, basic\_auth has a higher priority but is not enabled by default.
> 17 votes

# Answer
If you came here with the intention on figuring out why your **Drupal 8** site is now throwing ***Access Denied*** messages after enabling the **Relaxed** module (dependency on **Workspace** which is also dependent on core's Basic\_Auth module) you'll want to read this:

https://www.drupal.org/node/2842858

It took me several days of hunting around to finally get the right Google Search query to find the right answer. I hope this finds others in the same spot I was in.
> 4 votes

# Answer
I had this happen to me when I accidentally changed the password of the mysql username that Drupal was using for authentication to the DB. Make sure the DB user/pass is correct in settings.php.
> 0 votes

# Answer
After debugging I found what was the problem for me.

Drupal has some authentication providers. For standard pages this are: basic\_auth and cookie (basic\_auth has higher priority).

Because test site has a basic\_auth from the htaccess, this resulted in that Drupal marked my request as using basic\_auth. Only all pages did not require this. Result was just redirect to the 403 page (access denied in the watchdog table)

My temporary fix was the following: Open the file core/modules/basic\_auth/src/Authentication/Provider/BasicAuth.php

Go to this code:

```
public function applies(Request $request) {
    $username = $request->headers->get('PHP_AUTH_USER');
    $password = $request->headers->get('PHP_AUTH_PW');
    return isset($username) && isset($password);
}

```

Change it to this:

```
public function applies(Request $request) {
    return false;
    //$username = $request->headers->get('PHP_AUTH_USER');
    //$password = $request->headers->get('PHP_AUTH_PW');
    //return isset($username) && isset($password);
}

```

If there is a better solution, let me know. But this makes the site working.
> -4 votes

---
Tags: 8
---


title: Drupal 8 Commerce Module Hook_Theme()

text:
# Question
Title: Drupal 8 Commerce Module Hook_Theme()
I'm working on a custom module that I want to hook into a custom commerce template.

Heres is the code inside of my custom module the returns the variable.

```
 /**
     * Implements hook_theme().
     * @param $existing
     * @param $type
     * @param $theme
     * @param $path
     * @return array
     */
    function my_theme($existing, $type, $theme, $path) {
        return [
              'commerce-product--full' => [
                'variables'=> array (
                    'key'=> "I'm a key.",
                ),
              ],
        ]
}

```

Inside of commerce-product--full, using kint(key), I get null as a response.

Am I missing something?

# Answer
Try implementing `hook_theme_registry_alter()` and see how that goes.

```
function mymodule_theme_registry_alter(&$theme_registry) {
    $theme_registry['commerce_product__full']['path'] = drupal_get_path('module', 'mymodule') . '/templates';
}

```

Your module presumably will have a folder named templates. And inside the folder you have a file called commerce-product--full.html.twig
> 1 votes

# Answer
So I did figure out the answer. It was a combination of turning dashes into underscores and using a preprocess function.

```
/**
     * Implements hook_theme().
     * @param $existing
     * @param $type
     * @param $theme
     * @param $path
     * @return array
     */
    function my_theme($existing, $type, $theme, $path) {
        return [
              'commerce_product__full' => [
                     'preprocess functions' => ['my_preprocess_function'],

              ],
        ]
}

function my_preprocess_function(&$variables) {
    $variables['slogan'] = "I'm a slogan!!";
}

```

Thanks for everyone's help.
> 1 votes

---
Tags: commerce, hooks
---


title: $content array not showing as expected

text:
# Question
Title: $content array not showing as expected
This is a new install of Drupal 7.55, installed via drush.

I have installed the bootstrap theme and have created a subtheme that extends the bootstrap theme.

I have created a new Content Type called **Card** and within Card created a new field called **Grid Width (field\_grid\_width)**.

Within my subtheme I have created a new file node--card.tpl.php which is definitely being used.

When I try to access a field of Card using **$content\['field\_grid\_width'\]** I get an index undefined error.

After seeking some advice it looks as though the $content array is in an unexpected format as I should be able to access the fields of a content type using the $content array.

Here is a print\_r() of $content.

```
        Array
(
[links] => Array
    (
        [#theme] => links__node
        [#pre_render] => Array
            (
                [0] => drupal_pre_render_links
            )

        [#attributes] => Array
            (
                [class] => Array
                    (
                        [0] => links
                        [1] => inline
                    )

            )

        [node] => Array
            (
                [#theme] => links__node__node
                [#links] => Array
                    (
                        [node-readmore] => Array
                            (
                                [title] => Read more about Launching to Mars
                                [href] => node/1
                                [html] => 1
                                [attributes] => Array
                                    (
                                        [rel] => tag
                                        [title] => Launching to Mars
                                    )

                            )

                    )

                [#attributes] => Array
                    (
                        [class] => Array
                            (
                                [0] => links
                                [1] => inline
                            )

                    )

            )

        [comment] => Array
            (
                [#theme] => links__node__comment
                [#links] => Array
                    (
                    )

                [#attributes] => Array
                    (
                        [class] => Array
                            (
                                [0] => links
                                [1] => inline
                            )

                    )

            )

    )

[body] => Array
    (
        [#theme] => field
        [#weight] => 0
        [#title] => Body
        [#access] => 1
        [#label_display] => hidden
        [#view_mode] => teaser
        [#language] => und
        [#field_name] => body
        [#field_type] => text_with_summary
        [#field_translatable] => 0
        [#entity_type] => node
        [#bundle] => card
        [#object] => stdClass Object
            (
                [vid] => 1
                [uid] => 1
                [title] => Launching to Mars
                [log] =>
                [status] => 1
                [comment] => 1
                [promote] => 1
                [sticky] => 0
                [nid] => 1
                [type] => card
                [language] => und
                [created] => 1497537198
                [changed] => 1497538510
                [tnid] => 0
                [translate] => 0
                [revision_timestamp] => 1497538510
                [revision_uid] => 1
                [body] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [value] => Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Cras malesuada porta sem. Donec nec dolor sed leo
tincidunt sodales. Ut quis ornare mauris, eget interdum urna. Sed egestas
libero vel risus aliquam consectetur. Pellentesque mattis sed lorem in
egestas. Nunc vel ornare lorem. Proin finibus tortor tortor, sit amet pharetra
lacus elementum a.
                                        [summary] =>
                                        [format] => filtered_html
                                        [safe_value] =>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada porta
sem. Donec nec dolor sed leo tincidunt sodales. Ut quis ornare mauris, eget
interdum urna. Sed egestas libero vel risus aliquam consectetur. Pellentesque
mattis sed lorem in egestas. Nunc vel ornare lorem. Proin finibus tortor
tortor, sit amet pharetra lacus elementum a.

                                        [safe_summary] =>
                                    )

                            )

                    )

                [field_image] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [fid] => 1
                                        [uid] => 1
                                        [filename] => MARS_Helmets_DL.jpg
                                        [uri] => public://MARS_Helmets_DL.jpg
                                        [filemime] => image/jpeg
                                        [filesize] => 648162
                                        [status] => 1
                                        [timestamp] => 1497537198
                                        [rdf_mapping] => Array
                                            (
                                            )

                                        [alt] =>
                                        [title] =>
                                        [width] => 1920
                                        [height] => 1080
                                    )

                            )

                    )

                [field_grid_width] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [value] => 5
                                    )

                            )

                    )

                [rdf_mapping] => Array
                    (
                        [rdftype] => Array
                            (
                                [0] => sioc:Item
                                [1] => foaf:Document
                            )

                        [title] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => dc:title
                                    )

                            )

                        [created] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => dc:date
                                        [1] => dc:created
                                    )

                                [datatype] => xsd:dateTime
                                [callback] => date_iso8601
                            )

                        [changed] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => dc:modified
                                    )

                                [datatype] => xsd:dateTime
                                [callback] => date_iso8601
                            )

                        [body] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => content:encoded
                                    )

                            )

                        [uid] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => sioc:has_creator
                                    )

                                [type] => rel
                            )

                        [name] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => foaf:name
                                    )

                            )

                        [comment_count] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => sioc:num_replies
                                    )

                                [datatype] => xsd:integer
                            )

                        [last_activity] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => sioc:last_activity_date
                                    )

                                [datatype] => xsd:dateTime
                                [callback] => date_iso8601
                            )

                    )

                [cid] => 0
                [last_comment_timestamp] => 1497537198
                [last_comment_name] =>
                [last_comment_uid] => 1
                [comment_count] => 0
                [name] => Admin
                [picture] => 0
                [data] => b:0;
                [entity_view_prepared] => 1
            )

        [#items] => Array
            (
                [0] => Array
                    (
                        [value] => Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Cras malesuada porta sem. Donec nec dolor sed leo tincidunt
sodales. Ut quis ornare mauris, eget interdum urna. Sed egestas libero vel
risus aliquam consectetur. Pellentesque mattis sed lorem in egestas. Nunc vel
ornare lorem. Proin finibus tortor tortor, sit amet pharetra lacus elementum
a.
                        [summary] =>
                        [format] => filtered_html
                        [safe_value] =>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada porta
sem. Donec nec dolor sed leo tincidunt sodales. Ut quis ornare mauris, eget
interdum urna. Sed egestas libero vel risus aliquam consectetur. Pellentesque
mattis sed lorem in egestas. Nunc vel ornare lorem. Proin finibus tortor
tortor, sit amet pharetra lacus elementum a.

                        [safe_summary] =>
                    )

            )

        [#formatter] => text_summary_or_trimmed
        [0] => Array
            (
                [#markup] =>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada porta
sem. Donec nec dolor sed leo tincidunt sodales. Ut quis ornare mauris, eget
interdum urna. Sed egestas libero vel risus aliquam consectetur. Pellentesque
mattis sed lorem in egestas. Nunc vel ornare lorem. Proin finibus tortor
tortor, sit amet pharetra lacus elementum a.

            )

    )

)

```

I know there is another way I can access the data using the $node array, however from my research on the Drupal website I should be able to access it using the $content?

# Answer
In the display settings of the content type, the field should be set to Display. If it is hidden, it won't be in the render array ($content).
> 0 votes

---
Tags: theming
---


# Question
Title: How do I create a bundle under my custom content entity type in Drupal 8?
I am working on creating a base list entity type I will call CustomList for the sake of this question. I pair it up with CustomListItem so that I have an entity type to define the list and another to define the items in the list.

I intend to create bundles underneath these to build a custom cart, a saved item list, and an item group list.

So far everything I have found in Drupal 8 either creates Node Bundles (which I don't want) or a bundle of config yaml files to define the bundle (in this case ECK did this for me). But nothing useful on how to create a bundle under a specific entity type.

Would I just declare a new entity type and do something in the annotations to make it a bundle? If so I am unsure as to what annotation to use or how to use it.

Thanks, Patrick

# Answer
Yes, you declare a config entity type to store the bundle definitions. For example that for Custom Block Types (bundle of `block_content`):

*Drupal\block\_content\Entity\BlockContentType*

```
namespace Drupal\block_content\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
use Drupal\block_content\BlockContentTypeInterface;

/**
 * Defines the custom block type entity.
 *
 * @ConfigEntityType(
 *   id = "block_content_type",
 *   label = @Translation("Custom block type"),
 *   handlers = {
 *     "form" = {
 *       "default" = "Drupal\block_content\BlockContentTypeForm",
 *       "add" = "Drupal\block_content\BlockContentTypeForm",
 *       "edit" = "Drupal\block_content\BlockContentTypeForm",
 *       "delete" = "Drupal\block_content\Form\BlockContentTypeDeleteForm"
 *     },
 *     "list_builder" = "Drupal\block_content\BlockContentTypeListBuilder"
 *   },
 *   admin_permission = "administer blocks",
 *   config_prefix = "type",
 *   bundle_of = "block_content",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   links = {
 *     "delete-form" = "/admin/structure/block/block-content/manage/{block_content_type}/delete",
 *     "edit-form" = "/admin/structure/block/block-content/manage/{block_content_type}",
 *     "collection" = "/admin/structure/block/block-content/types",
 *   },
 *     ...
 * )
 */
class BlockContentType extends ConfigEntityBundleBase implements BlockContentTypeInterface {

```

Which is then referenced in the content entity type:

*Drupal\block\_content\Entity\BlockContent*

```
*   bundle_entity_type = "block_content_type",

```

If you use Drupal Console to generate a custom content entity type and you say yes to the question if you want bundles, this config entity type is set up for you automatically.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Drupal 7, language changes back to EN after clicking on any link
I have 8 languages on my website. When I visit the website with different language prefix such as mysite.com/da and scroll down to click on any link. The language prefix changes to EN in URL. For example mysite.com/en/about

Can anyone please help me on it?

Thanks Saeed Afzal

# Answer
in configuration, admin/config/regional/language/configure, modify language detection, the order there determinies wich language to use, it depends on how your languages are set, try moving on first place what you think how is confugured your site, set defalut value last. here are my settings on one site, your may be different.
> 1 votes

# Answer
**I found solution of this problem:**

Although I already have the same set of necessary configurations for multilingual modules. But actually, I was using "**base\_path()**" in template files to create paths. So when the user changes the languages and scrolls down to the website to click any link. The language prefix was changing back to EN automatically.

**Here is solution I implemented:**

I simply created my own method in "template.php" file which returns the current language prefix such as "en, da or fr" etc.

```
function <your_theme_name>_get_lang_prefix(){
  global $language;
  $prefix =  $language->prefix . '/';
  return $prefix;
}

```

Finally, I modified the path in template **from**

```
<?php echo base_path(); ?>

```

**to**

```
<?php echo base_path() . <your_theme_name>_get_lang_prefix(); ?>

```

Now I can browse the website in all language prefix with content translation and etc.

Seem working perfectly.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: D7 - field_update_instance requiring manual refresh after node save to view new values
I'm using preprocess\_entity to alter an image's style display setting based on number of entity references within a paragraphs bundle. The display setting value is correctly altered on node save, but the updated image style won't display without an additional browser refresh.

```
function THEME_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if ($variables['elements']['#bundle'] == 'promotions') {
      $promo = $variables['field_promotions'];
      $promo_count = count($variables['field_promotions']);
      $promo_img_styles = array(
        1 => 'promotion_1x',
        2 => 'promotion_2x',
        3 => 'promotion_3x',
        5 => 'promotion_5x'
      );
      $promo_img_style = str_replace(array_keys($promo_img_styles), $promo_img_styles, $promo_count);
      $promo_fields = field_info_instance('node', 'field_promotion_image', 'promotion');
      $promo_fields['display']['full']['settings']['image_style'] = $promo_img_style;
      field_update_instance($promo_fields);
    }
  }
}

```

Any ideas why field\_instance\_update is requiring the additional refresh?

# Answer
> 0 votes
the theme function occurs towards the end of the page request lifecyle in the theme layer of a drupal request.

Whereas, the field\_update\_instance call is updating the database values for this Node's promotion image. The node is already loaded and being used as variables within in the theme at this time. When you refresh the page you're requesting the Node from the database again -- which is "refreshing" the data.

---
Tags: 7, entities
---


# Question
Title: How to assign alt text to current inline images
Let me set the scope first, these images are **not** uploaded from an image field, they are uploaded from CKeditor, via imce or ckeditor\_image2. Therefore, they are in node body, together with other text (isn't that the worst scenario you can imagine?). Now how do I approach this accessibility improvement after already having hundreds of potential images without alt text.

# Answer
> 0 votes
You can use my module Image auto ALT Filter in this case https://www.drupal.org/project/image\_auto\_alt\_filter Only enable this filter for your text format, and all images will be with ALT tags. ALT generates from text keywords (I'm going to add some features in next release)

---
Tags: 7, files
---


# Question
Title: Override function image_style_path doesn't work?
I work with the S3FS module on Drupal 7.

In this module the function **\_s3fs\_image\_style\_deliver** of file **s3fs.module** call the function **image\_style\_path** in that line :

```
$derivative_uri = image_style_path($style['name'], $image_uri);

```

This function comes from drupal core module image.

I need a way to override this function or the function **\_s3fs\_image\_style\_deliver** from s3fs module. If someone have an idea ?

Thx :)

# Answer
> 0 votes
**I find a way to modify/rewrite the url for each files image style with s3fs module for amazon S3. It's not really easy to explain, but it work, so i try :**

**In module s3fs :**

Edit file S3fsStreamWrapper.inc line 310 in function getExternalUrl line 331 replace :

```
if ($path_parts[0] == 'styles' && substr($s3_key, -4) != '.css') {

```

by : `if (substr($s3_key, -4) != '.css') {`

This will stop checking whether the first path element is the 'styles' folder.

Line 337 replace:

array\_unshift($path\_parts, 's3','files');

by : `array_unshift($path_parts, 't','f','s');`

The listening url for creating the derivatives image will be changed from s3/files/ to t/f/s in part to not signal at any time that we are working with an S3. But it's url is not show to normaly user. We can not delete these folders because Drupal expects in 4th position the name of the style like s3/files/style /your-style-name we will see later why I added a folder "s".

Edit file s3fs.module : line 116 replace :

```
$items['s3/files/styles/%image_style'] = array(

```

by : `$items['t/f/s/%image_style'] = array(`

We changed the listening url in the S3fsStreamWrapper.inc file so we need to modify the listener.

In function \_s3fs\_image\_style\_deliver : Line 206 replace :

```
$scheme = array_shift($args);

```

par : `$scheme ='s3';`

In the previous modification we no longer send information on the scheme. That is read normally through the s3/files url which is now t/f/s. So here we have to say manually what is the scheme.

Line 210 replace :

```
if (!variable_get('image_allow_insecure_derivatives', FALSE) || strpos(ltrim($filename, '\/'), 'styles/') === 0) {

```

by : `if (!variable_get('image_allow_insecure_derivatives', FALSE) ) {`

Another line that check that in first position we have style but we change it afterwards so we change that.

**Edit directly Core module image** in module/image/image.module. Rewrite function image\_style\_path line 1096 :

```
function image_style_path($style_name, $uri) {
  $scheme = file_uri_scheme($uri);
  if ($scheme) {
    $path = file_uri_target($uri);
  }
  else {
    $path = $uri;
    $scheme = file_default_scheme();
  }
  $tabpath=explode('/', $path);
  $namefile = array_pop ($tabpath); //array_pop delete the last element of array $tabpath and put is value to $namefile
  $path=implode('/', $tabpath);

  $total= $scheme . '://' . $style_name . '/' . $path . '/' . $namefile;
  return $total;
}

```

The new variable $total allows to rewrite the address of the image by keeping the name of the style first so that the drupal core recognizes it. This is the final address. I did not want it to be like /styles/your-name-style/path but directly /your-name-style/path. As a result, this requires the previous changes in the derivatives creation url so that the style name is in the same location.

Save the files and create the new images for each style: Empty the Drupal cache with command : drush cc all

**And flush the old file to create the news :**

Execute this dursh function and when it ask choose all : drush image-flush

I hope it help someone !

---
Tags: hooks, media
---


# Question
Title: how to make checkbox checked by default in add content type form
Hi i had created 1 content type. In this content type I have created a field called courses of type field collections. In the field collections I have added 1 fields of type checkbox which I want to be enabled by default. there is option to do by configuration. But I want to do it by coding . How to do?

# Answer
> 0 votes
You can this using Drupal's Form API. You'll have to alter the form and set the value.

```
function modulename_form_alter(&$form, &$form_state, $form_id){

switch($form_id){
        case "your_form":

           $form['cbs'] = array(
           '#type' => 'checkboxes',
           '#options' => array(1 => "One", 2 => "Two", 3 => "Three"),
           '#default_value' => array(1, 3),
           );

        break;
        }
}

```

**To know more about altering form check the below links:**

1. http://befused.com/drupal/form-alter
2. http://themery.com/dgd7/advanced-theming/forms/with-alter-hooks

**UPDATE:**

If field collections try using widget\_form\_alter:

```
function my_module_field_widget_form_alter(&$element, &$form_state, $context) {

 if ("field_my_field_collection" == $element['#bundle']) {

    if ("field_my_field_collection" == $element['#field_name']) {

         //do your work here
    }
  }
}

```

**There are two related questions in the following links, which may help you:**

1. Question One.
2. Question Two.

# Answer
> 0 votes
```
if($form_id == 'course_page_node_form') {
$form['field_course_tabs'][LANGUAGE_NONE][0]['field_enable_in_tab'][LANGUAGE_NONE]['#default_value'] = 1;

```

} this one worked for me.

---
Tags: 7, nodes
---