# Question
Title: How to implement the mass operations on the Group's members page using Views?
I use the Group module and I want to customize the page to manage the members of the group, created by the module.

So I created a view by following the instructions below :

How to add a column to the list of group members or create a Views equivalent of it?

How do I do the mass operations of the members page of the module (screenshot 1) on the members page of my view (screenshot 2) ?

Here is the export of my view, to manage the members of the groups :

```
$view = new view();
$view->name = 'group_members';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'group_membership';
$view->human_name = 'Membres';
$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'] = 'Membres';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  3 => '3',
  9 => '9',
);
$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['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
/* Relation: Adhésion au groupe : Groupe gid */
$handler->display->display_options['relationships']['group']['id'] = 'group';
$handler->display->display_options['relationships']['group']['table'] = 'group_membership';
$handler->display->display_options['relationships']['group']['field'] = 'group';
/* Relation: Adhésion au groupe : Utilisateur uid */
$handler->display->display_options['relationships']['user']['id'] = 'user';
$handler->display->display_options['relationships']['user']['table'] = 'group_membership';
$handler->display->display_options['relationships']['user']['field'] = 'user';
/* Champ: Groupe : ID du groupe */
$handler->display->display_options['fields']['gid']['id'] = 'gid';
$handler->display->display_options['fields']['gid']['table'] = 'groups';
$handler->display->display_options['fields']['gid']['field'] = 'gid';
$handler->display->display_options['fields']['gid']['relationship'] = 'group';
$handler->display->display_options['fields']['gid']['exclude'] = TRUE;
/* Champ: Utilisateur : Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'user';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Champ: Groupe : Titre */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'groups';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'group';
/* Champ: Utilisateur : Nom */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'user';
$handler->display->display_options['fields']['name']['label'] = 'Nom d\'utilisateur';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_3']['id'] = 'nothing_3';
$handler->display->display_options['fields']['nothing_3']['table'] = 'views';
$handler->display->display_options['fields']['nothing_3']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_3']['label'] = 'Nom d\'utilisateur';
$handler->display->display_options['fields']['nothing_3']['alter']['text'] = '[name]';
$handler->display->display_options['fields']['nothing_3']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_3']['alter']['path'] = 'group/[gid]/member/[uid]';
/* Champ: Utilisateur : Courriel */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'user';
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Champ: Adhésion au groupe : Statut de membre */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'group_membership';
$handler->display->display_options['fields']['status']['field'] = 'status';
$handler->display->display_options['fields']['status']['label'] = 'Statut';
/* Champ: Adhésion au groupe : Group role */
$handler->display->display_options['fields']['role']['id'] = 'role';
$handler->display->display_options['fields']['role']['table'] = 'group_membership';
$handler->display->display_options['fields']['role']['field'] = 'role';
$handler->display->display_options['fields']['role']['label'] = 'Rôles';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = 'Modifier';
$handler->display->display_options['fields']['nothing']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'modifier';
$handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['path'] = 'group/[gid]/member/[uid]/edit?destination=group/[gid]/member';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_1']['id'] = 'nothing_1';
$handler->display->display_options['fields']['nothing_1']['table'] = 'views';
$handler->display->display_options['fields']['nothing_1']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_1']['label'] = 'Annuler';
$handler->display->display_options['fields']['nothing_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['text'] = 'annuler';
$handler->display->display_options['fields']['nothing_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['path'] = 'group/[gid]/member/[uid]/cancel?destination=group/[gid]/member';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_2']['id'] = 'nothing_2';
$handler->display->display_options['fields']['nothing_2']['table'] = 'views';
$handler->display->display_options['fields']['nothing_2']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_2']['label'] = 'Metadata';
$handler->display->display_options['fields']['nothing_2']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['text'] = 'metadata';
$handler->display->display_options['fields']['nothing_2']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['path'] = 'group/[gid]/member/[uid]/metadata';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_4']['id'] = 'nothing_4';
$handler->display->display_options['fields']['nothing_4']['table'] = 'views';
$handler->display->display_options['fields']['nothing_4']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_4']['label'] = 'Actions';
$handler->display->display_options['fields']['nothing_4']['alter']['text'] = '[nothing]   [nothing_1]   [nothing_2]';
/* Critère de filtrage: Adhésion au groupe : Statut de membre */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'group_membership';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['exposed'] = TRUE;
$handler->display->display_options['filters']['status']['expose']['operator_id'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['label'] = 'Membership status';
$handler->display->display_options['filters']['status']['expose']['operator'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['identifier'] = 'status';
$handler->display->display_options['filters']['status']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'group/%/member';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Membres';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['weight'] = '0';
$translatables['group_members'] = array(
  t('Master'),
  t('Membres'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Groupe'),
  t('Utilisateur'),
  t('ID du groupe'),
  t('.'),
  t(','),
  t('Uid'),
  t('Titre'),
  t('Nom d\'utilisateur'),
  t('[name]'),
  t('Courriel'),
  t('Statut'),
  t('Rôles'),
  t('Modifier'),
  t('modifier'),
  t('Annuler'),
  t('annuler'),
  t('Metadata'),
  t('metadata'),
  t('Actions'),
  t('[nothing]   [nothing_1]   [nothing_2]'),
  t('Membership status'),
  t('Page'),
);

```

**Update**:

I imported the Rules Component as included in revision 1 of Pierre's answer and I created a field "Mass Operations: Group Membership (Group Membership)". But I can not find that Rules Component in the view.

```
$view = new view();
$view->name = 'group_members';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'group_membership';
$view->human_name = 'Membres';
$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'] = 'Membres';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  3 => '3',
  9 => '9',
);
$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['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
/* Relation: Adhésion au groupe : Groupe gid */
$handler->display->display_options['relationships']['group']['id'] = 'group';
$handler->display->display_options['relationships']['group']['table'] = 'group_membership';
$handler->display->display_options['relationships']['group']['field'] = 'group';
/* Relation: Adhésion au groupe : Utilisateur uid */
$handler->display->display_options['relationships']['user']['id'] = 'user';
$handler->display->display_options['relationships']['user']['table'] = 'group_membership';
$handler->display->display_options['relationships']['user']['field'] = 'user';
/* Champ: Opérations en masse : Adhésion au groupe */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'group_membership';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Champ: Groupe : ID du groupe */
$handler->display->display_options['fields']['gid']['id'] = 'gid';
$handler->display->display_options['fields']['gid']['table'] = 'groups';
$handler->display->display_options['fields']['gid']['field'] = 'gid';
$handler->display->display_options['fields']['gid']['relationship'] = 'group';
$handler->display->display_options['fields']['gid']['exclude'] = TRUE;
/* Champ: Utilisateur : Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'user';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Champ: Groupe : Titre */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'groups';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'group';
/* Champ: Utilisateur : Nom */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'user';
$handler->display->display_options['fields']['name']['label'] = 'Nom d\'utilisateur';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_3']['id'] = 'nothing_3';
$handler->display->display_options['fields']['nothing_3']['table'] = 'views';
$handler->display->display_options['fields']['nothing_3']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_3']['label'] = 'Nom d\'utilisateur';
$handler->display->display_options['fields']['nothing_3']['alter']['text'] = '[name]';
$handler->display->display_options['fields']['nothing_3']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_3']['alter']['path'] = 'group/[gid]/member/[uid]';
/* Champ: Utilisateur : Courriel */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'user';
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Champ: Adhésion au groupe : Statut de membre */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'group_membership';
$handler->display->display_options['fields']['status']['field'] = 'status';
$handler->display->display_options['fields']['status']['label'] = 'Statut';
/* Champ: Adhésion au groupe : Group role */
$handler->display->display_options['fields']['role']['id'] = 'role';
$handler->display->display_options['fields']['role']['table'] = 'group_membership';
$handler->display->display_options['fields']['role']['field'] = 'role';
$handler->display->display_options['fields']['role']['label'] = 'Rôles';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = 'Modifier';
$handler->display->display_options['fields']['nothing']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'modifier';
$handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['path'] = 'group/[gid]/member/[uid]/edit?destination=group/[gid]/member';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_1']['id'] = 'nothing_1';
$handler->display->display_options['fields']['nothing_1']['table'] = 'views';
$handler->display->display_options['fields']['nothing_1']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_1']['label'] = 'Annuler';
$handler->display->display_options['fields']['nothing_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['text'] = 'annuler';
$handler->display->display_options['fields']['nothing_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['path'] = 'group/[gid]/member/[uid]/cancel?destination=group/[gid]/member';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_2']['id'] = 'nothing_2';
$handler->display->display_options['fields']['nothing_2']['table'] = 'views';
$handler->display->display_options['fields']['nothing_2']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_2']['label'] = 'Metadata';
$handler->display->display_options['fields']['nothing_2']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['text'] = 'metadata';
$handler->display->display_options['fields']['nothing_2']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['path'] = 'group/[gid]/member/[uid]/metadata';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_4']['id'] = 'nothing_4';
$handler->display->display_options['fields']['nothing_4']['table'] = 'views';
$handler->display->display_options['fields']['nothing_4']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_4']['label'] = 'Actions';
$handler->display->display_options['fields']['nothing_4']['alter']['text'] = '[nothing]   [nothing_1]   [nothing_2]';
/* Critère de filtrage: Adhésion au groupe : Statut de membre */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'group_membership';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['exposed'] = TRUE;
$handler->display->display_options['filters']['status']['expose']['operator_id'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['label'] = 'Membership status';
$handler->display->display_options['filters']['status']['expose']['operator'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['identifier'] = 'status';
$handler->display->display_options['filters']['status']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'group/%/member';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Membres';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['weight'] = '0';
$translatables['group_members'] = array(
  t('Master'),
  t('Membres'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Groupe'),
  t('Utilisateur'),
  t('Adhésion au groupe'),
  t('- Choisir une opération -'),
  t('ID du groupe'),
  t('.'),
  t(','),
  t('Uid'),
  t('Titre'),
  t('Nom d\'utilisateur'),
  t('[name]'),
  t('Courriel'),
  t('Statut'),
  t('Rôles'),
  t('Modifier'),
  t('modifier'),
  t('Annuler'),
  t('annuler'),
  t('Metadata'),
  t('metadata'),
  t('Actions'),
  t('[nothing]   [nothing_1]   [nothing_2]'),
  t('Membership status'),
  t('Page'),
);

```

# Answer
You need to transform the view you already have into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?".

In doing so, you'll then be able to use Rules Components (using the Rules module), in which you can then include the required logic to perform the equivalent of each of the mass operations of the Group members page.

Below is an example to explain the key concept of the solution. It includes everything (= 2 Rules Components + a VBO views) you need to implement the equivalent of these openrations that are available on `group/gid/member`:

* Block selected members.
* Unblock selected members.

### Part 1 - Rules Component to Block selected members

Here is the rule (in Rules export format which you can import if you have the Rules UI enabled), which you can use in your VBO enabled view to perform the equivalent of "Block selected members"):

```
{ "rules_block_a_group_membership" : {
    "LABEL" : "Block a group membership",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "IF" : [
      { "NOT data_is" : { "data" : [ "group-mbrship:status" ], "value" : "blocked" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "group-mbrship:status" ], "value" : "blocked" } },
      { "drupal_message" : { "message" : "Membership status for group \u0022[group-mbrship:group]\u0022 updated to BLOCKED for user \u0022[group-mbrship:user]\u0022." } }
    ]
  }
}

```

### Part 2 - Rules Component to Unblock selected members

Here is the rule (in Rules export format which you can import if you have the Rules UI enabled), which you can use in your VBO enabled view to perform the equivalent of "Unblock selected members"):

```
{ "rules_unblock_a_group_membership" : {
    "LABEL" : "Unblock a group membership",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "IF" : [
      { "NOT data_is" : { "data" : [ "group-mbrship:status" ], "value" : "active" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "group-mbrship:status" ], "value" : "active" } },
      { "drupal_message" : { "message" : "Membership status for group \u0022[group-mbrship:group]\u0022 changed to ACTIVE for user \u0022[group-mbrship:user]]\u0022." } }
    ]
  }
}

```

### Part 3 - VBO view that uses both Rules Components

Here is the VBO view (in Views export format) that refers (uses) the 2 Rules Components from above:

```
$view = new view();
$view->name = 'group_members';
$view->description = 'List of all members in a specific Group';
$view->tag = 'default';
$view->base_table = 'group_membership';
$view->human_name = 'Group Members';
$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'] = 'Membres';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  3 => '3',
);
$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['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Group membership: Group gid */
$handler->display->display_options['relationships']['group']['id'] = 'group';
$handler->display->display_options['relationships']['group']['table'] = 'group_membership';
$handler->display->display_options['relationships']['group']['field'] = 'group';
/* Relationship: Group membership: User uid */
$handler->display->display_options['relationships']['user']['id'] = 'user';
$handler->display->display_options['relationships']['user']['table'] = 'group_membership';
$handler->display->display_options['relationships']['user']['field'] = 'user';
/* Field: Bulk operations: Group membership */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'group_membership';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'rules_component::rules_block_a_group_membership' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'rules_component::rules_unblock_a_group_membership' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Field: Group: Group ID */
$handler->display->display_options['fields']['gid']['id'] = 'gid';
$handler->display->display_options['fields']['gid']['table'] = 'groups';
$handler->display->display_options['fields']['gid']['field'] = 'gid';
$handler->display->display_options['fields']['gid']['relationship'] = 'group';
$handler->display->display_options['fields']['gid']['exclude'] = TRUE;
/* Field: User: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'user';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Field: Group: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'groups';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'group';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'user';
$handler->display->display_options['fields']['name']['label'] = 'Nom d\'utilisateur';
/* Field: User: E-mail */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'user';
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Field: Group membership: Membership status */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'group_membership';
$handler->display->display_options['fields']['status']['field'] = 'status';
/* Field: Group membership: Group role */
$handler->display->display_options['fields']['role']['id'] = 'role';
$handler->display->display_options['fields']['role']['table'] = 'group_membership';
$handler->display->display_options['fields']['role']['field'] = 'role';
$handler->display->display_options['fields']['role']['label'] = 'Rôles';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing_3']['id'] = 'nothing_3';
$handler->display->display_options['fields']['nothing_3']['table'] = 'views';
$handler->display->display_options['fields']['nothing_3']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_3']['label'] = 'View';
$handler->display->display_options['fields']['nothing_3']['alter']['text'] = 'view';
$handler->display->display_options['fields']['nothing_3']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_3']['alter']['path'] = 'group/[gid]/member/[uid]';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = 'Modifier';
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'modifier';
$handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['path'] = 'group/[gid]/member/[uid]/edit?destination=group/[gid]/member';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing_1']['id'] = 'nothing_1';
$handler->display->display_options['fields']['nothing_1']['table'] = 'views';
$handler->display->display_options['fields']['nothing_1']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_1']['label'] = 'Annuler';
$handler->display->display_options['fields']['nothing_1']['alter']['text'] = 'annuler';
$handler->display->display_options['fields']['nothing_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['path'] = 'group/[gid]/member/[uid]/cancel?destination=group/[gid]/member';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing_2']['id'] = 'nothing_2';
$handler->display->display_options['fields']['nothing_2']['table'] = 'views';
$handler->display->display_options['fields']['nothing_2']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_2']['label'] = 'Metadata';
$handler->display->display_options['fields']['nothing_2']['alter']['text'] = 'metadata';
$handler->display->display_options['fields']['nothing_2']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['path'] = 'group/[gid]/member/[uid]/metadata';
/* Contextual filter: Group: Group ID */
$handler->display->display_options['arguments']['gid']['id'] = 'gid';
$handler->display->display_options['arguments']['gid']['table'] = 'groups';
$handler->display->display_options['arguments']['gid']['field'] = 'gid';
$handler->display->display_options['arguments']['gid']['relationship'] = 'group';
$handler->display->display_options['arguments']['gid']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['gid']['title'] = 'Members of the group with Group Id = %1';
$handler->display->display_options['arguments']['gid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['gid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['gid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['gid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['gid']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['gid']['validate']['type'] = 'numeric';
/* Filter criterion: Group membership: Membership status */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'group_membership';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['exposed'] = TRUE;
$handler->display->display_options['filters']['status']['expose']['operator_id'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['label'] = 'Membership status';
$handler->display->display_options['filters']['status']['expose']['operator'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['identifier'] = 'status';
$handler->display->display_options['filters']['status']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);

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

```

### Bonus feature

Since using `all` in the path `group/all/memberlist` is also supported in this VBO view, with this solution you can block/unblock memberships in a single mass operation for multiple groups at once (which you cannot do with what's delivered with the Group module ...).

### Not all Rules Components can be selected

Even though you may think "hm, is it really that easy?", it happens that after you created a Rules Component and try to use it in a VBO view, that Rules Component cannot be selected as an operation to be enabled in your VBO view.

As an example, here is a variation of the above rules (in Rules export format which you can import if you have the Rules UI enabled), which also performs the equivalent of "Block a member"):

```
{ "rules_group_membership_block_a_member" : {
    "LABEL" : "Group membership - block a member",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group_user" : { "label" : "Group User", "type" : "user" },
      "group_mbrship" : { "label" : "Group mbrship", "type" : "group_membership" }
    },
    "DO" : [
      { "data_set" : { "data" : [ "group-mbrship:status" ], "value" : "blocked" } },
      { "drupal_message" : { "message" : "Membership status for group \u0022[group-mbrship:group]\u0022 changed to BLOCKED for user \u0022[group-user:name]\u0022." } }
    ]
  }
}

```

However you won't be able to select this Rules Component ... If you wonder why, or wonder what it would take to make it show up anyway (in the VBO view), then use this link ...
> 1 votes

---
Tags: 7, rules, views, group
---


title: Disabling view blocks cache

text:
# Question
Title: Disabling view blocks cache
I have added a views block through my twig template file (`page.html.twig`) through Twig\_tweaks. It looks like this `{{ drupal_view('view_name', 'block_name') }}`.

I would like to disable caching for that particular block, but changes to the `preprocess_views_view`, seem to have no effect. Any suggestions to disable caching for just this one views block?

Any help very much appreciated.

# Answer
> 2 votes
You can use

```
function hook_block_view_BASE_BLOCK_ID_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  //Change the title of the specific block.
  $build['#cache']['max-age'] = 0;
}

```

Also note that this does not disable the page cache for anonymous users. If you need that too, then you also need:

> \Drupal::service('page\_cache\_kill\_switch')-\>trigger();

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


# Question
Title: How can I check the changes for the fields at form alter submit?
I am using hook\_form\_alter() with custom submit handler (). At submit I want to check if there is any change in the content except node-\>expire then my custom code will run.

but at $form\_state\['value'\] I am also getting: nid, vid, uid, created changed etc. and I have field type as ***taxonomy term reference*** and ***media files***.

I do not want to hard-code the fields name as admin may add new fields later on.

# Answer
> 0 votes
Try comparing both `$form_state[input]` and `$form_state['values']` .

After that check both values using the key's in foreach loop and compare both values, if changed then do your things there.

---
Tags: nodes, forms
---


# Question
Title: Creating media_bundle entities programatically
I am still trying to wrap my head around some of the D8 things. Working with some media bundles like media\_audio\_bundle and need to write some migration scripts. I have spent couple of days now researching and trying everything but nothing seems to work.

Its like Drupal wall all over again.

This is the closest I came:

```
$audio = \Drupal::entityTypeManager()
          ->getStorage('media_bundle')
          ->create(array(
            'type' => 'media',
            'bundle' => 'audio',
            'title' => 'Another Audio',
            'field_audio_file' => 11
          ));

```

It seems to create some sort of media object but does not save it.

If somebody can help, would be much appreciated.

# Answer
> 2 votes
```
use Drupal\media_entity\Entity\Media;

$image_data = file_get_contents("URL OF FILE");
$file_image = file_save_data($image_data, 'public://FILENAME', FILE_EXISTS_REPLACE);
$media_image = Media::create([
  'bundle' => 'image',(YOUR BUNDLE)
  'name' => "FILENAME",
  'field_image' => [
    'target_id' => $file_image->id(),
  ],
]);
$media_image->save();

```

Try this one, maybe this will help.

# Answer
> 0 votes
> You should invoke save method to save the entity to database.

```
$audio->save();

```

# Answer
> 0 votes
Not sure if this is the best way, but it seems to work.

```
$media =  Drupal\media_entity\Entity\Media::create([
 'bundle'        => 'audio',
 'name'       => 'demo audio',
 'field_audio' => [
   [
      'target_id' => $file->id(),
   ]
 ],
]);
$media->save();

```

---
Tags: 8, entities, media
---


# Question
Title: How to show/render 'Add to Cart' button?
I have a Commerce Kickstart 2 site. I know how to create products and variations. I used the Omega Kick Start theme and have implemented my own template files for the entire site. Now I need to theme the shopping basket, starting with the "Add To Cart" button. For the life of me - cannot get it right.

I've already tried the advice from this question \- but no luck. For the record, my reference field is setup to render / display as Add to Cart form:

The Shopping cart block from Kickstart is enabled and set to my Content region:

The template file to render my product starts off like this:

```
<?php
$nodew = entity_metadata_wrapper('node', $node);

/* Manually extract the product ID to get a new wrapper */
$product_id = field_get_items('node', $node, 'field_product')[0]['product_id'];
$productw = entity_metadata_wrapper('commerce_product', $product_id);
?>

<section class="home-hero about-course">
  <div class="blurb content">
    <h1><?php echo $nodew->title_field->value(); ?></h1>
    <p><?php echo $nodew->body->value(); ?> </p>
  </div>
</section>

<div class="list-wrapper">
  <div class="left">
    <?php } $duration=$ nodew->field_duration->value(); if (!empty($duration)) { ?>
    <p> Duration -
      <?php echo $duration; ?>
    </p>
    <?php } $assignments=$ nodew->field_assessments->value(); if (!empty($assignments)) { ?>
    <p> No of assignments -
      <?php echo $assignments; ?>
    </p>
    <?php } ?>
  </div>
</div>

```

What I would like to do is add/show the default, standard Commerce Kickstart "Add To Cart" button below all these attribute fields, and then hopefully I can use the standard commerce kick start shopping basket system (allowing me to just theme the relevant pages).

Just a side note - if I change the theme back to the Omega Kickstart 7.x-3.4 theme - my products show, and obviously the Add To Cart button as well, so I am fairly sure I did not break anything (uninstalled a module that was needed, or something like that).

# Answer
> 1 votes
There are a couple of things I would try to see what is going on.In the post that you referenced, they said the following code. `render($content['field_product'])`.

Have you tried just rendering the whole content using the following `render($content)`, which for you I think would be `render($productw)`. This should render the whole product including the add to cart button. I am guessing that if it doesn't show up then, then there is something wrong with how you are getting the content and field\_product isn't even available to render.

Also, which display are you affecting when you change your product reference to Add to Cart form? Your default or your teaser? Are you modifying the right template?

# Answer
> 0 votes
I just noticed you are getting the actual `commerce_product`. The `field_product` with the variations that renders the Add to Cart form exists on the product content type (or however you have set up to display the product) You need to render that, not the commerce\_product.

# Answer
> 0 votes
I found a solution to my problem. I created a custom form (Form API), and on the submit hook, I add the line item to a new commerce order myself.

Here is the code to the custom module (custom form and block):

```
<?php
function addtocart_block_info() {
  $blocks = array();

  // Create a key in our $blocks array that defines our block.
  $blocks['addtocart_form'] = array(
  // 'info' is what you will see when viewing the blocks admin page.
  'info' => t('Add-To-Cart-Form'),
  // 'cache' how this block will be cached
  'cache' => DRUPAL_CACHE_GLOBAL,
  );

  return $blocks;
}

function addticart_block_view($delta = '') {
  $block = array();

  switch($delta) {
    case 'addtocart_form':
      $block['subject'] = t('Take This Course');
      // 'content' are just that, the contents of the block. In our case, we
      // will be showing a form. We use drupal_get_form() to return a
      // drupal-built form.
      // Note that the parameter passed to drupal_get_form is the name
      // of the function we will build below to define our form.
      $block['content'] = drupal_get_form('addtocart_form');
    default:
      // Do Nothing
    break;
  }
  return $block;
}

function addtocart_form($form, &$form_state, $product_id) {
  $node = node_load ($product_id);
  $nodew = entity_metadata_wrapper('node', $node);

  $Options = array ();
  // Step through variations for this product to build a drop-down
  foreach($nodew->field_product->value() as $Variation) {
    $Options [$Variation->product_id] = $Variation->title;
  }
  $form['product_id'] = array(
   '#type' => 'select',
   '#options' => $Options
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#default_value' => 'all',
    '#value' => t('Add To Cart'),
  );
  return $form;
}

function addtocart_form_validate($form, &$form_state) {
  // We have a drop-down, nothing to validate (for now)
}

function addtocart_form_submit($form, &$form_state) {
  // Get the values and assign to variables for easy access.

  global $user;
  $Order = null;
  $product_id = $form_state['values']['product_id'];

  // Load the current cart for the current user.  If there is no cart, then add
  // (create) a new order
  if (commerce_cart_is_cart_empty()){
    $Order = commerce_order_new($user->uid, 'checkout_checkout');
    commerce_order_save($Order);
  }
  else{
    $Order = commerce_cart_order_load($user->uid);
    // This is an existing order, so there is probably existing item in the
    // cart.  We only purcahse one item at a time, so we delete
    // any existing items first.
    $line_items = $Order->commerce_line_items['und'];
    foreach ($line_items as $lid) {
      commerce_line_item_delete ($lid['line_item_id']);
    }
  }

  // Load whatever product represents the item the customer will be
  // paying for and create a line item for it.
  $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, 1, $Order->order_id);

  // Save the line item to get its ID.
  commerce_line_item_save($line_item);

  // Add the line item to the order using a wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $Order);
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save the order again to update its line item reference field.
  commerce_order_save($Order);
}

function commerce_cart_is_cart_empty() {
  global $user;

  if ($order = commerce_cart_order_load($user->uid)) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);

    // If there are one or more products in the cart...
    if (commerce_line_items_quantity($wrapper->commerce_line_items,
      ommerce_product_line_item_types()) > 0) {
      return FALSE;
    }
  }

  return TRUE;
}

```

In the template file where I want this form to be displayed, all I have to do is:

```
<?php print drupal_render (drupal_get_form('addtocart_form', $node->nid)) ?>

```

Remember to enable this "Add To Cart" module (you will have to create a custom module - beyond this response).

Hope this saves someone the 2 days I spent trying to modify the existing "Add To Cart" form in Commerce Kickstart.

# Answer
> 0 votes
```
function MY_MODULE_add_to_cart_form($form, &$form_state, $product) {
    $id = drupal_html_id('product-add-to-cart');
    $form['#prefix'] = '<div id="' . $id . '" class="add-to-cart-wrapper">';
    $form['#suffix'] = '</div>';
    $form['#product'] = $product;

    $form['qty'] = array(
        '#type' => 'textfield',
        '#default_value' => 1,
        '#size' => 3
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Add to cart'),
        '#ajax' => array(
            'callback' => 'MY_MODULE_add_to_cart_form_ajax_callback',
            'wrapper' => $id,
        )
    );

    return $form;
}

function MY_MODULE_add_to_cart_form_submit($form, &$form_state) {
    $product = $form['#product'];
    if (is_numeric($form_state['values']['qty']) && $form_state['values']['qty'] >= 1) {
        commerce_cart_product_add_by_id($product->product_id, $form_state['values']['qty'], TRUE);
    }
}

function MY_MODULE_add_to_cart_form_ajax_callback($form, $form_state) {
    $element = $form;
    $element['qty']['#value'] = '1';
    return $element;
}

```

And now you render function:

```
drupal_get_form('MY_MODULE_add_to_cart_form', $product)

```

in your block, custom field etc...

---
Tags: theming, commerce
---


# Question
Title: Only show block if View or nid has certain term referenced to it
I have a tricky one here and looking for some suggestions.

I have a Page view which uses a contextual filter on the nid (which is in the URL).

These nodes have a term reference field which contain various terms.

I have a block which I only want to be displayed on this page if the node has this specific term referenced to it. Bare-in-mind this is not the actual node page, this a dynamically created page/view based on the nid in the url.

# Answer
> 1 votes
Did you try php code? If you enable 'PHP filter' module, you can add php code under 'Pages restricted to certain pages' option in block configuration and write your code like

```
<?php
$relative_path = request_uri();
if (some condition)   {

    return TRUE;
   }

 else
    return FALSE;

?>

```

# Answer
> 1 votes
Please try below steps,

1. Crearte a hook for the block display alter, hook\_block\_view\_MODULE\_DELTA\_alter() // To alter specific block
2. Inside the hook, render the view using below code, $my\_view = views\_get\_view($my\_view\_name); // To get related Taxonomy term for the node
3. Check if the Taxonomy term exists.
4. Manage display/hide for the block.

---
Tags: views, taxonomy-terms
---


title: View is not showing all columns

text:
# Question
Title: View is not showing all columns
I configured a View showing all groups the user belongs to. I also added the name of the author and his/her role. In the Preview of the View everything is OK, the same if Im logged as an admin (user1). But if Im logged as an authenticated user, the view is not showing up the Role column.

Any ideas what can be wrong? Maybe some permissions, but which one?

# Answer
I think, Role data is not displayed to users other than administrator. Try with 'Field Permissions' module to edit the field specific permissions.
> 1 votes

---
Tags: views, users
---


# Question
Title: How do I change the value of a Hidden element?
I would like to change the value of a hidden element and, depending of this value, to show some elements in the form or not. I'm trying to implement `hook_yamlform_element_info_alter(array &$elements)` and I do `$elements['hidden_element_name']['#value'] = 'New value of the hidden element'` but it doesn't work.

Do you have any idea?

# Answer
Based on @mradcliffe suggestion, I've implemented `hook_form_FORM_ID_alter()` and I do:

```
$form['elements']['hidden_element_name']['#value'] = 'New value of the hidden element';

```

It works for me! I hope it helps someone!
> 1 votes

---
Tags: 8
---


# Question
Title: Elysia cron and feeds being stuck - how to resume the imports?
I have a bunch of Feeds imports, programmed automatically with Elysia Cron.

There is a problem with the size of the content to be loaded, as the import uses to hang, and always at about the same approx. point in a definite feed. The feed, imported manually, throws no errors and do all its stuff perfectly, only fails in automated cron, getting stuck.

After I unblock the Feed with this

```
 update feeds_source set state = 'b:0;';
 update feeds_source set fetcher_result='b:0;';

```

And reset the Elysia table with this

```
 UPDATE elysia_cron SET running = 0 WHERE name = :name_of_process

```

sometimes the Elysia Cron starts again, but, to my dismay, no Feed process is launched even if Elysia Cron says otherwise. There is a Running indication, but no feed importation is done, and the progress indicator in the Feed itself indicates that it is not working.

What can I do, someone has the same problems? I have read tons of documentation, but I find no solution, I see terrible stories on the net about updating processes enduring for weeks, shouldn't just 4.000 products (nodes, taxonomies) load in just 5 minutes?

# Answer
I have discovered that the following lines had been wiped out from the code somehow in my module:

```
 while (FEEDS_BATCH_COMPLETE != $source->import()){
// nothing
 } // while

```

This piece of code keeps de feeds working after it finishes. When the resetting is done via phpMyAdmin, the cron itself (called every minute) launches again the tasks. The Elysia task when being called, but the callback did not do anything as the feed had started and the code lacked the while() construction
> 0 votes

---
Tags: 7, feeds, cron
---


# Question
Title: How to prevent that import with Feeds and Elysia cron gets stuck
I have several Feeds which are called by Elysia cron. The feeds are called at a given time, and later the last two feeds are called each 2 minutes, because it was the only way of preventing them from stopping. However, when data has increased in size and complexity, the cron process is stopped because one or both of the last Feeds are stuck and never ending.

I have seen that by updating the database table `elysia_cron` by setting the field `running` to 0, the Feeds are completed.

So my idea was to create a daemon to regularly update the process and thus prevent the hanging of the Feeds process.

What am I missing, shouldn't this check had been already incorporated into the module itself? What other ideas could prevent the failed import?

# Answer
> 0 votes
I have discovered that temporarily switching off the modules PathAuto and SubPathAuto improved the speed x10, making all these problems dissapear forever. No more feeds stuck or hanged. Later, I enable the modules again, and everything is ready.

---
Tags: 7, feeds, cron
---


# Question
Title: Profile field create and set default value programmatically
I need the checkbox to be checked by default. Below is my code, notice the `'default_value'` under the settings array.

```
$field_instance = array(
    'field_name'    => $fielddef['field_name'],
    'type'          => 'list_boolean',
    'entity_type'   => 'user',
    'bundle'        => 'user',
    'label'         => t($opts['label']),
    'description'   => t($opts['description']),
    'required'      => FALSE,
    'widget'        => array(
        'type'      => 'options_onoff',
        'weight'    => 10,
    ),
    'settings'      => array(
        'allowed_values' => drupal_map_assoc(range(0,1)),
        'default_value' => array(array('value' => 1))
    )
);
field_create_instance($field_instance);

```

I have tried using 'default\_value' in the `$field_instance` array, I've also tried `'default_value_function'` without success. I feel like I'm close on this, what am I missing? Thanks!

Also, I am running Drupal 7.23 as shown on my Status Report. I asked this question earlier on SO, but no reply so I moved it here: https://stackoverflow.com/q/19772646/988355

# Answer
Try with this

```
$field_instance = array(
'field_name'    => $fielddef['field_name'],
'type'          => 'list_boolean',
'entity_type'   => 'user',
'bundle'        => 'user',
'label'         => t($opts['label']),
'description'   => t($opts['description']),
'required'      => FALSE,
'widget'        => array(
    'type'      => 'options_onoff',
    'weight'    => 10,
),
'settings'      => array(
    'allowed_values' => drupal_map_assoc(range(0,1)),
    'default_value' => array(1),
)

```

);
> 0 votes

---
Tags: entities
---


# Question
Title: Show content only if user is an owner of this content (node)
How do I show a node "only if a user is an owner of the node" with Panels/Page Manager' Variants and its Visibility Rules (right icon on each content)?

# Answer
If possible then create your own permission which should be visible under \**Variants » Basic » Selection rules \** section. For creating panel permission, check following steps: 1. Create folder structure like module -\> plugins -\> access -\> filename.inc 2. Add following function and hooks under that file:

```
/**
 * @file
 * Plugin to provide access control based upon role membership.
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Community: Access"),
  'description' => t('Control access by community.'),
  'callback' => 'dc_visibility_ctools_access_check',
  'default' => array('community' => array()),
  'settings form' => 'dc_visibility_ctools_access_settings',
  'settings form submit' => 'dc_visibility_ctools_access_settings_submit',
  'summary' => 'dc_visibility_ctools_access_summary',
  'all contexts' => TRUE,
);

/**
 * Settings form for the 'by role' access plugin
 */
function dc_visibility_ctools_access_settings($form, &$form_state, $conf) {

  return $form;
}

/**
 * Compress the community allowed to the minimum.
 */
function dc_visibility_ctools_access_settings_submit($form, &$form_state) {
  $form_state['values']['settings']['community'] = array_keys(array_filter($form_state['values']['settings']['community']));
}

/**
 * Check for access.
 */
function dc_visibility_ctools_access_check($conf, $context) {

}

function dc_visibility_ctools_access_summary($conf, $context){

}

```
> 0 votes

---
Tags: 7, panels
---


title: Custom forms inside another form?

text:
# Question
Title: Custom forms inside another form?
Is there any way to create a custom form in which one of its elements is another custom form using the YAML Form module?

# Answer
> 0 votes
No, please see Provide mechanism to build composite and/or base forms

---
Tags: 8
---


# Question
Title: valueCallback in custom form element is not invoking itself?
I am creating a custom form element in my custom module. Everything is working fine except the valueCallback function is not invoking itself. I have done it in following way :

Name space

```
namespace Drupal\custom_element\Element;

```

getInfo and valueCallback Method:

```
public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#tree' => TRUE,
      '#process' => [
        [$class, 'processCheckboxes'],
      ],
      '#theme' => 'custom_theme',
      '#value_callback' => ['valueCallback'], // Try with and without #value_callback key
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    dsm('in valuecallback');
  }

```

I am not sure what I am missing.

**Related Link :** https://www.drupal.org/node/2320115

# Answer
It doesn't invoke itself when `#value` is already set to element. I didn't notice that I set it in theme function. After removing `#value` key from `$element` array it is working fine.
> 3 votes

---
Tags: forms, 8
---


title: Services api set browser cookie

text:
# Question
Title: Services api set browser cookie
I would like to use Services to programmatically login a user from another website.

So for example if site.example.com uses the services login endpoint on example.com in Chrome, when that user moves over to example.com they will already have a valid session and cookie for accessing the site.

I have looked into adding the cookies.txt file via my CURL request, and have tried the various different Drupal authentication method like user\_login\_submit() and drupal\_session\_regenerate() but none of them are working.

When i navigate over to example.com the user is still seen as being anonymous.

# Answer
Just for anyone who is looking to implement something similar, i done this using a http redirect to an authentication page, passing and authenticated using the token generated from drupal\_get\_token() (important not to use the session id).

The important steps to follow are to override the GLOBAL $user with the newly generated session user details and then regenerate the session using drupal\_session\_regenerate().
> 0 votes

---
Tags: users, services, cookies
---


title: Map Proximity - Modify markers

text:
# Question
Title: Map Proximity - Modify markers
I want to build a map that has multiple control selectors above the map. When one icon is selected, it prints the relevant markers all over the globe on the map.

If one of the control selectors appears at any one location it just shows one marker, but if two or more different control selectors are clicked on and they share the same location, the marker is modified and expands.

In essence this is something "like a heatmap" function, but not quite.

Anyone had a similar project that can relate and perhaps set me on the right path?

# Answer
> 0 votes
Maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.

---
Tags: 7, google-maps
---


# Question
Title: Drupal 8. Imce module show thumbnails instead of a filename
Is it possibility to show thumbnails instead of a filename in imce file manager? Just not see any options for this..

# Answer
Short answer: No

Long answer: This seems like it existed in the 6.x branch of the module as a "Box View", but in 7.x it looks like it's been dropped. See here for the 6.x discussion. And there's a ticket for 7.x too, with 0 activity.

Edit: Serhiy found out that for D7 there's a template file which can be modified to display thumbnails instead of a list.
> 1 votes

---
Tags: files
---


# Question
Title: How to Create twig template files in drupal 8 for customizing user login,profile edit and forget password forms?
**Earlier we use the below code for creating custom template of user login ,user profile edit and forget password forms:**

```
 function Yourtheme_theme($existing, $type, $theme, $path){
 return array(
 'user_register' => array(
 'render element' => 'form',
 'template' => 'templates/user-register',
),

'user_pass' => array(
  'render element' => 'form',
  'template' => 'templates/user-pass',
),

'user_profile_form' => array(
  // Forms always take the form argument.
  'arguments' => array('form' => NULL),
  'render element' => 'form',
  'template' => 'templates/user-profile-edit',
),
);
}

function Yourtheme_preprocess_user_register(&$variables) {

$variables['rendered'] = drupal_render_children($variables['form']);
}

function Yourtheme_preprocess_user_login(&$variables) {

$variables['rendered'] = drupal_render_children($variables['form']);
}

```

**How to Create same twig template files in drupal 8 for customizing user login,user profile edit and forget password forms?**

# Answer
Using hook\_theme\_suggestions\_alter, you can create whatever template suggestions you like. For example, based on the form id. Just remember, the suggestion has underscores ("\_"), but the template file has hyphens ("-").

```
function Yourtheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook === 'form' && !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

```

then you would create templates in your theme, such as

`form--user-register-form.html.twig`

and

`form--user-login-form.html.twig`

You are doing some non-standard and unnecessary things by rendering the form in a preprocess hook and registering custom theme hooks for your forms. You don't need to create new hooks in hook\_theme, you can just use the suggestions, and it will do the rest, after you clear cache.

You can render your elements within the template.

For example, for form--user-login.html.twig:

```
<div class="login-form login-form__wrapper">
    <form{{ attributes }}>
        <div class="login-form__top">
            <h3>hello world</h3>
            <div id="error_messages"></div>
            {{ element.messages }}
            {{ element.name }} {# username element #}
            {{ element.pass }} {# password element #}
            <div class="login-form__help_actions">
                <input id="show_password" class="show_password" type="checkbox" />
                <label class="password-toggle" for="show_password">Show password</label>
                <a href="/user/password" class="forgot-password">Forgot Password?</a>
            </div>
            {{ element.form_build_id }} {# required #}
            {{ element.form_id }} {# required #}
            <div class="login-form__submit">
                {{ element.actions.submit }}
            </div>
        </div>
    </form>
</div>

```
> 16 votes

---
Tags: users, 8
---


title: Get organic group name in a rule?

text:
# Question
Title: Get organic group name in a rule?
I want to create a rule that sends an email to all users of an organic group when content is posted to that group. In the email I want the name of the group to appear in the subject. I'm completely lost. How can this be accomplished?

# Answer
> 1 votes
You can use the token `[node:group-audience]` to add the group name in your email notification.

Here is the export of the rule I am using:

```
{ "rules_og_group_content_notification" : {
    "LABEL" : "OG group content notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "og", "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [ { "og_entity_is_group_content" : { "entity" : [ "node" ] } } ],
    "DO" : [
      { "og_get_members" : {
          "USING" : { "group_content" : [ "node" ] },
          "PROVIDE" : { "group_members" : { "group_members" : "List of group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : [ "list-item:mail" ],
                "subject" : "New [node:content-type] in [node:group-audience]",
                "message" : "Hello [list-item:name],\r\n\r\nThere is a new [node:content-type] called [node:title] that belongs to [node:group-audience]: [node:url]\r\n\r\n\r\n--\r\n",
                "from" : [ "" ],
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
I was not able to use the placeholder \[node:group-audience\] in my setup for some reason. However the placeholder \[node:og-group-ref\] did the trick.

To answer the rest of this two-years old question, here is a screenshot of the required rules configuration:

To provide the group name in the mail add the placeholder \[node:og-group-ref\] in the subject:

---
Tags: 7, rules, organic-groups
---


title: Sub menu item not found by system

text:
# Question
Title: Sub menu item not found by system
I'm try to overwrite the menu.html.twig file to support my menu structure.

My menu has some links and sublinks (only one level deep). Now when I write the menu.html.twig file I only to all the root links. No subitems can be found.

Can someone tells me what I'm doing wrong?

My source code of menu.html.twig looks like:

```
{% import _self as menus %}

<ul class="nav side-menu">

{% for item in items %}

{% if item.below | length == 0 %}
  <li {% if item.in_active_trail%}class="current-page"{% endif %}>
    {{link(item.title, item.url)}}
    </li>
{% else %}
  <li><a><i class="fa fa-edit"></i> item.title <span class="fa fa-chevron-down"></span></a>
    <ul class="nav child_menu">

      {% for subItem in item.below %}
      <li>{{link(subItem.title, subitem.url)}}}</li>
      {% endfor %}
    </ul>

{% endif %}

{% endfor %}
</ul>

```

My menu structure in Drupal looks like:

# Answer
> 0 votes
Found a way to display the menu correctly.

```
{% import _self as menus %}

<ul class="nav side-menu">

{% for item in items %}

{% if not item.below %}
  <li {% if item.in_active_trail%}class="current-page"{% endif %}>
    {{link(item.title, item.url)}}
    </li>
{% else %}
  <li><a><i class="fa fa-edit"></i> {{item.title}} <span class="fa fa-chevron-down"></span></a>
    <ul class="nav child_menu">

      {% for subItem in item.below %}
        <li><a href="{{ path(subItem.url.routename, {(subItem.url.routeParameters|keys|first) : (subItem.url.routeParameters|first)}) }}">{{subItem.title}}</a></li>
      {% endfor %}
    </ul>

{% endif %}

{% endfor %}
</ul>

```

---
Tags: theming, 8
---


# Question
Title: How to alter languageswitcher to display as select element
I am trying to get to grips with D8, and want to be able to use the language module's language switcher block. I am trying to alter the output to get it to display as a select element rather than a list.I tried creating `block--languageswitcher.html.twig` but couldn't see how to alter the list.

Looking into the module, I can see a function `language_element_info_alter` but cannot see how to use this to render a different output.

Do I need to use a `block_alter` or theme hook? In the LanguageBlock.php, the `build()` function returns an array with a #theme parameter set to `links__language_block`. Would this be what I need?

# Answer
> 1 votes
Yes, you could override the links\__language\_block template (links--language-block.html.twig) and print out a select there by hand. You would also need JS to make selecting something the same as clicking a link as an option element alone won't be able to trigger like a form.

---
Tags: 8, blocks
---


title: Use of a function when importing a feed

text:
# Question
Title: Use of a function when importing a feed
I have a Feed which imports data from a CSV file. I import data of products, namely title, price, category, etc. However, in order to provide a friendly URL, I send a customized field, which is in different languages and completely verbose, for example: *Shoes for female scientists*. I want to use this description as part of the clean friendly URL, so I would need to use some function like `pathauto_cleanstring()`. However, the update takes ages to complete. Is there a faster way, for example directly on import?

This code is executed on a call to *mymodule\_cronapi* via Elysia Cron, and through curl PHP function:

```
   $results = db_query('SELECT nid, title FROM node WHERE type= :product', array(":product" => "product") );
    foreach($results as $row){
        $node = node_load($row->nid);
        $node_wrapper = entity_metadata_wrapper('node', $node);
        $node_wrapper->field_product_url->set(pathauto_cleanstring($row->title));
        $node_wrapper->save();
    } // foreach

```

# Answer
> 1 votes
You should be able to use Feeds Tamper to create your URLs based on values in your CSV: https://www.drupal.org/project/feeds\_tamper

---
Tags: 7, nodes, feeds
---


# Question
Title: How can I get node url in rules for facebook auto post
> Event is: After saving new content

When I add new blog type content it shows error. I know this error is occurred for

> Set a data value
> Parameter: Data: \[entity-created:field..., Value: \[node:url\]

```
1. I know the problem is occurred  Value: [node:url]
2. But I need the url of the created node
3. how can I get this url

```

# Answer
> 0 votes
Make sure when you use `[node:url]` in any code, it must be in `""` so for example

```
$path = [node:url];

```

is wrong, it must be

```
$path = "[node:url]";

```

# As another solution

When you *Set a data value* you can use **Value** textarea and `php` codes to generate the node url.

this is an example where I post a trimmed `field_body` and the node url to Facebook. If you need to post the node alias to Facebook, you can use

```
$nid = [node:nid];
$path = drupal_get_path_alias('node/$nid');

```

to get the alias then print it in the `<?php` segment.

---
Tags: nodes, rules, social-network
---


# Question
Title: Display top level of book, in book navigation block
In my theme's .theme file I have the book navigation block stored in a twig variable like so.

```
function mytheme_preprocess_page(&$variables){
    $book = \Drupal\block\Entity\Block::load('booknavigation');
    $variables['book'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($book);
}

```

I'm then calling it in my page.html.twig template like so

```
<div class="sidebar">
    {{ book }}
</div>
<div class="content">
    {{ page.content }}
</div>

```

However on basic pages that are book pages, sibling book items are shown but the top level book page is not. Even when visiting the top level book page the link is not shown in the book block.

Why isn't the top level of the book ever displayed? And is there a way I can get the top level to be shown?

UPDATE: I've looked at creating a book-tree.html.twig. The contents are below

```
{% import _self as book_tree %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ book_tree.book_links(items, attributes, 0) }}

{% macro book_links(items, attributes, menu_level) %}
  {% import _self as book_tree %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
        {{ dump(book_tree|keys) }}
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ book_tree.book_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```

But I don't see where I can access the top level.

UPDATE: I found a workaround but I'm looking for a solution that does not require that workaround. Users should not have to create an empty page with the same title just to act as the non displayed top level.

# Answer
> 4 votes
This looks like a bug in the book module.

I have added a patch for it.

https://www.drupal.org/node/2827910#comment-11780887

You could add that patch, or create a new block that overrides the BookNavigationBlock,

in a custom module add /src/Plugin/Block/CustomBookNavigationBlock.php:

```
  namespace Drupal\mymodule\Plugin\Block;

  use Drupal\book\Plugin\Block\BookNavigationBlock;

    /**
     * Provides a 'Book navigation' block.
     *
     * @Block(
     *   id = "custom_book_navigation",
     *   admin_label = @Translation("Book navigation - Customized"),
     *   category = @Translation("Menus")
     * )
     */
    class CustomBookNavigationBlock extends BookNavigationBlock {

      /**
       * {@inheritdoc}
       */
      public function build() {
        $current_bid = 0;

        if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
          $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
        }
        if ($this->configuration['block_mode'] == 'all pages') {
          return parent::build();
        }
        elseif ($current_bid) {
          // Only display this block when the user is browsing a book and do
          // not show unpublished books.
          $nid = \Drupal::entityQuery('node')
            ->condition('nid', $node->book['bid'], '=')
            ->condition('status', NODE_PUBLISHED)
            ->execute();

          // Only show the block if the user has view access for the top-level node.
          if ($nid) {
            $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
            return $this->bookManager->bookTreeOutput($tree);
          }
        }
        return array();
      }

    }

```

# Answer
> 0 votes
I ended up solving my issue by creating an empty book page that isn't meant to be visited to act as the top level. And just added everything as a child of the book. Though I'm surprised that the possibility of letting users click on a link to the topmost level of a book wasn't considered by the module.

However I would prefer not to use this route. I'd like the user to be able to create books using the book outline tab on basic pages so they don't have to create empty book pages.

---
Tags: nodes, 8, blocks, navigation
---


# Question
Title: How can I set a default value for date field using hook_form_alter
I am new to Drupal. I need to set a default value to a date field. Please anyone help me on this. Thanks.

# Answer
Please see below code to set a default value for date field using hook\_form\_alter

```
$form["your_date_field"]["und"][0]['#default_value']['value'] = '2016-11-16 00:00:00';

```
> 2 votes

---
Tags: forms
---


# Question
Title: How to create path for taxonomy term pages with parent terms if they exist
I have a taxonomy vocabulary which will only ever contain 2 level deep hierarchy.

I need the url to be just \[vocabulary\]/\[term\] for any parent term.

But for a child term I need it to be the following

\[vocabulary\]/\[parent\_term\]/\[term\]

Is this possible with a pathauto token? If not, is there another solution to this?

# Answer
> 2 votes
You can use pathauto token like this.

```
 [term:vocabulary]/[term:parents:join-path]/[term:name]

```

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: How to get the shipping address programmatically in drupal commerce - what wrapper should i use?
I need to get the shipping address (shipping country to be precise) programmatically in drupal commerce. I have the `$order` object. How can i get the shipping address?

EDIT - Ok i did this

```
 $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
 $shipping =  $order_wrapper->commerce_customer_shipping->value();

```

Now i need to wrap it up again, but i don't know the type

```
$shipping_wrapper = entity_metadata_wrapper(?, $order);

```

Whatshould i put instead of the question mark?

# Answer
> 7 votes
Ok i did this in this way

```
function commerce_shipping_biagetti_service_rate_order($shipping_service, $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $shipping = $order_wrapper->commerce_customer_shipping->commerce_customer_address->value();
  //$shipping is an array containing all shipping data

```

# Answer
> 1 votes
you can use `commerce_customer_profile_load($profile_id)`, the profile id can be fetched from `$order->commerce_customer_shipping` variable since you have the order object.

# Answer
> 1 votes
There are 2 Ways to Find Customer/user shipping Address-

```
function get_user_shipping_address(){

global $user;
$default_pid =commerce_addressbook_get_default_profile_id($user->uid,'shipping');

```

After getting profile id you can load profile and get customer name & Address

```
$profile_load = commerce_customer_profile_load($default_pid);
$first_line = $profile_load->commerce_customer_address['und'][0]['name_line'];
$landmark = $profile_load->commerce_customer_address['und'][0]['sub_premise'];
$postal_code = $profile_load->commerce_customer_address['und'][0]['postal_code'];
$state = $profile_load->commerce_customer_address['und'][0]['locality'];
$add[] = $first_line . ' ' . $landmark . ' ' . $postal_code . ' ' . $state;
return $add;
}

```

second way if you have $order

```
function get_default_address_of_customer_by_order_id($order) {
  $order1 = commerce_order_load($order);
  $shipping_id = $order1->commerce_customer_shipping['und'][0]['profile_id'];
  $address = commerce_customer_profile_load($shipping_id);
  $first_line = $address->commerce_customer_address['und'][0]['name_line'];
  $landmark = $address->commerce_customer_address['und'][0]['sub_premise'];
  $postal_code = $address->commerce_customer_address['und'][0]['postal_code'];
  $state = $address->commerce_customer_address['und'][0]['locality'];
  $add[] = $first_line . ' ' . $landmark . ' ' . $postal_code . ' ' . $state;
  return $add;
 }

```

---
Tags: 7, commerce
---


title: How echo a date field in php

text:
# Question
Title: How echo a date field in php
I am trying to call a custom date field to use in a text pane from a node to use as YYYY-mm-dd in:

```
<div class="swod-date swod-hide">yyyy-mm-dd</div>

```

I have tried to use:

```
<?php echo date('Y-m-d', strtotime($node->field_custom_date['und'][0]['value']));?>

```

but this is not working. I have tied to just print the php but get a result of 1970-01-01 instead of the date in the field.

What am I missing?

# Answer
Check format\_date() function. We can also pass timezone from date field (if any). For example on how to use this function check Formatting the way the date/time is displayed.

```
$custom_date = strtotime($node->field_custom_date['und'][0]['value']);
echo format_date($custom_date, 'custom', 'D j M Y');

```
> 2 votes

# Answer
Please try with below code.

```
echo date('Y-m-d', strtotime($node->field_custom_date[LANGUAGE_NONE][0]['value']))

```
> 1 votes

---
Tags: nodes, panels
---


# Question
Title: How to lock distros so they can only be used on 1 URL?
I plan on making distributions for dating sites and stuff like that.

Maybe sell them as functional themes.

How do I lock the distribution and theme so the client can only use it on 1 URL?

I have seen this done with many website and templates, how can I do this with Drupal?

# Answer
> 2 votes
I see 2 possible approaches (there might be others):

* Include "something" that requires an API key, whereas 1 such key can be used on 1 URL only.
* Offer a "hosted" version only, which uses your distribution. That way you don't have to ... "*distribute*" the *distribution*.

PS: Drupal is GPL, so before creating something that is based on Drupal, make sure you do understand the legal aspects of GPL ...

---
Tags: theming, distributions
---


title: DNS settings in Aegir

text:
# Question
Title: DNS settings in Aegir
I successfully set up Aegir hosting in my Ubuntu based VM. At the time of new site creation I face some problems. I got message saying the new site successfully installed but when i click "Log into site" I get a "page not found error". I understand there will be DNS issue, how can I resolve this?

While trying same thing in my local pc. I get to the new site by modifiying my hosts file. Is it possible to get the site without altering my hosts file?

# Answer
Check out item 2 on this page on setting up sites in Aegir.

> Login to your DNS control panel at your domain registrar, or wherever your nameservers are, and setup the DNS for the domain name to point at your Aegir server. It's worth including a wildcard record - ie an 'A' record for '\*' to resolve to your aegir server - then you can easily setup new sites on subdomains without having to ever setup DNS again!

This video also looks pretty neat, not sure how much it'll help though.
> 2 votes

# Answer
Are you using VM software, such as VirtualBox? Are you trying to connect to the VM through your host machine?

If it so, then you will need to modify your host file for each new site. On Ubuntu it is simple; just type `sudo nano /etc/hosts`, put in your VM IP, and the site name.
> 0 votes

# Answer
I also faced the same issue when I first installed Aegir on my Ubuntu 16.04. What I just did is edit /etc/hosts and point the Aegir address to localhost like this

```
127.0.0.1 aegir.localhost

```

and it works fine.

Note:- You need to restart your server for this to takes effect.

Hope it helps.
> 0 votes

---
Tags: aegir
---


# Question
Title: Error : Only variables should be passed by reference
I get this error Strict warning:

> Only variables should be passed by reference in include() (line 20 of ...)

Can anybody see what is wrong here?

```
<section id="fixed-navbar">
  <nav class="navbar navbar-default navbar-static-top" role="navigation">
    <div class="container">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav">
          <span class="sr-only"><?php print t('Toggle navigation'); ?></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" rel="home" href="<?php print url('<front>'); ?>" title="<?php print variable_get('site_name', ''); ?>">
          <?php print isset($logo) && $logo ? theme('image', array('path' => $logo)) : '<h3>' . variable_get('site_name', '') . '</h3>'; ?>
        </a>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="main-nav">
        <ul class="nav navbar-nav  navbar-right">
          <?php print drupal_render(menu_tree_output(menu_tree_all_data('menu-top-menu'))); ?>
        </ul>
      </div><!-- /.navbar-collapse -->
    </div><!-- /.container -->
  </nav>

</section>

```

# Answer
The error is because you're trying to directly pass menu\_tree\_output() function return value to drupal\_render() function. Which is not allowed because `drupal_render()` accepts `$element` as call by reference. When accepting arguments as call by reference those must be passed as variable (preferred).

So your code should look like below:

```
<nav>
  <div class="container">
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="main-nav">
      <ul class="nav navbar-nav navbar-right">
        <?php $menu_output = menu_tree_output(menu_tree_all_data('menu-top-menu')); ?>
        <?php print drupal_render($menu_output); ?>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container -->
</nav>

```
> 1 votes

---
Tags: 7, debugging
---


# Question
Title: Is it possible to alter the behavior of the Ajax pager?
I have a problem with the way the Drupal 7 Ajax pager works on my website: when looking into the code, it creates links, then when one clicks on one of these links, the ajax.js catches this event and replaces "going to another page" with "loading a block with Ajax-retrieved content".

This causes an SEO problem. In fact, as the links for the Pager are declared like following:

```
<a href="current-page?page=1">1</a>

```

... it is therefore understood by crawlers as links to another page, even though they're not; during SEO analysis of my website, I get a *Duplicate content between page "A" and page "A?page=1"* notice.

Is there is a way to alter this behavior?
For example, how could I replace these links with elements that would have a dedicated attribute? I thought of replacing "a href=" with "span data-target=", for example, but I have no clue how to do this and didn't find any easy solution yet.

Would the amount of work be worth the gain in SEO?

~Stéphane

# Answer
> 0 votes
The way I fixed this was to take advantage of the way the Drupal/jQuery script for the "Views PHP" module's Ajax loading is working:

* It looks for elements in the DOM with such structure : `ul.pager > li > a`
* it listens to a click event and calculates the data to be retrieved based on the "href" tag.
* It operates its magic on the DOM.

My tweak is to modify line 8 of the "ajax\_view.js" file so it also looks for `ul.pager > li > span` elements. Then, I add a hook in my theme's "template.php" file with the following code:

```
function THEME_pager($variables) {
  $output = "";
  $items = array();
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];

  global $pager_page_array, $pager_total;

  $pager_middle = ceil($quantity / 2);
  $pager_current = $pager_page_array[$element] + 1;
  $pager_first = $pager_current - $pager_middle + 1;
  $pager_last = $pager_current + $quantity - $pager_middle;
  $pager_max = $pager_total[$element];

  $i = $pager_first;
  if ($pager_last > $pager_max) {
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  $li_previous = ($pager_current > 1) ? '<span class="progress-enabled" href="?page=' . ($pager_current - 2) . '%2C' . ($pager_current - 2) . '">' . (isset($tags[1]) ? $tags[1] : t('previous')) . '</span>' : NULL;
  $li_next = ($pager_current < $pager_max) ? '<span class="progress-enabled" href="?page=' . ($pager_current) . '%2C' . ($pager_current) . '">' . (isset($tags[3]) ? $tags[3] : t('next')) . '</span>' : NULL;
  if ($pager_total[$element] > 1) {
    if ($li_previous) {
      $items[] = array(
        'class' => array('prev'),
        'data' => $li_previous,
      );
    }
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
          'class' => array('pager-ellipsis', 'disabled'),
          'data' => '<span>…</span>',
        );
      }
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'data' => '<span class="progress-enabled" href="?page=' . ($i - 1) . '%2C' . ($i - 1) . '">' . $i . '</span>'
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => array('active'),
            'data' => l($i, '#', array('fragment' => '', 'external' => TRUE)),
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'data' => '<span class="progress-enabled" href="?page=' . ($i - 1) . '%2C' . ($i - 1) . '">' . $i . '</span>'
            );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => array('pager-ellipsis', 'disabled'),
          'data' => '<span>…</span>',
        );
      }
    }
    if ($li_next) {
      $items[] = array(
        'class' => array('next'),
        'data' => $li_next,
      );
    }
    return '<div class="text-center">' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pagination')),
    )) . '</div>';
  }
  return $output;
}

```

It works perfectly for my usage.

*Note : I know a "href" tag is technically illegal in a "span" element, but I didn't want to dig too deep in Drupal's JS ;)*

~Stéphane

---
Tags: 7, ajax, paging
---


# Question
Title: How to display a image and some text instead of unset a field using form_alter hook?
In D7 I have a field photo on the user account page (user edit form).

I have a conflict between the modules conditional state and simplecrop therefore I like to disable the conditional state module for this field and replaced it by some code in the form\_alter hook..

When another field has a value of ok/not oke I can e.g. use the function like

```
if( set my check here) {
        unset($form['field_photo']);
}

```

But I do not want to unset the field. I would like to display the image and put some text here.

How to achieve this?

# Answer
Using `unset()` with form elements is always wrong.

To avoid the form element is shown, just set its `#access` property to `FALSE` or to the value returned from a function, and that form element will not appear in the form, or it will appear basing on what returned from that function.
Once you make it not accessible from the currently logged-in user, you can add the form elements you need, not forgetting to add the form submission handler to handle the input given from the users for those form elements you add.
> 0 votes

---
Tags: forms
---


# Question
Title: Drupal 8 - How to edit a user as admin without changing the password
Does anyone know how to edit user profiles as an administrator in Drupal 8(change roles in my case) without having to know or change the password?

Thanks

# Answer
You can do it from the command line using drush user-add-role. To find the exact syntax, type :

drush help urol

Hope it helps.
> 1 votes

---
Tags: 8, users
---


title: Drush Command for Installing core

text:
# Question
Title: Drush Command for Installing core
Is there a simple `drush site-install` script for Drupal 8? I've gotten very used to running the following script to install Drupal.

```
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://username:password@localhost/sitename -y;

```

# Answer
I manage to install Drupal 8 with Drush after creating the project with Composer from drupal-composer/drupal-project. Steps I take are as follows:

1. Create project with dev dependencies:

`composer create-project drupal-composer/drupal-project:8.x-dev directory-name --stability dev --no-interaction`

2. Create site-database for the project.
3. Run **inside web folder**:

`../vendor/bin/drush site:install standard --account-name=admin --account-pass=admin --db-url=mysql://username:password@localhost/site-database -y`
> 2 votes

# Answer
`drush site:install` or `drush si` seems to work as intended. You can also use `drush make` to download the core files and any other modules that you need.
> 0 votes

---
Tags: drush, installation
---


# Question
Title: How to show only current user registration list in Node registration view?
I have used views for registration type and listed as table. They listed all registered details to everyone. But I need to show only current user registration list in the table using views contextual filters.

# Answer
Add Configure contextual filter.

Select the Name field.

Checked "**Provide default value**".

Type select box select: **User ID from logged in user**.

Refer
> 2 votes

---
Tags: views
---


title: Check for Feed id in hook_feeds_presave

text:
# Question
Title: Check for Feed id in hook_feeds_presave
I have a module that is using hook\_feeds\_presave. I want to only run specific parts of this function based on the feeds importer that is running. How can I check for the ID of the feed? These are standalone feeds and don't use node forms.

# Answer
> 1 votes
Try printing `$source->id` ( even if `$source` seems empty ). This should return the machine name. It's what I always use.

# Answer
> 0 votes
Not tested but I think you can print\_r and see yourself. function MYMODULE\_feeds\_presave($source, &$node){ drupal\_set\_message(print\_r($source,1)); }

# Answer
> 0 votes
```
function MYMODULE_feeds_presave(FeedsSource $source, $entity, $item) {
    if($source->importer->id=='FEED_ID'){
                # code...
    }
}

```

$source-\>importer-\>id provides the ID of the feed

---
Tags: feeds
---


# Question
Title: How to display referenced field data in view?
I have two content types named as "abc" and "xyz" respectively.

"xyz" content type having field called "field\_abc". Its a referenced field to "abc" content type.

I create a view by taking "abc" contents. Is it possible to show the title of "xyz" in which "abc" taken as referenced field?

I think the reverse may works. Means if I create a view by taking "xyz" contents. But i need to know if I create a view by taking "abc" contents. It will work on not?

# Answer
You want a backreference. For D8 this is an open feature request:

Implement Entity Reference Backreferences

You should consider to this is in a forward reference (what you call reverse). Because even if the feature Backreferences is available, you would also somehow need to manage that there is only one reference, which you want to get the title field from. You can control this in the forward direction by making the reference field single value, but not in the other direction.
> 0 votes

---
Tags: 8, views
---


# Question
Title: Installing a New Site with Drush and Ansible
I'm trying to create an Ansible Role to run on a VM that creates a new site (so my colleagues don't have to memorize the `drush si --db-url` command and automate the entire process.

I'm running into a problem where the `drush si` command is getting the error: `Command site-install needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.` We know this means that we're trying to run Drush from a non-drupal environment, so even when I add the 'chdir' arg to my playbook, it still gets this error.

The command in the playbook looks like this:

`- name: Site Install with Drush
 command: |
 drush si standard --db-url=mysql://{{ mysql_username }}:{{ mysql_password }}@127.0.0.1:3306/{{ mysql_dbname }} --sites-subdir="domain.edu.{{ drupal_uri }}" --db-prefix="d_"
 chdir=/vagrant/d7core/`

# Answer
I found in a comment somewhere deep in the internet that there is a hidden `-r` option to specify the drupal root within a drush command.

The new play looks like this:

`- name: Site Install with Drush
 command: |
 drush si standard --db-url=mysql://{{ mysql_username }}:{{ mysql_password }}@127.0.0.1:3306/{{ mysql_dbname }} --sites-subdir="domain.edu.{{ drupal_uri }}" --db-prefix="d_" -r /vagrant/d7core/ -y
 chdir=/vagrant/d7core/`

Note, I also added the -y option, because it will count as an ansible error when it asks you to confirm that you want to DROP ALL ON *db*.

Because this was hidden functionality and it took me an hour and a half and it was a random comment somewhere that I found that in, I figured I'd make it an official SO question so anyone else looking to automate a workflow could hopefully find this faster.
> 0 votes

---
Tags: drush
---


title: Make a copy of an installation

text:
# Question
Title: Make a copy of an installation
I am trying to create a copy of a Drupal installation in a different folder.

I want to copy the site that is located on https://my-url/drupal to http://my-url/copy. I copied all the files in the Drupal root to the copy folder and I exported and imported the database in a new database and also changed the database configuration of the copy site using settings.php (copy/sites/default/settings.php).

When I put the main site on maintenance mode though the copy site is also put on maintenance mode.

Am I missing something here?

# Answer
Thanks to @Clive giving me an indication that is something to do with memchache I followed these steps to resolve my issue.

1. Disabled the memcache module.
2. Commented out the memchache configuation settings in the settings.php of the copy site.

This resolves the issue.
> 0 votes

---
Tags: 7
---