# Question
Title: How to resolve the negotiated theme for any other user?
I have found How can I programmatically get the theme name?, which works for the current user, but would I apply such logic to learn what theme another user would use?

I can get the active theme for current user and the default theme by using:

```
$my_theme = \Drupal::theme()->getActiveTheme();
$default_theme = \Drupal::config('system.theme')->get('default');

```

I was hoping there would be something like `\Drupal::theme()->getActiveTheme($other_user);` to discover what theme another user would be using.

Is such a thing even possible and how?

UPDATE

To clear things up, I am attempting to figure out what theme was negotiated for a certain user. This could be the global default theme, but it could also be the theme that was negotiated based on a certain role, user selected theme, or any other contrib theme negotiator that might be in place.

So the better question would be, how can I discover what theme a user would be presented if he visits the site (no specific page)?

# Answer
As far as I remember, this type of functionality was built in in Drupal 6.

In Drupal 7 there was the ThemeKey module .

Unfortunately, as of this date ThemeKey is not yet ported to Drupal 8, however I think you can achieve pretty easy that functionality by using the user data object inside custom module.

In order get something from the user data object:

```
$data = \Drupal::service('user.data')->get('mymodule', \Drupal::currentUser()->id(), 'key');

```

In order to set something in the user data object:

```
\Drupal::service('user.data')->set('mymodule', \Drupal::currentUser()->id(), 'key', $value);

```

**Update:**

you can combine the code above with the solution posted here:

https://www.drupal8.ovh/en/tutoriels/259/theme-negotiators-switch-theme-dynamically

where your negotiator will be called last by adding priority in the services.yml

you can implement the business logic inside the function the function determineActiveTheme. Combine this with hook\_user\_login where the information is stored inside users\_data and you have a working solution (If I don't have a mistake somewhere).
> 2 votes

---
Tags: 8, theme-negotiation
---


# Question
Title: HTTP basic authentication to API endpoint for PUT request
I'm make a PUT request to a Drupal API end point created via a custom module and have enabled HTTP based authentication. When I call the api via rest client using Authorization header, the username and password prompts keeps coming again and again even though I supply a valid Drupal user. I see unauthorized user error as well using the advanced rest client on chrome. How do I solve it?

This is the code I am using.

```
function anonymize_user_services_resources() {
  return array(
    'update' => array(
      'update' => array(
        'help' => 'When user is deleted  users info should be anonymized',
        'callback' => 'anonymize_user_info',
       // 'access callback' => 'anonymize_callback',
        'access arguments' => array('update anonymize_user'),
        'access arguments append' => FALSE,
        'args' => array(
            array(
               'name' => 'id',
               'type' => 'int',
               'description' => 'The id of the user to update',
               'source' => array('path' => '0'),
               'optional' => FALSE,
            ),
          ),
        ),
      ),
    );

/**
* Implements hook_permission()
*/
function anonymize_user_permission() {
  return array(
    'update anonymize_user' => array(
      'title' => t('Update inactive user and anonymize'),
      'description' => t('Perform rest call to update and anonymize inactive user'),
    ),
  );
}

```

# Answer
The apache server needed to know the HTTP authorization header so the htaccess file had to be modified to accept the HTTP authorization header.

```
<IfModule mod_rewrite.c>
  RewriteEngine on

  SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

```
> 0 votes

---
Tags: services
---


# Question
Title: Access custom billing field in rules using Commerce
I have added the field `field_e_mail` to the Billing profile type in Commerce and would like to use this for sending an confirmation email to the customer (customers never log in). However, I can't for the life of me get hold of the field in rules. I've tried to use *Entity has field* in different ways, but I still can't get it to work.

What can I do to get the `field_e_mail` field from Billing into rules and use it for sending a confirmation email?

This is where I am at the moment (test@test.com is just a placeholder where I'd like to put the field\_e\_mail value):

```
{ "commerce_checkout_checkout_send_order_activation" : {
"LABEL" : "Send an order notification e-mail (cloned)",
"PLUGIN" : "reaction rule",
"WEIGHT" : "4",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_customer_billing" } },
  { "entity_has_field" : {
      "entity" : [ "commerce-order:commerce-customer-billing" ],
      "field" : "field_e_mail"
    }
  }
],
"DO" : [
  { "mail" : {
      "to" : "test@test.com",
      "subject" : "Order [commerce-order:order-number] at [site:name] test",
      "message" : "hello.",
      "from" : "no-reply@test.com",
      "language" : [ "commerce-order:state" ]
    }
  }
]

```

} }

# Answer
> 0 votes
If you have added the e-mail field on the commerce profile type as you said, you should access is via the profile type as well. (It is not a property of the commerce order.)

Normally, the commerce profiles are already available when the commerce order is loaded. But you might not recognize them as such. Nothing indicates it it a profile.

For instance I have access to these profiles:

And then you can use a condition like this:

```
  { "entity_has_field" : {
      "entity" : [ "commerce-order:commerce-customer-quotation" ],
      "field" : "commerce_customer_address"
    }
  }

```

---
Tags: 7, commerce, rules, emails
---


# Question
Title: Can't restrict permissions on forum topics?
I have like a bit of an issue with my forum-topic content types : **any authentificated user can edit and delete any post in the forums (node or comment of forum-topic type).** It's not the case for any other content type where permissions works normal (user can edit/delete their own content, but not any content).

My features are the following:

User's permissions :

> * Forum topic: Create new content -\> auth user : YES ; admin : YES
> * Forum topic: Edit own content -\> auth user : YES ; admin : YES
> * Forum topic: Edit any content -\> auth user : NO ; admin : YES
> * Forum topic: Delete own content -\> auth user : NO ; admin : YES
> * Forum topic: Delete any content -\> auth user : NO ; admin : YES
> * Bypass content access control -\> auth user : YES ; admin : YES

The modules installed in the forums : Advanced forum, Forum Access.

Forum permissions (in `admin/structure/forum/`) view this forum - post in this forum - edit posts - delete posts : all checked for auth users and admin.

-\> Disabling Forum access only make delete and edit any comment/reply on forum topic disappear. But any auth user can still delete or edit any topic.

-\> Disabling "bypass content access control" make forum topic unvisible to auth users.

I hope it is somehow clear... And you can find what's going wrong.

Thanks !

# Answer
The problem is that you selected "Bypass content access control" for the authenticated users. That means the previous permissions you chose for the authenticated users are not considered: You didn't give the permission of editing any forum topic, but as authenticated users are selected to bypass the content access control, Drupal will not check if they can edit any forum topic, and it will give them that permission.

If you look at the code of node\_access(), the function that returns `TRUE` when a user has the access passed as argument for the node passed as second parameter, you will notice that it execute the following code:

```
if (user_access('bypass node access', $account)) {
  $rights[$account->uid][$cid][$op] = TRUE;
  return TRUE;
}

```

What you reported are only the Drupal core permissions, not the one set by the Forum access module. For the Drupal core permissions, you didn't report if the authenticated users have the "View published content" permission; without that, any published content would not be visible to any users, except the user #1, and the users with the "Administrator" role, for which Drupal automatically set all the permissions, but then leave you the possibility to disable some permissions.

The other problem is the conflict between Drupal core permissions, and the permissions set by the Forum Access module; when you use that module, you should not use the permissions used by Drupal core core, such as the ones you reported. If Forum Access needs to control the permissions, then the permissions you shown for the forum topics should not be set.

If the users get an "Access denied" error for every node, even if those are not forum topics and they have the permission to view published nodes, then the problem is something else. The first think I can think of is that those nodes are unpublished: There is an option in the content type settings that set its nodes as published, when created; if that option is not selecte, the nodes are created unpublished. It could also be a problem with an installed module (which is not Forum Access, as it doesn't handle permissions for other content types); in that case, I would not be able to give a hint about which module is causing the problem, but I see the same problem when the theme used as default theme was not enabled.
> 1 votes

# Answer
What do You think about Taxonomy Acces Control Lite? It seems to be the solution of Your problems.
> 0 votes

---
Tags: 7, navigation, nodes, users
---


title: Migrating images and files

text:
# Question
Title: Migrating images and files
I am trying to migrate a Drupal 7 site to a Drupal 8 site. I already created my module for migration and I have a content type that has a title, field\_picture and a field\_text in Drupal 7.

I want to migrate it to Drupal 8 where field\_text = field\_description and field\_picture is field\_image.

I tried the following:

```
id: drupal7_fruit
label: "Test migration"
migration_group: drupal7
source:
  plugin: d7_node
  node_type: fruit
process:
  nid: nid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_description: field_text
  field_image:
    plugin: iterator
    source: field_picture
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height
destination:
  plugin: 'entity:node'
  default_bundle: fruit
migration_dependencies: {}

```

I could migrate description and title, but the image is never migrated.

What am I doing wrong?

EDIT

**migrate\_plus.migration.drupal7\_fruit.yml**

```
    id: drupal7_fruit
label: "Migrate Fruit Content Type"
migration_group: drupal7
source:
  plugin: d7_node
  node_type: fruit
process:
  nid: nid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_descricao: field_body
destination:
  plugin: 'entity:node'
  default_bundle: fruit
  migration_dependencies:
    optional: drupal7_image

```

**migrate\_plus.migration.drupal7\_image.yml**

```
 id: drupal7_image
label: Images
migration_tags:
  - Drupal 7
source:
  plugin: d7_file
  constants:
    source_base_path: ''
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file

```

Edited my question because @Berdir in the comments said that images or files must have a different migration file but still can't migrate images. I restored my D8 site database to start all from scratch.

# Answer
Thank you for Berdir's help but I noticed that I was missing some information on my drupal7\_fruit migration file like the values for field\_image and migration dependencies.

The working solution:

**migrate\_plus.migration.drupal7\_image.yml**

```
id: drupal7_image
label: Images
migration_group: drupal7
migration_tags:
  - Drupal 7
source:
  plugin: d7_file
  constants:
    source_base_path: '/var/www/username/drupal7/' # Full location of your drupal7 site
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file
migration_dependencies: {}

```

**migration\_plus.migration.drupal7\_fruit.yml**

```
id: drupal7_fruta
label: "Migrate Fruit Content Type"
migration_group: drupal7
migration_tags:
  - Drupal 7
source:
  plugin: d7_node
  node_type: fruit
process:
  nid: nid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_description: field_body
  field_image: # Image field name in Drupal 8 site
    plugin: iterator
    source: field_photo # Image field name in Drupal 7 site
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height
destination:
  plugin: 'entity:node'
  default_bundle: fruit

migration_dependencies:
  required:
    - drupal7_image

```

Hope this may help anyone with the same problem in the future!
> 10 votes

# Answer
images and files are their own entity type. The node table just contains the file id, basically an entity reference.

You need a separate file migration that you need to execute first. You can create it based on the d7\_file migration template.

Note: If you migrate the existing nid and vid (and fid), you need to be certain that you have no existing data with conflicting ids on your D8 site or you will get conflicts. You can leave those out then it will automatically use auto incrementing ids just like when you create content manually. But then you need to set up a migration process plugin to map the old to the new file id.
> 5 votes

---
Tags: 8, migrations
---


# Question
Title: Drupal 8 always editing a translation, never the original
I have a website with 4 languages, while English is the default. Each language has its own directory (`mydomain.com/contact`, `mydomain.com/jp/contact`, etc.). I have the following languages:

* English
* Czech
* Japanese
* Russian

For the record, my language detection is configured with these priorities:

1. URL
2. Session
3. Selected Language
4. Browser

When I try to edit a translation of a content page (let's say Japanese), it works just fine, but when I try to open an edit page (`mydomain.com/node/6/edit`) of the orignal, english node, I'm always getting "Edit Basic Page Nobg Kontakty \[Czech translation\]", with the Czech content and can't access the edit page for the english original. What to do?

# Answer
> 1 votes
If you want to use English as default without URL prefix you have to disable

* Session
* Browser

in the language detection list, so that only URL and Selected Language (which can't be removed) is enabled.

Then configure in

* Selected Language

the site's default language (English).

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


title: Redirect after submit form

text:
# Question
Title: Redirect after submit form
I use this code in my form ( buildForm(array $form, FormStateInterface $form\_state) ) :

```
<?php

namespace Drupal\test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManager;
use Symfony\Component\HttpFoundation\Response;

class TestForm extends FormBase {

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

    public function buildForm(array $form, FormStateInterface $form_state) {
        \Drupal::service('page_cache_kill_switch')->trigger();

    $a['ad_mail'] = [
        '#type' => 'email',
        '#title' => t('Email ID:'),
        '#required' => TRUE,
    ];
    $b['total'] = [
        '#type' => 'hidden',
        '#attributes' => [
            'id' => 'actionsubmitid',
        ],
        '#value' => '0',
    ];
    $c['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Finalize the purchase'),
        '#button_type' => 'primary',
    ];
    $test= [
        '#theme' => 'test',
        '#a' => $a,
        '#b' => $b,
        '#c' => $c,
    ];

    return $test;
    }

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

    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        $form_state->setRedirect('test.new');
    }

}

```

Now I want redirect to a machin name ( for example "test.new" ) that create in routing.yml file . I use `$form_state->setRedirect('test.new');` in "submitForm(array &$form, FormStateInterface $form\_state)" but not work .

EDITED :

.routing.yml

```
test.old:
  path: '/test/old'
  defaults:
    _form: '\Drupal\bpay\Form\TestoldForm'
  requirements:
    _permission: 'access content'

test.new:
  path: '/test/new'
  defaults:
    _controller: '\Drupal\bpay\Controller\TestnewController::new'
  requirements:
    _permission: 'access content'

```

# Answer
The `buildForm` method needs to return `$form`. Not `$test`. You're missing key items by ignoring the `$form` variable. Properly set the form items (not as their own variable) and remove the custom theme hook you're trying to do. Cut this down to its simplest pieces first just to get it working and go from there.

Get rid of `$a $b $c` variables as that doesn't make any sense, just use `$form`. Your submit info is not making it into the form itself, which is why it isn't working.
> 3 votes

# Answer
You can set the redirection in form action,

```
// Get the routename
$routename = 'test.new';
  $url = \Drupal\Core\Url::fromRoute($routename);
  // make the redirection
  $form['#action'] = $url->toString();

```
> 1 votes

# Answer
I think it may be because you are killing the cache with this:

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

Remove that and see if your redirect works.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Alter views limit using hook_views_query_alter
I've used **display specified number of items** for set limit in views. I want to change limit and also display all items using hook\_views\_query\_alter(). I've tried this:

```
function test_views_query_alter(&$view, &$query) {
  if ($view->name == 'sample') {
    $query->set_limit(20);
    //~ $view->set_items_per_page(20);
  }
}

```

But i've no luck. How to solve this?

# Answer
Try using the following:

```
function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
    $view->set_items_per_page(2);
}

```
> 3 votes

# Answer
Drupal 8.

I created views in rest mode for send 10 items per page. But the native pager was not works for me. So, I implemented **hook\_views\_query\_alter**() for set up custom pager settings with limit and offset.

1) Create **custom\_rest\_api.views\_executable.inc** file for implement the hook

2) Set views offset and page limit

```
/**
 * @file
 * Containts custom_rest_api.views_executable.inc.
 */

use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_query_alter().
 */
function custom_rest_api_views_query_alter(ViewExecutable $view,     QueryPluginBase $query) {
   if ($view->id() == "news" && !empty($view->args)) {
   $number = (int) ($view->args[0]);
   $number--;

   $limit = 10;
   $offset = $limit * $number;

   $view->setOffset($offset);
   $view->getPager()->setItemsPerPage($limit);
 }
}

```
> 3 votes

---
Tags: views
---


# Question
Title: Change the node edit link for a specific content type
I want to be able to change the node edit link from node/\[nid\]/edit to my\_custom\_module/\[nid\] for just one content type. Which hook sould I implement?

I need this change to be applied to all the node edit links present on the frontend and backend of the site.

I tried implementing hook\_menu\_link\_alter but this hook does not provide me any node-related data so I can not apply the link changes just to one content type.

# Answer
> 1 votes
You can use hook\_node\_prepare, Please check the below code which can help you to sort out your problem.

```
function hook_node_prepare($node) {
if($node->type == "somecontent type"){
    drupal_goto("/somepath..");
}

```

}

---
Tags: 7, nodes
---


title: Alter edit link behaviour in a view

text:
# Question
Title: Alter edit link behaviour in a view
I am trying to change the URL of the node edit link for a specific view. This is what I have done and it (almost) works:

1. created a file **mymodule/views/mymodule.views.inc** with the following code:

```
/**
 * Implements hook_views_data_alter().
 */
function kd_ari_views_data_alter(&$data) {
  module_load_include('inc', 'mymodule', 'views/views_handler_field_article_link_edit');
  $data['views_entity_node']['edit_node']['field']['handler'] = 'views_handler_field_article_link_edit';
}

```
2. created a second file **mymodule/views/views\_handler\_field\_article\_link\_edit.inc** with the following code:

```
class views_handler_field_article_link_edit extends views_handler_field_node_link {

 function render_link($node, $values) {
   if (!node_access('update', $node)) {
     return;
   }
   $this->options['alter']['make_link'] = TRUE;
   $this->options['alter']['path'] = 'admin/mymodule/' . $node->nid;
   $text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
   return $text;
 }
}

```

The problem is that the view displays the edit link only one time after I clear all caches... afterwards the display link is gone. Any tips would be highly appreciated.

# Answer
> 1 votes
Add Nid as field, Set Label to Operation (or anything you want ), in *Rewrite results* section

* check **Override the output of this field with custom text** and enter *Edit* text.
* check **Output this field as a custom link** and in the input box enter `admin/mymodule/[nid]` .

save the field and enjoy the power of views rewriting.

---
Tags: 7, views
---


title: Content type 1 to N relation view

text:
# Question
Title: Content type 1 to N relation view
First of all sorry if this is a basic question.

I have two content types "Category" and "Items"

I used "Entity reference" to link both content types with each other.

Category contains "Category1, Category2, Categry3" as data.

Items contains 10 items 1 to 10. Lets say each categoy contains 3 items.

How can I create a view of items grouped by categories? For example:

1. Category 1:

* Item 1
    * Item 2
    * Item 3
2. Category 2:

* Item 4
    * Item 5
    * Item 6
3. Category 3 :

* Item 7
    * Item 8
    * Item 9
    * Item 10

Thank you very much in advance for your support

# Answer
> 0 votes
Let's suppose your nodes titles for Category content types are *Category N* and for Item Content Type are *Item N*.

Create a view on content filtered by content type = category, then in views advanced section in **Relationships** add relation on your entity reference field on category content type, then in the field section again add a title but in **Relationship** section of the field settings choose your relation created before and then Group Results by Category title field.

---
Tags: views
---


# Question
Title: How to parse a URL's content into a Drupal node
I'd like to create a node type in which I'd have an URL field, title and some description. Once I create a new node using this content type, Drupal would parse the contents of the URL I've added in the URL field. It'd work almost like one of these read it later services.

Is this possible, if its how? I've been looking into feeds, but its not exactly what I'm looking for (as it deals with rss/atom rather than url).

Background: Basically I'm creating a personal wiki using Drupal and wanted the ability to parse content directly to a node type. This way I can categorize the way I want as well as being able to create views, aggregate different content, etc. This is for a personal project and the site wouldn't be public.

# Answer
> 0 votes
Yes, it is possible using hook\_node\_insert or hook\_node\_presave. You will just need to implement it like:

```
function hook_node_insert($node) {
  if ($node->type == 'CONTENT_TYPE_MACHINE_NAME') {
    // get the URL content here
  }
}

```

You can do it using the hook\_node\_presave too. The only difference is that it is called before even the node is saved into the database.

# Answer
> 0 votes
If you have a lot of data/fields you'll be importing from these URL's, you can look into the migrate module, https://www.drupal.org/project/migrate. It has a really nice framework to migrate data in.

You can invoke the migration from multiple places, like the hooks Asad mentions.

---
Tags: uri, nodes
---


title: How to configure Secure Pages

text:
# Question
Title: How to configure Secure Pages
I'm using Drupal 6 on a website and trying to configure SSL for it.

I installed the Secure Pages module. However I can't figure out the following things:

* How to give secure pages to all anonymous users and admin.
* How to secure all pages of my site in the settings.

The documentation is not extensive.

Please help as I've spent half the day trying to fix this.

# Answer
> 0 votes
If I recall, SecurePages has an easy config to enforce HTTPS for everyone on all paths. Check the README.

You could also ditch SecurePages and force all traffic to HTTPS via .htaccess.

---
Tags: 6, ssl
---


# Question
Title: How to hide certain fields on the User Edit form?
So I have three types of users - admin, LA admin and users. I am trying to set it up so that admins and LA admins cannot edit the username, password and timezone for users. I am talking about the default user edit form for admins and the form ID is "user-profile-form".

I have created a custom module but this doesn't seem to be working. Any idea what I might be doing wrong?

Even the var\_dump does not seem to be outputting. I have cleared the cache and verified that the module is enabled.

```
function profile_change_form_alter(&$form, $form_state, $form_id) {
    if ($form_id === 'user-profile-form') {
    // Use var_dump  to dump the $form array to see the fields.
        var_dump ($form);

        hide($form['account']['pass']);
        hide($form['account']['current_pass_required_values']);
        hide($form['account']['current_pass']);
    }
}

```

# Answer
> 3 votes
You need to replace form id `user-profile-form` with `user_profile_form`

Your code should look like the following:

```
function profile_change_form_alter(&$form, &$form_state, $form_id) {
    // changed form id
    if ($form_id === 'user_profile_form') {
        // Use var_dump  to dump the $form array to see the fields.
        var_dump ($form);

        hide($form['account']['pass']);
        hide($form['account']['current_pass_required_values']);
        hide($form['account']['current_pass']);
    }
}

```

# Answer
> 0 votes
This code will work if you want to disable the field instead of hiding them.

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'user_profile_form') {
    if ($user->uid != 1) {
      $form['field_joining_date']["#disabled"] = TRUE;
    }
  }
}

```

Replace the 'field\_joining\_date' by your custom field name.

---
Tags: users, forms
---


# Question
Title: How field values are stored in the database
I'm working in a migration from Drupal 7 and I'm trying to find out where the value of some fields are. I've tried but could not find an answer for this on this site.

I see each field has a pair of tables:

```
field_data_field_{field_name}
field_revision_field_{field_name}

```

Some of the `field_data` tables have a column named `field_{field_name}_value` and that's easy to find.

However, other tables don't have this column and have one called `field_{field_name}_target_id`. Inside it they have an integer but I can not find where it is referenced to...

I'm looking only at the database, I don't have the code (yet) and I don't know if this is related to a module, or if this is Drupal native. Anyhow, I can't find any other table with the values that relate to these Ids...

# Answer
Different field types can have different data columns in the database. Most modules have a 'value' column. Others, like reference fields, have a 'target\_id' column instead. The Date module can create a 'value1' and 'value2' column (for start date / end date).

You can't assume that it is always 'value'.

The 'target\_id' value refers to the ID of the entity being referenced. So, if the field is referencing nodes, target\_id is holding a node id value. If the field was referencing users, the value stored is the user id.
> 2 votes

---
Tags: 7, entities
---


title: force views to bring a specific nid

text:
# Question
Title: force views to bring a specific nid
I want to have a views with this Filter criteria

```
Content: Nid (= 2410)
OR
Content: Type (= news) AND
Content: value (= high) AND
Content: published (Yes)
OR
Content: Type (= multimedia) AND
Content: category (<> cinema) AND
Content: piblished (Yes)

```

and Sort criteria :

```
Content: Post date (desc)

```

and just need to display 10 items.

actually, I need to force views to bring one or more NIDs. But when it sorts the results by post date if the specified nid is older than the 10 first results it does not appear in the results.

How can I solve the problem?

# Answer
I can think of two solutions. I will improve my solution a bit if you clarify exactly what the concept is behind the fixed node ID.

**Solution 1: Custom field**

* Create a custom boolean field (working just like the *node.sticky* property).
* Filter and sort your view by the boolean property.

The advantage of this approach is that the admin would be able to change the hard-coded default node you want to display by simply updating the custom field from the node form. Also, they would be able to specify more than one such forced-appearance nodes, which is good in certain cases.

**Solution 2: Custom sort handler**

* You can write a custom views sort handler and add an `ORDER BY n.nid = 2410 DESC`.
* You will have to ensure that this sort is placed before the other sorts though.

BTW, as an additional suggestion, if you are using a hard-coded `nid` in logic, then make sure nobody can delete that node, otherwise you will have to change the relevant code every time someone deletes that node by mistake.

Hope this helps! Good luck.
> 1 votes

# Answer
I suggest you remove that specified node form that display and add it as attached OR another solution divide the what do you did into two view display and with getting help of hook\_views\_pre\_render combine them (helper question)

and Third solution is remove 10 item limit and with getting help of hook\_views\_pre\_render you should manually limit it to 9 result ordered by date and the specified NID. try something like following snippet (I don't have drupal 7 to test it, But take the Idea )

```
function HOOK_views_pre_render(&$view) {

  if($view->name == 'VIEWS_MACHINENAME' && $view->current_display == 'DISPLAY_MACHINE_NAME') {

    if(empty($view->result)){
      return;
    }
    $other_items = array();

  foreach($view->result as $item){
      if($item->nid == 2410){
       $special_item = $item;
      }else{
       $index = $item->created . $item->nid; // maybe some nodes has the same created time
       $other_items[$index] = $item;  // set index of array to created for sorting
       }
    }
    krsort($other_items); // sort by key descending , key = publish date
    $final_items = array_slice($other_items, 0, 9);
    $index = $special_item->created . $special_item->nid;
    $final_items[index] = special_item;
    krsort($final_items); // sort again to have correct sorting with special Item
    $view->result =  $final_items;
  }
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: In which file is the list of the installed modules saved?
I am trying to synchronize some config data, and I'm getting the following error:

```
X depends on modules (examples here) that will not be installed after import.

```

Now I'm fine with adding the setting that they'll be enabled after synchronization, but I cannot for the life of me find any documentation or where in the config files this lives.

Does anyone have any information?

# Answer
> 2 votes
You are looking for `core.extension.yml`. Directory for configuration synchronization is set up in `settings.php` with variable `$config_directories`.

Here is the documentation, but it's not full.

---
Tags: 8
---


title: Set a Date field with Rules?

text:
# Question
Title: Set a Date field with Rules?
I have a form that users can fill out and it creates a node, an event node to be shown in the community calendar of my website. I'm using Rules to create the new node when the "Webform: After a webform has been submitted" event (requires Webform Rules module).

Everything is working well except for the Date field. The event node needs a date and time, that's kinda the point of a calendar!

I can select the webform data with `[data:date-value]` and `[data:time-value]` and I know that they output the correct data because if I put them into a regular text field (`[entity-created:body:value]`) the date and time show up just fine. And I can use PHP if I need to:

```
<?php
  echo $data['components']['date']['value'][0] ;
?>

```

I just don't know what Data Selector to choose for the date field. There's several that Rules knows about but so far I have no luck:

* `entity-created:field-date`
    + if I choose this, in the resulting page to set the new value, there is no PHP Evaluation or Replacement Patterns available to use, only the Data Selector ajax dropdown, which doesn't allow for the `[data:date-value]`.
    + and it says "`Data types: Select data of the type List<struct>.`"
* `entity-created:field-date:0` \- it goes from 0 to 3 although there's only 1 date field for the event node, and they all the same
    + if I choose this, in the resulting page to set the new value, there is no PHP Evaluation or Replacement Patterns available to use, only the Data Selector ajax dropdown, which doesn't allow for the `[data:date-value]`.
    + and it says "`Data types: Select data of the type Struct.`"
* `entity-created:field-date:0:value (Start Date)`
    + in the resulting page to select the new value, it says: "Data types: Select data of the type Date." so I think it's a step in the right direction...
    + now there's a plain value field I can use (direct input mode),
        - instructions say: "The date in GMT. You may enter a fixed time (like 2016-06-04 16:01:07) or any other values in GMT known by the PHP strtotime() (link is external) function (like "+1 day"). Relative dates like "+1 day" or "now" relate to the evaluation time." If I put "+1 day" into the field and test it by submitting the webform, then a node is correctly created with the date field set one day into the future.
    + I can switch to the Data Selection mode and I have Data Selectors, PHP Evaluation and I can add an offset.
        - if I set the new value to `[data:date-value]` or `[data:date-value] [data:time-value]` then it doesn't say there's any errors, but when I test it but submitting the form and checking the new node that was created, the Date field was not set
        - if I try to set the value to `<?php echo $data['components']['date']; ?>` ... still no luck. And no errors are displayed or logged.
    + it also lists `entity-created:field-date:0:value2 (End Date)` and `entity-created:field-date:0:duration (Duration)` as possible "Set a data value" things to select

Anybody have any idea what I'm supposed to do here?? Thank you!

# Answer
While it is not possible to set the date using the *Set a Data Value* action (see my other answer), it is possible to set it using the *Execute custom PHP code* action.

This is the code I am using.

```
// set the date
$date = format_date(strtotime($data['components']['date']['value'][0] . ' ' . $data['components']['time']['value'][0]), 'custom', 'Y-m-d H:i:s', 'UTC'); // ISO format
$entity_created->field_date[LANGUAGE_NONE][0] = array(
    'value' => $date,
    'timezone' => 'UTC',
    'timezone_db' => 'UTC',
  );

```

The format is extremely important. It will not work unless it exactly matches the format, which is controlled by the 'Field Type' you have chosen for the date field of the content type (ISO or Unix Timestamp). I have ISO. I was missing the '\T' part of the format and I was scratching my head for weeks trying to figure it out. Date Field Types explains it a little.
> 0 votes

# Answer
Re Dan Mantyla's comment, if your date field is not a Date (UNIX timestamp) or Date (ISO) field but just a normal Date field, the following code works for me:

```
$thedate = $data['components']['date']['value'][0].' 00:00:00';

// set the date
$entity_created->field_date[LANGUAGE_NONE][0] = array(
    'value' => $thedate,
  );

```
> 1 votes

# Answer
Since you are using Webform, the "clue" to answer your question might be that you have access to all labels and all values of any field of a webform available, i.e:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name `MachineFieldName`.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name `MachineFieldName`.

Refer to my answer to "How to create a node from a Webform using rules?" for way more details.

The above is a good start, but not sufficient to achieve your goal (= "... what Data Selector to choose for the date field", as in your question). However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your `[data:date-value-raw]` (and with a data type which equals the data type of your Webform component). Looks like you need 2 variables though: 1 related to `[data:date-value]`, one for `[data:time-value]`.
* In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).
> 0 votes

# Answer
it's not possible

when setting value for `entity-created:field-date:0:value` if I use the data selector field and choose site:current-date then I am able to set the date field of the new node to the current date and time.

if I use PHP to emulate the same date format, ie "Fri, 06/24/2016 - 14:10", with the field data - `return format_date(strtotime($data['components']['date']['value'][0] . ' ' . $data['components']['time']['value'][0]));` \- it prints in the same format (I know because I print it to the screen using the `dms()` function) but it does NOT set the date field of the new node. It does not work :(

If I simply type the string and use PHP to return it in the PHP Evaluation field of the Rules setting, like this - `return "Thu, 08/04/2016 - 02:02";` \- it STILL DOES NOT WORK ! :(

if I put `return $value + 1000;` into the PHP Evaluation field with `site:current-date` still in the Data Selector field, it does set the Date field of the new node correctly, with the date a few minutes into the future from the current date and time, as expected.

if i put return `$value + strtotime($data['components']['date']['value'][0]);` into the PHP Evaluation field with `site:current-date` still in the Data Selector field, it does set the Date field of the new node BUT IT DOESN'T SET THE DATE/TIME INTO THE FUTURE as expected! **THEREFOR I CAN CONCLUDE that the PHP Evaluation field CANNOT access the $data variable and probably nothing but the $value variable.**

edit: https://www.drupal.org/node/1231418 \- "In contrast to the php input evaluator, the php data processor doesn't support accessing variables yet. Patch welcome."
> 0 votes

---
Tags: 7, entities, rules, webforms, datetime
---


title: Add paragraph element programmatically

text:
# Question
Title: Add paragraph element programmatically
When change format field through ajax I want to add paragraph element programmatically and display it on current form, just do the same like if I would click the add question answer, any ideas ?

# Answer
> 1 votes
You're going to have to do this with Javascript. You'll need to add a listener on the text format field and trigger a click on the button when the text format value is changed to what you want.

---
Tags: 8, paragraphs
---


title: unflag from all users

text:
# Question
Title: unflag from all users
I have created a views list of users who are flagged offensive by other users.

I want a button in front of each user to clear that flag from him from every user. So if admin after checking the user decided that he was wrongly flagged he can simply remove that flag.

I have different view pages for each flag report like following

* annoying
* offensive
* fake

So if I am on view page for list of annoying users, I need a link in front of each user to clear that flag from that user from all/any users.

# Answer
> 0 votes
I'm assuming this question is about D7 ...

### Step 1

Start with creating an extremely basic Rules Component with a Rules Action to unflag (using the Flag module) a user, whereas you specify the user to be unflagged as a parameter for that Rules Component. And you pick one of the 3 flags you want to process (eg the "*annoying*"-flag).

Optionally include whatever Rules Conditions you might need (if any, eg to check if the user is flagged). FYI: this is really like a getting started with Rules ...

### Step 2

Use the view of flagged user that you already have and transform that view 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 unflag a single user. I.e the Rules Component from Step 1.

### Step 3

Use the checkmark in front of each user in your VBO view as the "***button in front of each user to clear that flag***" (as in your question), and select the custom VBO action that you created in Step 2.

### Step 4

Repeat the previous steps for your additional flags, i.e. the "*offensive*"-flag and the "*fake*"-flag.

---
Tags: views, flags
---


# Question
Title: What's this type of content actually called?
I think I've been getting the terminology wrong.

When I open a Panel and go to the Content region and click the gear icon, then Add Content a modal appears.

On the left of this modal are categories housing various site components - gallerys, forms, HTML, etc

What are these things collectively actually called?

# Answer
> 0 votes
I think those are called site content (but I don't know if you'll find a name for all of them written somewhere, as you said).

---
Tags: 7, theming
---


# Question
Title: Unable to install lullabot/amp and sensiolabs/security-checker
i have installed amp and composer manager today i have been trying to get lullabot/amp installed, i have managed to install composer and drush on my computer but im not sure if they have been installed correctly. The image below shows that they are not installed. This is on my localhost/xampp would that make any difference. Could someone help me get this right as its a big learning curve as i have never used composer or drush since today. Any ideas on how to get this working.

# Answer
Try these commands, in this order: 1. Go to the docroot and type: drush composer-json-rebuild 2. In the same place: drush composer-manager install 3. If this doesn't work, go to sites/default/files/composer and type: composer install 4. In the end you can run: drush composer-manager update
> 0 votes

---
Tags: 7, theming, drush, configuration, composer
---


# Question
Title: How to assign define role to group creator in groups created with the Group module?
I am using the Group module. Whenever a new group is created, member is added to that group with role `none`.

I want to assign a role to a group when a user creates a group. How can I do that?

# Answer
The latest beta release of the group module (8.x-1.0-beta5) includes that functionality.

Download, install, run DB updates and go the the settings page for the group type.
> 1 votes

---
Tags: 8, group
---


# Question
Title: Reestablishing development workflow with GIT after doing it wrong
At one point, I had the following proper Drupal development workflow: local development environment (using Mamp), dev server for testing and a production server, and I used GIT to deploy the changes from the local to the repository and then I would pull from the repository into the dev or production server. MAMP was causing me a lot of issues so I uninstalled it in favor of setting up a LAMP stack in a more traditional way. But I'm using a Mac and things got really wonky. I basically messed up my local dev environment beyond all repair and wasn't able to use it but I had an aggressive deadline for a project.

I began to make many changes to the website on the dev server and then doubling the work on the live site, no longer using the local environment or pushing the changes up using GIT. During this time, I didn't commit any of the changes to GIT either. Basically, GIT and the local dev have been out of the picture for the last several months.

Since my last commit, the following situations have changed.

* created a new git repository that I want to use
* my local dev stack is still non-functional
* I want to set up a new host so I can test my existing dev site for current hosting issues

Where do I go from here in order to get back on track so that I can move the current website to a new host and preserve the GIT history without being able to use a local dev environment?

# Answer
> 2 votes
Commit the changes on the live site to the master git branch and then branch off this to create a develop branch.

The master branch should mirror live and development takes place on individual branches, when you're ready merge or pull request onto the develop branch. When ready to go live merge or pull request into master.

---
Tags: workflows, version-control
---


# Question
Title: Programmatically translate a string in hook_update_N()
Is there a function I can use to perform a string translation in `hook_update_N()`?

# Answer
> 10 votes
Yes, you can check in the locale module how it's done and replicate to use the same queries like this :

```
/**
 * Translating some pagination strings.
 */
function hook_update_XXXX() {
  $translations = array(
   'last' => array(
     'fr' => 'dernière page',
     'en-en' => 'last',
   ),
   'first' => array(
     'fr' => 'première page',
     'en-en' => 'first',
   ),
 );

 foreach ($translations as $string => $values) {
   $source = db_query('SELECT lid, source, context, textgroup, location FROM {locales_source} WHERE source = :string', array(':string' => $string))->fetchObject();
  if (!$source) {
    watchdog('update_hook', 'Translation of string "%string" failed.', array('%string%' => $string));
    continue;
  }

  foreach ($values as $langcode => $translated) {
    $translation = db_query('SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language', array(':lid' => $source->lid, ':language' => $langcode))->fetchField();
    if (is_string($translation)) {
      db_update('locales_target')
      ->fields(array('translation' => $translated))
      ->condition('lid', $source->lid)
      ->condition('language', $langcode)
      ->execute();
    }
    else {
      db_insert('locales_target')
      ->fields(array(
        'lid' => $source->lid,
        'translation' => $translated,
        'language' => $langcode,
      ))
      ->execute();
      }
    }
  }
}

```

I'm using such code to update strings in code instead of having to this manually when deploying code. So a simple "drush updb" can do the job for me.

OR as I've found out recently, a faster version exists like this :

```
/**
 * Translating some strings.
 */
function hook_update_X() {
  $report = array(
    'skips'=> 0,
    'updates'=> 0,
    'deletes'=> 0,
    'additions'=> 0
  );

  // Translate strings.
  _locale_import_one_string_db($report, 'fr', '', 'Your shipping address book is currently empty.', 'Votre carnet d\'adresses de livraison est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);
  _locale_import_one_string_db($report, 'fr', '', 'Your billing address book is currently empty.', 'Votre carnet d\'adresses de facturation est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);

  // Clear locale cache.
  cache_clear_all('locale:', 'cache', TRUE);
}

```

For Drupal 8, please see this answer : https://drupal.stackexchange.com/a/220608/61138

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


# Question
Title: HTML tags in a block body are not rendred
I'm using Drupal 8. I have created a custom installation profile. Inside the profile profileName.install file, I created the following function:

```
function setupCustomBlocks() {
  $blockContent = BlockContent::create([
        'type' => 'basic',
        'info' => 'Why choose us?',
  ]);
  $blockContent->set('body', '<p><i class="fa fa-drupal"> </i></p>
                              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>'
  );
  $blockContent->save();

  $block = Block::create([
        'id' => 'why_choose_us',
        'plugin' => 'block_content:' . $blockContent->uuid(),
        'region' => 'topwidget_first',
        'provider' => 'block_content',
        'weight' => 0,
        'theme' => \Drupal::config('system.theme')->get('default'),
        'visibility' => array(),
        'settings' => [
          'label' => 'Why choose us?',
          'label_display' => TRUE,
        ],
  ]);
  $block->save();
}

```

The bellow function, allows me to create a custom block when I install the profile. Here is the result:

As you can see, the HTML tags are not rendering. How can fix that?

# Answer
> 1 votes
It's rendering the block's content a plain text, not HTML, because you aren't setting the body field's format property when creating the `BlockContent` entity.

```
$blockContent = \Drupal\block_content\Entity\BlockContent::create([ 'type' => 'basic', 'info' => 'Why choose us?' ]);
$blockContent->body->value = '<p><i class="fa fa-drupal"> </i></p>
                              <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>';
$blockContent->body->format = 'full_html';
$blockContent->save();

```

---
Tags: blocks, installation-profiles
---


# Question
Title: Programmatically get the product name from $order
I need to get the product name using the `$order` variable in Ubercart. How can I achieve?

# Answer
> 0 votes
In ubercart **uc\_products** table stores the product details. You can get product id from the $orders array and can fetch the required product data from uc\_products table.

```
$query = "SELECT * FROM uc_products WHERE nid = ". $pid;

```

Refer the links for more details https://www.drupal.org/node/1940926

# Answer
> 0 votes
Here's the link that you have to check uc\_order\_get\_product\_list. ubecart API will help you alot:

you will get an array with the products when you pass the `$order` variable to it.

```
$product_list = uc_order_get_product_list($order)

```

check the `$product_list` variable and you'll find the product name/ node ids there.

if it's only node ids \[node\_load\] method in Drupal will help you to get the product title. (https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_load/7.x)

work with \[devel\] (https://www.drupal.org/project/devel) module and development will be easier for you in drupal. use `dsm ($variable)` to display the variable content. it works like `var_dump($variable)` in PHP but has a more developer friendly interface for drupal.

---
Tags: 7, ubercart
---


# Question
Title: Get order title value from $order variable
I have to get order status and order title from $order variable. I can get order status by `$order->order_status`. But I can't able to get order title. So how to get order title value from $order variable programmatically.

I am using the below hook :

```
  function hook_uc_order($op, $order, $arg2) {
     if ($op == 'update') {
       if (($order->order_status == 'payment_received') && ($order->title == 'My Product')) {
         // Do something with the $order object.
       }
    }
  }

```

Here `$order->order_status` is working individually but `$order->title` is not working. How to get Order Title?

Looking forward for this answer.

# Answer
> 0 votes
You can get the order title from this method.

```
   uc_order_page_title($order)

```

check out all the methods you need for ubecart. ubecart drupal 7 API

---
Tags: 7, ubercart
---


# Question
Title: Why my button element don't trigger the submitForm method?
I have a form with a `<button>` element

```
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['address'] = array(
      '#type' => 'textfield',
      '#autocomplete_route_name' => 'geocoder_autocomplete.autocomplete',
      '#title' => '<span>' . t('Find an adoration place') . '</span>',
    );

    $form['submit'] = [
      '#type' => 'inline_template',
      '#template' => '<button type="submit" class="glyphicon glyphicon-search"></button>',
    ];

    return $form;
  }

```

When I click the button the page is refreshed but the `submitForm()` method is not called. If I add an `<input type='button'>` element in the form and I click the `<button>` or the `<input type='button'>` the `submitForm()` is called.

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['address'] = array(
      '#type' => 'textfield',
      '#autocomplete_route_name' => 'geocoder_autocomplete.autocomplete',
      '#title' => '<span>' . t('Find an adoration place') . '</span>',
    );

    $form['submit'] = [
      '#type' => 'inline_template',
      '#template' => '<button type="submit" class="glyphicon glyphicon-search"></button>',
    ];

    $form['submit1'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

```

I'm missing something here? Why my button element don't trigger the submitForm method?

# Answer
> 4 votes
Your first "submit" button doesn't get recognized by Drupal as a button because you use an inline template.

If you want to add a class on your button use:

```
$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes'=> ['class'=>['glyphicon', 'glyphicon-search']],
];

```

---
Tags: 8, forms
---


title: Drupal & Wordpress User Integration

text:
# Question
Title: Drupal & Wordpress User Integration
I know I might be asking a really dumb and likely complex matter, but it's the only remotely easy option I have at the moment.

Due to what is set up on two systems by my predecessor, wordpress and drupal both appear as CMS's that I have to manage, the one problem area apparently always having been the ability to keep users accounts in order so that if a user created an account on one site, the admin would have to go through and manually connect that account to the other site.

So my question is, after looking through everything and apparently finding very little to resolve this issue, I am coming to ask whether or not there is an option for me to connect the two (for the time being, I don't expect it to take more than a few months) in just how pull, from a table, a username and password? And just as a heads up, I am converting the wordpress to drupal so this problem will be solved in the near future, I just need this as a temporary solution...

I'd greatly appreciate any help.

# Answer
This is a rough sketch based on some other projects I've been involved in but the WP part is a bit uncertain. FWIW here it is:

1) install services, rest server and an auth module (like oauth or api\_key) the on drupal and create an endpoint with resources for the user functions you need. Find a great tutorial by here. Essentially you should be able to push a php call with the json to your endpoint (Chrome's postman is a great tool to test this with) and get a 200 response if user was logged in or 401 unauthorized if not.

2) pause WP from processing user tasks on its side

3) export legacy WP users to csv and import users into Drupal using the user import module

4) Now you should be able to set ping your drupal from WP, get a reply back, set a session var if logged in and serve content on WP as if they logged in.

Granted, this is not an ideal setup but hopefully will carry you through the few months until you convert WP to Drupal.
> 2 votes

---
Tags: 7, users, security
---


title: Role delay using Rules

text:
# Question
Title: Role delay using Rules
I'm aware of the Role Delay module however it is not working for me. I'm running D7. I read somewhere that it is possible to do the same thing with Rules.

The 3 stages I want users to go through are...

1) Non-authenticated user 2) Authenticated user 3) Trusted authenticated user

I've got the movement from 1) to 2) working fine as it's taken care of by the Logintoboggan module (upon account activation). Moving 2) to 3) is proving trickier as I want it to be time based, after the 1) to 2) event.

All I want users to move from 2) to 3) in 24 hours after they become an authenticated user.

# Answer
### Step 1

Create a Rule Component to "Grant a user the Trusted authenticated user permission" (whereas the user is specified as a parameter for this Rules Component).

### Step 2

Enable the rules scheduler (a sub-module of the Rules module).

### Step 3

Adapt the rule you seem to have in place already for that "movement from 1) to 2)" (or create a new rule that catches that as a Rules Event): at the end of this rule, add another Rules Action to schedule the execution of the Rules Component in Step1, after 24 hours.

Optionally you may also want to add some extra Rules Conditions that the user does not have rule "3)" yet (or any other Rules Condition that may fit).

### Step 4

Next time your cron job runs, the permission "Trusted authenticated user" will get granted.

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

---
Tags: rules
---


title: It doesn't run the first time

text:
# Question
Title: It doesn't run the first time
Trying to run cron tasks using `0 */1 * * * root curl -s http://site.name/cron.php?cron_key=secret_key >> /var/log/site-cron.log 2>&1` or `0 */1 * * * root wget -O - -q -t 1 http://site.name/cron.php?cron_key=secretkey >> /var/log/site-cron.log 2>&1` doesn't work.

Using `0 */1 * * * root curl -s http://site.name/cron.php?cron_key=secret_key >> /var/log/site-cron.log 2>&1` and `2 */1 * * * root curl -s http://site.name/cron.php?cron_key=secret_key >> /var/log/site-cron.log 2>&1`, the second attempt works.

Access log shows both calls, but dblog shows only the second attempt. There are no errors in nginx log, cron log, php-fpm log.

How do I fix this?

UPD: thanks @zhilevan. I was able to debug cron scripts with his help. This way `drush --root=/usr/share/nginx/demo --quiet cron` displays errors in cron scripts.

# Answer
If your source code and crontab on the same server I suggest try to run internally by PHP, Try something like

```
0 */1 * * * root  /usr/bin/php /home/sites/example.com/public_html/cron.php

```
* **/usr/bin/php** = your php path
* **/home/sites/example.com/public\_html/** = your site source code path

For getting more information read Configuring cron jobs using the cron command.

**Update: Solution 2 : create bash script**

```
touch ~/scripts/cron-php.sh
chmod 700 ~/scripts/cron-php.sh
vi ~/scripts/cron-php.sh

```

filled it with

```
#!/bin/bash
root_path=/usr/share/nginx/demo/
parse=/usr/bin/php

# PHP parser options
#
# Defaulting to not report notices.
parse_options="-d error_reporting=2037"

# Verbosity
#
# Default to only report errors.
verbose=false

cd $root_path

if [ -e "cron.php" ]
then
    $parse $parse_options cron.php
    if [ "$?" -ne "0" ]
    then
         echo "cron.php not parsed."
    else
         if $verbose
         then
             echo "cron.php has successfully been parsed."
         fi
    fi
else
    echo "cron.php not found."
    exit
fi

exit

```

and then the crontab itself:

```
$crontab -e
*/1 * * * * ~/scripts/cron-php.sh

```

**Third Solution is based on Drush**

According to Drush Doc

```
0 */1 * * * /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /usr/local/bin/drush --root=/usr/share/nginx/demo --uri=your.drupalsite.org --quiet cron

```
> 0 votes

# Answer
Running cron tasks before clear all your cache. During development it is necessary to clear the cache very frequently. Clearing caches is relatively harmless. Sites might slow down for a bit afterwards while the cache fills back up.
> 0 votes

---
Tags: cron
---


title: Drupal 7 Solr 4 $query group by

text:
# Question
Title: Drupal 7 Solr 4 $query group by
I'm beginner in Drupal 7 et Solr 4. I have $query and I want to do a group by category. How can I add 'group by' as a parameter to $query (DrupalSolrQueryInterface) ??

# Answer
> 0 votes
I solve my problem. In the view of Apache Solr, I enter the parameter and and add the field of group by. That's all.

# Answer
> 2 votes
You can add custom parameters through `hook_apachesolr_query_alter`, eg

```
function MYMODULE_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->addParam('group', 'true');
  // etc
}

```

---
Tags: search
---


# Question
Title: How to make Adaptivetheme dropdown menu show on start page?
I'm using Drupal 8 with an Adaptivetheme subtheme. The horizontal navigation menu resides in the leader board region. Some menu entries have submenus, but they do not show on the start page. One has to click on the respective menu (e.g. "Football"), which loads the single page "Football", and it is only here that submenus will be shown.

Is there a way to make submenus work on the start page with Adaptivetheme?

# Answer
Try editing the relevant menu at /admin/structure/menu/

Edit each (first level) items that is not showing it's submenu items and tick off "show as expanded".

This is a general tip. I don't know exactly how your theme works.
> 0 votes

---
Tags: navigation
---


title: Different path for multilingual view

text:
# Question
Title: Different path for multilingual view
With the Drupal 7 module Internationalization Views it was possible to add in a view a different url-path in each active language.

In D8 i found only a solution with a redirect, but i'ts the way i want it.

Any suggestions?

# Answer
> 4 votes
I think you are searching for URL alias for different language.

Go to `/admin/config/search/path/add` where you can add alias for different language.

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


# Question
Title: How can I have a multilingual URL for a views result page depending on the language?
I have a multilingual website that is currently in 5 languages. We are going to be adding more - a lot more.

Views has a Filter, "Language: Current user's language" to display content based on the language the user has selected to view the content in.

Currently we are not using that filter, and the reason is URL path setting for the Views result page. Instead, because we have to have the URL translated into the language being viewed as well, we have a block configured with an English URL page, for example, and the language filter set to English.

Instead, I need to be able to configure just one view to use the Filter "Language: Current user's language" and, when that page is viewed, I need the url to display correctly in that user's language regardless of the one entry I am allowed in the Views page configuration. I also need for this to show properly in the Menu I select there as well when the page is viewed as a translation.

How can I achieve this?

# Answer
You should enable "Translation sets" and "Path translation" modules, both part of i18n module.

Then in admin/config/regional/i18n\_translation/path, you have to add the translated paths and then add a "translation set" which will map all these pages together.

Doing this, you'll be able to switch language on your view page and retrieve the corresponding alias (same view with different current language)

See also this page on drupal.org documentation.
> 4 votes

# Answer
You can use Internationalization Views module as well.
> 2 votes

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


# Question
Title: drupal_render() returns "Array" instead to render the content
I'm using Drupal 7 and I have made a custom module in which there is this function.

```
    function product_search_by_pin_form($form, &$form_state) {
           // Provide a text field.
           $form['pin'] = array(
           '#method'=> 'POST',
           '#action' => '$come_back',
           '#title' => t('Input your PIN'),
           '#type' => 'textfield',
           '#attributes' => array('size' => '20', 'maxlength' => '20'),
           '#placeholder' => 'Type your PIN',
           '#required' => TRUE,);

           // Provide a submit button.
           $form['submit'] = array(
           '#type' => 'image_button',
           '#required' => TRUE,
           '#src' => "/images/upload/search.png",
           '#attributes' => array('id' => 'submit'),
           '#value' => 'Search',);

           return $form;
    } // END of Function

```

The form is being used from the following code.

```
    $arr = drupal_get_form('product_search_by_pin_form');
    print drupal_render($arr);

```

The problem is that Drupal displays the *Array* instead of showing the form.

How can I solve it?

**EDIT** As asked, and after have followed suggestions but without result, please here the code of the module

```
<?php
/**
 * @file
 * a test file
 */

/**
 * Implements hook_menu().
 */

function myform_menu() {
  $items = array();

  $items['/examples/myform-examples'] = array(
    'title' => 'Example myform',
    'description' => 'Configuration for TEST module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('product_search_by_pin_form'),
    'access callback' => TRUE
  );

  return $items;
}

/**
 * Implements hook_help().
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */

function myform_help($path, $arg) {
  switch ($path) {
    case "admin/help#myform":
      return '' . t("<b>Myform</b> to test a drupal form") . '';
      break;
  }
}

function product_search_by_pin_form($form, &$form_state) {
       // Provide a text field.
       $form['pin'] = array(
       '#method'=> 'POST',
       '#action' => '$come_back',
       '#title' => t('Input your PIN'),
       '#type' => 'textfield',
       '#attributes' => array('size' => '20', 'maxlength' => '20'),
       '#placeholder' => 'Type your PIN',
       '#required' => TRUE,);

       // Provide a submit button.
       $form['submit'] = array(
       '#type' => 'image_button',
       '#required' => TRUE,
       '#src' => "/images/upload/search.png",
       '#attributes' => array('id' => 'submit'),
       '#value' => 'Search',);

       return drupal_get_form($form);
} // END of Function

```

# Answer
First try Render instead of drupal\_render

```
$arr = drupal_get_form('product_search_by_pin_form');
print render($arr);

```

From Clive answer on what is the difference between render() and drupal\_render()?

> The docs for render() explain it pretty well:
>
> This function renders an element using drupal\_render(). The top level element is shown with show() before rendering, so it will always be rendered even if hide() had been previously used on it. render() is basically just a wrapper for drupal\_render(), except that it makes sure the element passed in is set to be shown when passed through to drupal\_render().
>
> It also makes sure the element passed in is an array (which is all drupal\_render() can accept). If it isn't, the element is return back as-is. So it provides a bit of a safety net if you like.
>
> If for any reason you have a variable you need to render, and you don't know if it's a string or a render array, you can pass it straight through render() without having to test the variable type yourself.

and another solution is, use `drupal_get_form` as you call back function and pass your form to it as an argument. ( take a look at https://www.drupal.org/docs/7/howtos/how-to-make-a-simple-module-with-a-form-and-menu-link )

```
function YOURMODULE-NAME_menu() {
  $items = array();

  $items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('product_search_by_pin_form'), //put the name of the form here
    'access callback' => TRUE
  );

  return $items;
}

function product_search_by_pin_form($form, &$form_state) {
         // Provide a text field.
       $form['pin'] = array(
       '#method'=> 'POST',
       '#action' => '$come_back',
       '#title' => t('Input your PIN'),
       '#type' => 'textfield',
       '#attributes' => array('size' => '20', 'maxlength' => '20'),
       '#placeholder' => 'Type your PIN',
       '#required' => TRUE,);

       // Provide a submit button.
       $form['submit'] = array(
       '#type' => 'image_button',
       '#required' => TRUE,
       '#src' => "/images/upload/search.png",
       '#attributes' => array('id' => 'submit'),
       '#value' => 'Search',);

  return $form;
}

```

and **third** is another way of implementation second solution

```
function product_search_by_pin_form($form, &$form_state) {
       // Provide a text field.
       $form['pin'] = array(
       '#method'=> 'POST',
       '#action' => '$come_back',
       '#title' => t('Input your PIN'),
       '#type' => 'textfield',
       '#attributes' => array('size' => '20', 'maxlength' => '20'),
       '#placeholder' => 'Type your PIN',
       '#required' => TRUE,);

       // Provide a submit button.
       $form['submit'] = array(
       '#type' => 'image_button',
       '#required' => TRUE,
       '#src' => "/images/upload/search.png",
       '#attributes' => array('id' => 'submit'),
       '#value' => 'Search',);

       return drupal_get_form($form);
} // END of Function

```
> 1 votes

# Answer
Don't return `drupal_get_form()` from your function. Just return the $form variable. Your menu item is already calling `drupal_get_form()`, you don't need to from your form builder.

When calling it programmatically, use the `render()` function to turn a form array to HTML output.
> 1 votes

# Answer
Instead of printing the form directly, You should be returning the form array. like

```
  $output['form'] = drupal_get_form('product_search_by_pin_form');
    return $output;

```

if you have to handle it seperately, You should be creating a template and print the form varibale in that temlate.
> 0 votes

---
Tags: forms
---


# Question
Title: How to add a comment box in a view so that users can comment on it just like it displays in node
I want to add a comment box in a view so that user can comment there also just like they do in specific node.

# Answer
> 0 votes
You can create a *block* display of the View, add that block to a node, and activate comments on that node.

---
Tags: 7, views
---


# Question
Title: How to restrict ckeditor to display full html alone?
I am using ck editor and want to hide the filtered html and plain text.

And user should use only the full html format. They should not get the option to select filtered html and plain text.

Anyone guide me how to do this in ck editor?

# Answer
> 0 votes
You can install the Better Formats module to achieve this.

Better formats is a module to add more flexibility to Drupal's core input format system.

> ## Features
>
> 8.x & 7.x (needs more testing for a stable release)
>
> * Set allowed text formats per field.
> * Set default order of text formats per field.
> * Hide format tips per role.
> * Hide more format tips link per role.
> * Hide format selection per role per entity.
> * Currently only works on Field API fields on fieldable entities implementing core - style text processing. The good thing is that is most things in core and contrib.

This will let you limit what format is available per field implementing formatted text, like a body field.

Despite what the warning says, I have used this extensively on many sites to do exactly what you asked about.

---
Tags: 7, wysiwyg
---


title: How to sum two fields

text:
# Question
Title: How to sum two fields
I have a content type with the field\_watermelons and field\_apples fields. I want to record the sum of these fields in the (existing) field\_total\_fruits field. How can I achieve this?

I do not want to use the Computed field module(because of PHP filter requirement) and the Math Field module is also out because it can't handle Field Collections at the moment (if it could, then I'd have my answer).

I tried `hook_form_alter` with a callback function attached to the `$form['submit']`. In that callback, I've tried a number of methods of inserting new values including adding values to `$form_state`'s input, values, completed\_form. I've also tried to use `entity_metadata_wrapper()` approaches in the callback, to no avail. I also tried `form_set_value()`.

How to create a Rules action set to calculate a sum of integers in a Field Collection? looks interesting, but there's no answer.

Surely I'm over-thinking this. Can someone tell me if there's a simple way to sum two field values and insert that sum into the value of another field programmatically?

I suppose I could use the Drupal AJAX system too. I just didn't want that hassle, thinking that there's an easier way, but perhaps it's the best option.

# Answer
> 4 votes
Ok, I've got a solution that will work for me. This d.o forum comment was *very* helpful.

Instead of changing the `$form['submit']` array, **prepend** the callback to the submit callback stack! Like so:

`array_unshift($form['actions']['submit']['#submit'], 'MODULE_my_custom_submit_handler');`

Note that the code in the comment from d.o is a bit off, you don't need to assign the unshift'ed array, you just run `array_unshift` on the array itself.

Once that's added in your `hook_form_alter` you can do WHATEVER processing magic you want with `form_set_value()`. Cool! Thanks all.

EDIT: here's what the callback looks like. Also note that for some reason someone took out my fields in my original question. But these field names would make more sense if someone didn't do that.

```
function MODULE_my_custom_submit_handler($form, &$form_state) {
  $lang = $form['language']['#value'];

  $a = $form_state['values']['field_fruit_collection'][$lang][0]['field_watermelon']['und'][0]['value'];
  $b = $form_state['values']['field_fruit_collection'][$lang][0]['field_apples']['und'][0]['value'];

  $sum = $a + $b;
  form_set_value($form['field_total_fruit'][$lang][0]['value'], $sum, $form_state);
}

```

# Answer
> 3 votes
If the value of the field\_total\_fruits is always the sum of the other fields, then there is not really a point in storing it. Instead, you can compute the value when you want to display it, or when you want to do other things with it.

You now have a number of options, depending what you want to do with the result.

I personally do not like solutions like "computed field", from what I remember from last time I used it.

## Actual fields + hook\_entity\_presave() (EDIT)

Yes, you can store the sum in a dedicated field added to the entity. This means having redundant data in the database, but it also means having the data available to functionality that only works with fields. It can make your life easier.

To do so, you can use hook\_entity\_presave() to calculate the sum and store it in the new field.

Notice that you probably need to load the field collection items, because the field items of `$node->field_fruit_collection` will only contain the field collection item ids.

You should pay attention to the array indices `[$langcode][$delta]` of field items. On a specific site it can be sufficient to always hardcode \`\[LANGUAGE\_NONE\]\[0\], but this limits the reusability of the module a lot. And you'd still need to check if the keys are set to prevent PHP notices.

I think it is ok to hardcode some assumptions into your module. You are already hardcoding the field names, so you can also hardcode which of the fields are single-value. So in `[$langcode][$delta]`, the `$delta` is always `0`. Or use `reset()` to pick the first item. This makes your module unsuitable for publishing on drupal.org, but good enough for your site.

But for the language key you should be more careful. Normally I would say loop over the languages, then store results per language in the field\_total\_fruit. Maybe use some kind of fallback logic to use LANGUAGE\_NONE if no language present.

What complicates things here, is that both the field collection and the field\_apples and field\_watermelons can have values per language. E.g. you could have `$node->field_fruit_collection['fr'][0]['field_collection_entity']->field_apples['en'][0]['value']`.

Things like this can go unnoticed for a while, and then you get strange bug reports that make you scratch your head.

Since all of this is numbers, I'd say configure these fields so that only LANGUAGE\_NONE is used.

I would say do NOT use field\_get\_items() here. Or if you do, be careful what you are doing. The entity will be saved in all languages, and field\_get\_items() filters the result to the current language only. So you could have inconsistent behavior depending on the current user language.

## Entity properties

You could use hook\_entity\_property\_info() to register a property with a value callback. In this value callback you would use field\_get\_items() on both fields and calculate the sum.

Entity properties can be used in a number of places, but they do not naturally show up in field ui for entity view modes, or as views fields.

You would need to do more research to find a way to make them show up in views or elsewhere. Although the hook has some interesting fields like 'entity views field' which might help.

I think it would be worth it to do some more research in this direction, possibly even open a new question. Entity properties are quite a powerful concept, and really there has to be a way to make them show up where you need them.

## DS custom field

You could declare a Display suite custom field where you calculate the value. This will only be available in DisplaySuite-enabled view modes, though.

## Custom Views field handler

You could write you own views field handler. But these are only available in Views, not elsewhere.

I personally have created some of those, but never really enjoyed working with the API.

## Custom "entity display plugin"

There is a collection of modules that I have created myself, that would make this specific task quite easy. The downside is that this is an entire new world to dive into, not something you want to do for just one little task. I am presenting this option here for completeness.

You start with EntDisP. It has a bunch of dependencies, which are listed on the module page. The basic getting-started is explained on the module page.

You would then create a custom module, e.g. "fruitsum" with a custom entity display plugin.

I could elaborate on this further, but this would give it unjust priority over the other options.

The advantage is that these plugins are easy to write and maintain once you get the hang of it, and they can be used in a lot of places.

The disadvantage is that, as said, this is a completely new world to dive into.

## Conclusion

I personally would suggest to follow the "entity property" route, with some research of your own. If you find a way to make those things show up, you have a new tool at your disposal for future tasks.

I am even considering to create a new entdisp plugin for the purpose of displaying properties.

Maybe other answers can elaborate more on this direction. Or if you find out, you could write the answer yourself!

# Answer
> 1 votes
So you want to sum 2 fields of a field collection, and you think the Rules module may help you doing so. Indeed, that's a way to do so, have a look at my answer to "How to add up all items of a field collection field using Rules?" which includes a rule (in Rules export format). Here is how the rule looks like:

```
{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
    "LABEL" : "Calculate sum of prices in all field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "Article details item" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-price" ],
                  "op" : "+",
                  "input_2" : [ "article-details-item:field-price" ]
                },
                "PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
            { "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
    ]
  }
}

```

Refer to the related answer for "some" details, and a demo, about it.

To "*insert that sum into the value of another field*" (as in your question), just add another Rules action after the sum got calculated, and use a "Set a data value" Rules Action.

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

PS 2: this answer applies to revision 2 of your question, and does not yet take into consideration your most recent edit you added (and which makes your question a chameleon question, which IMO should have been a followup question ... instead of changing your original question).

---
Tags: entities
---


# Question
Title: How dio I change things on module installation?
I've been looking around for several days now, maybe i'm just not fully understanding how the new Drupal 8 framework works entirely. What i'm trying to do is create a module that is a complete product that runs on the Drupal framework. I need to be able to completely customize the Drupal settings when the module installs. Changing things like the "Home" link to be "Dashboard" or just remove/disable it entirely or updating the front page url to point to the page i'm going to be creating programatically. There are also a myriad of administrative settings that i would like to set as well like the site email, error pages, email templates, and configuration of other required modules.

If anyone has any examples of how this can be done or can point me to the right areas of documentation that has the answers i'm looking for (googling has not yielded the answers and i like to think i have pretty decent google foo).

# Answer
> 0 votes
I think what you are thinking of is configuration and overriding configuration. You can load any config object and set its value.

See: https://drupal.stackexchange.com/a/187488/57

Menu links are entities and can be loaded and changed too. See: https://drupal.stackexchange.com/a/225605/57

---
Tags: 8, installation
---


title: Loop through all entities with rules

text:
# Question
Title: Loop through all entities with rules
I have a content type (called Issue dates with fields called field\_issue\_date (date type) and field\_issue\_type (term\_reference)) and by using Rules module 7.x-2.9 I want to check if the taxonomy field has been set to "Double", If so I want to list and set the next Issue Dates content type to be unpublished e.g

"Magazine Issue Date 2017-04-07 (Double)"

"Magazine Issue Date 2017-04-14" this should now be set as unpublished

"Magazine Issue Date 2017-04-21" this should be/remain published

**Note:** If Rules isn't the way to go, what would be a better way to unpublish a piece of content

# Answer
> 0 votes
Have a look at this, rather basic, rule (in Rules export format):

```
{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_issue_type" } },
      { "list_contains" : { "list" : [ "node:field-issue-type" ], "item" : "4" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_issue_type] just got created or updated." } }
    ]
  }
}

```

Here is what this rule does:

* Rules Event: After saving new content, After updating existing content
* Rules Conditions:

+ ***Entity has field*** "`field_issue_type`", which is the machine name of the term reference field I want to check for.
    + ***List contains item*** "node:field-issue-type" and with Taxonomy term identifier value "`4`" (which is the term id of the term I want to check in this Rules Condition).
* Rules Action: Show a message on the site (which is "*A node containing the tag \[node:field\_issue\_type\] just got created or updated.*" (with `[node:field_issue_type]` the actual term with term id = `4`).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions. Especially because of your extra comment "`field_issue_type` is a multiple value" (only "List contains item" is the Rules Condition that will do the trick ...).

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

* Within the Rules Conditions, adapt the "term id" (= "`4`") to fit your case.
* Replace the Rules Action by what you want to happen as per the "*set the next Issue Dates content type to be unpublished*" in your question, which should really be a different (followup?) question.

PS: This answer applies to D7.

---
Tags: rules, views
---


title: How to set parent on taxonomy term

text:
# Question
Title: How to set parent on taxonomy term
I have done:

```
$term = Term::create([
  'name' => 'title',
  'vid' => 'myvocab',
])->save();

```

It works.

But I don't seem to be able to set the parent term.

I have tried:

```
$term->parent = array($parent_tid);
$term->save();

```

It gives an error:

> InvalidArgumentException: Value is not a valid entity. in Drupal\Core\Entity\Plugin\DataType\EntityReference-\>setValue() (line 106 of /core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php).

I have also tried:

```
$term->parents = array($parent_tid);
$term->save();

```

It gives no error, but also does nothing.

In my code $term could be a new term or an existing term I've loaded, which is why I set the parent and then save it. But I can't get it to work.

Documentation for D8 is sparse. I've dug around the code in the taxonomy module, and it looks like `parent` is an entity reference field that accepts multiple values, but I can't work out how to set it. It looks like setting `parent` to array($id) should work, but I think the magic setter is breaking. Any help?

# Answer
The correct way for a reference field is to set the property target\_id:

```
$term->parent = ['target_id' => '2'];

```

All this shorter versions work too:

```
$term->parent = ['2'];
$term->parent = '2';
$term->parent = 2;

```

Also works like this:

```
$term->set('parent', ['target_id' => 2]);
$term->set('parent', 2);

```
> 12 votes

# Answer
It turns out that I was doing it right after all: `$term->parent = array($parent_tid)`. The problem was that to find `$parent_tid`, I was using `$another_term->tid`. It turns out that this is a FieldItemList, and to get the tid I have to use `$another_term->tid->value`. I don't know if maybe there is a better way?
> 1 votes

---
Tags: 8, taxonomy-terms
---


title: Disable render cache for a node type

text:
# Question
Title: Disable render cache for a node type
Is there a way to disable the render cache, which caches all the nodes by default, for a particular content type `X`.

I know we can disable the render cache site wide by commenting out

```
$settings['cache']['bins']['render'] = ‘cache.backend.null’;

```

in `settings.local.php`. But this is not a ideal approach for me as I need to disable the render cache only for a particular node type.

Also, I need to disable the cache for both Authenticated and Anonymous users for the content type `X`.

Any pointers on the same would be very much appreciated.

# Answer
Like you said disabling the render cache site wide is not a good idea. If you need this for one content type you can do this in a view alter hook.

If you want to disable caching for authenticated and anonymous users you have to set cache max-age = 0 and trigger the kill switch for the internal page cache:

```
function MYMODULE_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($entity->bundle() == 'article') {
    $build['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')->trigger();
  }
}

```

The same can be implemented in a theme in a preprocess hook.
> 19 votes

---
Tags: theming, 8, caching
---


# Question
Title: How to configure an additional field for a bundle that is created by a custom module
In Drupal 8 have a custom module for which bundles are created via yaml files in its config/install folder. I need to add an additional field to the 'schema.'

My steps were:

* pm-uninstall the module
* delete the content type via the ui
* rebuild cache
* add the new yaml file (a clone of an existing file with the field name changed)
* re-enable the module

This gave me an unmet dependencies error.

If I remove the file and enable the module, the bundle is created, without the field of course.

I can create the field via the ui, but then its yaml file is not present in the install folder, so the module isn't deployable as-is.

# Answer
You have to add the field via the UI. Then you can export the yml config files required by the field by

1. Using drush cex sync
2. Navigating to admin/config/development/configuration/single/export and export the changed/new files on admin/config/development/configuration manually.

Copy the new/changed files to your config/install folder and you are good to go
> 1 votes

---
Tags: entities
---


# Question
Title: How to require a user to be logged in to access files
On my website I currently have a way for users to upload files. It has been brought to my attention that these files are showing up in search engines. I'm fairly new and this is not a desired effect. As a way to fix this for now, is there a way I can restrict access to `sites/default/files`to logged in users? Thanks!

# Answer
> 2 votes
You have to setup the private file system. You can do this on /admin/config/media/file-system.

Next you will have to alter your field to use the private file system instead of the public file system. If this field already has data, you can use https://www.drupal.org/project/filefield\_paths to migrate the files from public to private

# Answer
> 1 votes
Go to admin -\> Config -\> Media -\> file system. Ensure that a folder for the private file system is set. Then go to the file upload element settings, and choose the private method for file storage.

---
Tags: 7, files
---


# Question
Title: Why can't anonymous users vote more than once from different browsers/machines?
I created a poll in a Drupal 8 site and I enabled anonymous voting too, but when opening the pool in different browsers/machines, the poll results appear and anonymous users cannot vote.

Please tell me where the issue is.

# Answer
> 0 votes
Seems like that was the issue because of same IP address. But in case of local network with hundreds of machines, how will that be taken care of, is still a question. Right resource: Does poll not allow multiple anonymous votes?

---
Tags: 8, polls
---


# Question
Title: How to keep the same vertical tab open on AJAX call?
We're using vertical tabs on a configuration form for a ctools content type inside Panels. Inside most of these vertical tabs, there are "Add more" buttons, which use AJAX to add another item to the form. Essentially combine these two examples:

https://api.drupal.org/api/examples/vertical\_tabs\_example!vertical\_tabs\_example.module/7

https://api.drupal.org/api/examples/ajax\_example!ajax\_example\_graceful\_degradation.inc/function/ajax\_example\_add\_more/7

We set the container around the whole form to reload the entire thing. The problem is that, on reload, the vertical tabs reset. We'd prefer it leave the element that the user currently had open open. Is there a way to do that?

# Answer
> 0 votes
We can save in $form\_state html id current vertical tab. Only, be sure, do not forget to set custom ids your tabs

---
Tags: ajax, chaos-tool-suite, forms
---


# Question
Title: When page is not node entity site breaks
How can correct this, my problem is that I'm using node label to set class. And everything works perfectly until I visit contact form or user login form which are not node entities, then site completely breaks, only on that two pages. How can I make some condition if it's not node or its contact form?

```
  if ($vars['node']->getType('location')) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $title = $node->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

```

# Answer
`getType()` takes no arguments.

What you want to do is:

```
  if (isset($vars['node']) && $vars['node']->getType() == 'location') {
    $title = $vars['node']->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

```

That will check that the node object exists in the variables array, and getType returns location.

You could go a step further and ensure the type on the off chance that $vars\['node'\] could get set to anything not an instance of NodeInterface, which getType would not be available for and throw another error.

```
  if (isset($vars['node']) && ($vars['node'] instanceof NodeInterface) && $vars['node']->getType() == 'location') {
    $title = $vars['node']->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

```

Be sure to include `NodeInterface` with a `use` statement at the top of the file.

See more about getType().
> 4 votes

---
Tags: 8, nodes
---


# Question
Title: Creating a module arguments page with a shorter URL
I'm creating two pages with a custom the module. The first page makes an API call to create an XML object and then lists all objects. Each object contains 10 entries but i only display 3 of them. From here clicking on an object directs users to a module argument page.

Is there anyway for me to create an argument page that doesn't have 10 different entries in the URL?

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  //general page
  $items['my_module'] = array(
    'title' => 'My Module List',
    'description' => 'My module list Page',
    'page callback' => '_my_module_page',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
      );
  //single event page
  $items['my_module/event/%/%/%/%/%/%/%/%/%/%'] = array(
    'page callback' => '_my_module_arguments',
    'page arguments' => array(2, 3, 4, 5, 6, 7, 8,9,10,11),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

# Answer
> 0 votes
My suggestion is concatenating arguments by a dilemma (something like -) and in callback function explode them simply by Php Explode function.

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  //general page
  $items['my_module'] = array(
    'title' => 'My Module List',
    'description' => 'My module list Page',
    'page callback' => '_my_module_page',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
      );
  //single event page
  $items['my_module/event/%'] = array(
    'page callback' => '_my_module_arguments',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function _my_module_arguments($args){
 $items = explode("-",$args); // you can use another dilemma instead -
  //$items[0] first arg
  //$items[1] second arg
}

```

---
Tags: 7, hooks
---