title: Example for $form_state[‘rebuild’]

text:
# Question
Title: Example for $form_state[‘rebuild’]
May anyone give me an example of rebuilding the form using `$form_state['rebuild']` after user's input?

# Answer
> 5 votes
$form\_state\['rebuild'\] is used extensively in multistep forms. Take a look at the more advanced examples in the *Form Example* module in the Examples project, for example in the form\_example\_wizard.inc file.

```
/**
 * Submit handler for the "previous" button.
 *
 * This function:
 * - Stores away $form_state['values']
 * - Decrements the step counter
 * - Replaces $form_state['values'] with the values from the previous state.
 * - Forces form rebuild.
 *
 * You are not required to change this function.
 *
 * @ingroup form_example
 */
function form_example_wizard_previous_submit($form, &$form_state) {
  $current_step = &$form_state['step'];
  $form_state['step_information'][$current_step]['stored_values'] = $form_state['input'];
  if ($current_step > 1) {
    $current_step--;
    $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
  }
  $form_state['rebuild'] = TRUE;
}

```

It's used in AJAX forms, as a special case of multi-step, so you may want to look at the AJAX example.

# Answer
> 1 votes
The following example, lists two textfields for filling passenger names. If the user wants to add one more passenger (one more textfield), the form has to rebuild upon clicking the 'add passenger' button. Hope this helps.

```
function add_passenger_form($form, &$form_state){
    //$form['#tree'] = TRUE;

   if(!isset($form_state['num_names'])){
      $form_state['num_names'] = 2;
   }

   $form['passenger_fieldset'] = array(
      '#type' => 'fieldset',
      '#title' => t('List of Passengers'),
      '#prefix' => '<div id="passenger-form-wrapper">',
      '#suffix' => '</div>',
    );

   for ($i = 0; $i < $form_state['num_names']; $i++) {
     $form['passenger_fieldset']['passenger_name'][$i] = array(
       '#type' => 'textfield',
       '#title' => t('Passenger Name'),
       '#required' => false,
     );
   }

   $form['passenger_fieldset']['add_button']= array(
    '#type' => 'submit',
    '#value'=> t('Add passenger'),
    '#submit' => array('add_passenger_form_add_one'),
    '#ajax' => array(
        'callback' => 'add_passenger_form_callback',
        'method' => 'replace',
        'effect' => 'fade',
        'wrapper' => 'passenger-form-wrapper',
    ),
  );

   if ($form_state['num_names'] > 2) {
     $form['passenger_fieldset']['remove_button'] = array(
      '#type' => 'submit',
      '#value' => t('Remove Passenger'),
      '#submit' => array('remove_passenger_form_remove_one'),
      '#ajax' => array(
        'callback' => 'add_passenger_form_callback',
        'method' => 'replace',
        'effect' => 'fade',
        'wrapper' => 'passenger-form-wrapper',
        ),
      );
   }

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

  return $form;
}
/*
* add a textfield one more
*/
function add_passenger_form_add_one($form, &$form_state) {
  $form_state['num_names']++;
  // rebuild whole form with new values
  $form_state['rebuild'] = true;
}
function remove_passenger_form_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 2) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}
function add_passenger_form_callback($form, $form_state){
    return $form['passenger_fieldset'];
}

```

---
Tags: 7, forms
---


# Question
Title: What is the equivalent of user_set_authmaps()?
I need the equivalent function for `user_set_authmaps()`, in Drupal 8.

What function/method replaced it?

# Answer
As reported in {authmap} deprecation, the *authmap* database table has been removed from Drupal 8; at the same time, the functions using that database table (such as `user_set_authmaps()`) has been removed.

The suggested alternatives are:

* Write your own solution for managing user external authentication and storing remote identities
* Use the External Authentication module
> 2 votes

---
Tags: 8
---


# Question
Title: How do I make batch callbacks as class methods?
This is the code I am using.

```
$serviceClass = \Drupal::service('abcclass.service');
$batch = array(
  'title' => t('Pushing updated.'),
  'init_message' => t('Start Pushing.'),
  'progress_message' => t('Completed @current step of @total.'),
  'error_message' => t('Pushing has encountered an error.'),
  'operations' => array(
    array(array($serviceClass , 'ebook_push_single_pdf'), $node->id()),
  ),
  'finished' => array($serviceClass , 'ebook_push_finished'),
);
batch_set($batch);

```

But it doesn't work. I checked log file and I get:

> Settings can not be serialized. This probably means you are serializing an object that has an indirect reference to the Settings object. Adjust your code so that is not necessary.

Note that if I implement batch callbacks in same file, it works.

How can I fix the code?

# Answer
> 7 votes
When I use a callback function what live in a class I use, for example:

```
'finished' => array('\Drupal\my_batch\Form\MyBatchForm', 'finish_function'),

```

The same with `'operations'`:

```
'operations' => array(array('\Drupal\my_batch\Form\MyBatchForm', 'operation_function'), array($node->id())),

```

# Answer
> 2 votes
A `$serviceClass` cannot be passed through the form to a batch file like this. It has to be passed as an array of arguments inside the `operations`.

**Fixed Code is here** -

```
$serviceClass = \Drupal::service('abcclass.service');
$batch = array(
  'title' => $this->t('Pushing updated.'),
  'init_message' => $this->t('Start Pushing.'),
  'progress_message' => $this->t('Completed @current step of @total.'),
  'error_message' => $this->t('Pushing has encountered an error.'),
  'operations' => array(
    array(
      array('Drupal\module_name\Batch_file','run'),
      array($serviceClass , 'ebook_push_single_pdf', $node->id(),'import'),
    ),
  ),
  'finished' => array('Drupal\module_name\Batch_file','finished'),
);
batch_set($batch);

```

> where, "Batch\_file" is the Batch\_file.php where we get those arguments.
>
> 'run' and 'finished' are the two static functions of Batch\_file.

---
Tags: 8, batch-operations
---


title: how are user ids assigned to new users?

text:
# Question
Title: how are user ids assigned to new users?
what determines what user id to which a new user account will be assigned? On my site, Drupal 7.37, new user accounts are assigned to non-sequential user ids. All new users now have user ids well above 3500.

# Answer
There are a couple of layers here...

Any code that calls `user_save` can technically affect what ID is assigned. If the account object has a uid property, that is used, otherwise it comes from the database:

```
// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
if (empty($account->uid)) {
  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

```

So if an ID is provided, great, if not (which is the norm), it gets more complicated.

The `users` table doesn't have an auto-increment column (probably because an ID of 0 is used for the anonymous user, and there's no way to support that across all DB platforms). If you were to just get the last inserted user ID + 1, you're open to race conditions when other requests get the same ID returned before the first script has had a chance to insert the record into `users`.

Because of that, the Sequence API is used. The `sequences` table has a single, auto-incremented primary key column. When a new, unique, identifier is required, a record is inserted into that table, and the auto-assigned ID is returned to Drupal. That ensures it's not susceptible to race conditions, as the operation has already completed and any other requests would be guaranteed a new ID.

If you just need to hack around the problem you mentioned, and you're not worried about or prepared to take the risk of race conditions, add this to a custom module:

```
function MYMODULE_user_presave(&$edit, $account, $category) {
  if (!empty($account->is_new)) {
    $account->uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField() + 1;
  }
}

```
> 2 votes

---
Tags: users
---


# Question
Title: After migration, impossible to logging from the remote server, error 'You are not authorized to access this page"
(Drupal 8) From my local environment, I haven't any problem about logging with the admin user.

But after a migration from my local to my remote server, when I log with any user (and admin), I'm redirected to the user page (/user/x, x as number) but I get this error message:

> You are not authorized to access this page

If I refresh the page, I'm automatically redirected to the user login page. I don't understand why.

From my database, I see the new session when I logging. And the watchdog shows only the used connecting and then the access denied.

```
$drush wd-show

25136  27/Dec 00:18  access denied   warning   /user/1
25135  27/Dec 00:18  user            notice    Session opened for okli

```

Someone can help me?

I noticed I haven't any cookies in my browser after logging in. Maybe the issue is this, but I'm not an expert in Drupal login session.

During the migration, I changed the server configuration. Before, the website used a SSL certificate; I removed the certificate (and the website is in http). I don't think, but may the new server configuration is the source of the problem.

**UPDATE : my steps and log**

1) From the database, I truncate sessions and flood tables

2) I use firefox browser, I empty all registered cookies

3) I open /var/log/apache2/access.log, /var/log/apache2/error.log and /var/log/mysql/error.log with 'tail -f' from shells and I go to the loggin page with firefox (http://xxx.xxx.xxx.xxx)

4) I enter my admin name and password, then I submit my loggin form. I go to the access denied page :

5) My logs files display :

6) My cookie in my browser have this value :

7) My table session have one entry :

Is is normal my cookie value and database entry aren't the same ? How can/must I do for debug the loggin process and, I hope, find where is the bug ?

below, the content of my apache2.conf file :

```
Mutex file:${APACHE_LOCK_DIR} default

PidFile ${APACHE_PID_FILE}

Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

HostnameLookups Off

ErrorLog ${APACHE_LOG_DIR}/error.log

LogLevel debug

IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

Include ports.conf

    LimitRequestBody 204800
    FileETag None
    <IfModule mod_headers.c>
        Header always append X-Frame-Options SAMEORIGIN
        Header set X-XSS-Protection "1; mode=block"
        Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    </IfModule>
    RewriteEngine On
    RewriteCond %{THE_REQUEST} !HTTP/1\.1$
    RewriteRule .* - [F]

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options -FollowSymLinks -Includes -ExecCGI
        AllowOverride None
        Require all granted
</Directory>

AccessFileName .htaccess

<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

IncludeOptional conf-enabled/*.conf

```

And my /ect/apache2/sites-enabled/xxx.conf files (there is only one conf file) :

```
<VirtualHost *:80>

    ServerAdmin webmaster@localhost
    ServerName xxx.xxx.xxx.xxx
    DocumentRoot /var/www/drupalmaindir

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

        <Directory /var/www/drupalmaindir>
            Options FollowSymLinks
            AllowOverride All
            Require all granted
    </Directory>
</VirtualHost>

```

My drupal watchdog :

I don't find where is my mistake and why I can't connect to my drupal website... :/

**Note**: During the migration, I changed the apache website configuration. Before, the website used a ssl certificate (https), now I remove the certificate (and the website is in http).

# Answer
According to **kingfisher64** in "Access denied" "you are not authorized to access this page" error ???

> Just in case somebody stumbles over this issue the solution for me was in **settings.php**. I had copied a website from one domain to another and had not changed the following setting at the bottom of the file.
>
> ```
> $cookie_domain = 'newwebsitenamehere.com';
>
> ```

**Note:** notice how it does not have `http://` nor `www.` so **do not** put these.

---

**Update**: OPer commented:

> During the migration, I changed the apache website configuration. Before, the website used a ssl certificate (https), now I remove the certificat (and the website is in http).

Also, another thing to look for in **settings.php** is the `$base_url` **if it is uncommented** (does not have a # at the start) make sure it is the correct domain name (assuming you already pointed your domain name to this new server. If this server does not have a domain name pointing to it, then comment this line out) and also remove the `s` if it has https:// (since you are not using SSL).

Ex:

OR since there is no SSL, you could just comment it out, by adding a `#`.
> 3 votes

---
Tags: 8, users, migrations, .htaccess
---


# Question
Title: My custom page.tpl.php file is not picked up
I have a site running in a subdir of my main site, like www.mysite.com/drupal.

I want to use a separate page.tpl.php file for my about page www.mysite.com/drupal/about.

I have tried naming the file page--about.tpl.php and page--drupal--about.tpl.php but neither is working. It just loads the regular page.tpl.php file.

This seems really straightforward and one of those should be correct. Is this buggy because Drupal is in a subdir or am I doing something wrong?

(And yes, I've cleared the cache.)

# Answer
> 2 votes
have you seen through your theme suggestions for the about page?

If not, then please refer to it and create a tpl file according to the suggestions and you will see that particular template running for "about" page.

As of Drupal 7.33, Drupal core has a `theme debug mode` that can be enabled and disabled via the `theme_debug` variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments).

> To enable it, add this line to your settings.php:

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

```

> OR, You can enable it with drush using:

```
drush vset theme_debug 1

```

> And disable using

```
drush vset theme_debug 0

```

**Note: You'll then see output like this when you inspect or view source:**

```
<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.tpl.php
   * page--node.tpl.php
   x page.tpl.php
-->
<!-- BEGIN OUTPUT from 'modules/system/page.tpl.php' -->
…
<!-- END OUTPUT from 'modules/system/page.tpl.php' -->

```

---
Tags: 7, theming
---


title: How do I migrate an image attributes?

text:
# Question
Title: How do I migrate an image attributes?
I am migrating a Drupal 7 site to Drupal 8 using the Migrate API. So far, I have been able to do this without writing my own plugins.

How do I migrate additional information in an image field (e.g. the *alt* and *title* attributes)?

So far I have been using this, but it does not seem to work.

```
field_bild:
  plugin: iterator
  source: field_bild
  process:
    target_id:
      plugin: migration
      migration: d7_file
      source: fid
      alt: alt
      title: title

```

# Answer
> 2 votes
Here is the format I found working:

```
field_teaser_image/target_id:
  plugin: migration
  migration: attachment_image
  source: file_id
field_teaser_image/alt: file_alt

```

# Answer
> 1 votes
Here is the correct format for 8.2 and up.

```
  field_bild:
    plugin: iterator
    source: field_bild
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height

```

---
Tags: 8, migrations
---


title: Unable to save content title

text:
# Question
Title: Unable to save content title
I am using feeds to import content to my custom content type, Clients.

After the Import, the mapping comes up fine, the Content Title displays in the Page View Node, however, when I go to edit the content, the Title comes empty & also does not save the updated title.

It was working fine a few days back. I haven't made any changes or updates to any modules.

Please advice.

Thanks

# Answer
I've had something similar happen to me before. Turned out that Automatic Entity Label module was overwriting the title field with an empty token.
> 0 votes

---
Tags: nodes, feeds
---


# Question
Title: Index View donot show 'Contains' operator for (exposed) filter
I have created an indexed view, for facet search. Now I want to put a text field from which search provides a result, that contains that string from the title.

Now, title here donot have operator, 'Contains' which is required to filter matching titles.

I am using Global Populate filter as exposed filter. I tried using hook\_views\_query\_alter which donot work with index view of search api. How should we do this?

# Answer
I used hook\_search\_api\_views\_query\_alter from search\_api\_views.api.php.

```
function MYMODULE_search_api_views_query_alter(&$view, &$query) {
  // Altering the title filter to operator LIKE which is not available in the
  // views itself.
  if ($view->name = '[VIEWNAME]') {
    if (!empty($query->where[1]['conditions'][0][1])) {
      $query->where[1]['conditions'][0][1] = '%' . $query->where[1]['conditions'][0][1] . '%';
      $query->where[1]['conditions'][0][2] = 'LIKE';
    }
  }
}

```
> 1 votes

---
Tags: views, search
---


# Question
Title: How can I add a CSS class to the body tag based on the current path alias?
Is it possible in Drupal 8, to add a CSS class to the `<body>` tag based on the current path alias?

# Answer
In your theme, you can add the following code in `template_preprocess_html`:

```
$current_path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
$path_alias = ltrim($path_alias, '/');
$variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);

```
> 14 votes

---
Tags: theming, 8
---


title: Act on date field value

text:
# Question
Title: Act on date field value
I have a CT with a Date (Unix timestamp) field implemented. It represents the start date of an event.

One simply question: Is there a way to compare somehow, this value with the current date() and when it matches (equal) the current date() to trigger an action? It must be equal, other way will trigger an action many times.

Up until now I've tried in hook\_node\_view to implement the whole logic, no luck.

This hook offers no accuracy on what someone wants to do.

Cron job's aren't suitable, cron isn't running every minute or second.

The other thing I've tried was Rules, but things become complicated, thought is the best way to follow!? Any suggestions?

# Answer
> 1 votes
### Step 1 - Use VBO and Rules

You could *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* Load the VBO list of nodes that you want to be processed (ie those for which the date field matches your criteria).
* Add a loop to perform a Rules Action, for each node contained in your Views results.

For any node related data you may need in your Rules Actions, make sure that they are contained in the Views result.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

### Step 2 - Trigger the rule

Use the "Rules Once per Day" module to actually get your rule triggered. Here is how it works (as per the comment in issue 2495775, from the module owner):

* You specify a **trigger hour** on the administration settings page for this module.
* The Rule trigger will then **run when cron tasks are first run after the start of that hour**. The actual run time will depend on your cron task timings.

So this is another way to understand/read this:

* The "Event" will only be triggered when a cron job is run.
* And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

With that, you should be able to adapt the rule from Step 1 to run ... ***once a day***, on any day.

# Answer
> 0 votes
There are ways to compare the current date to a field. Views for instance can have filters that do exactly that. The correct approach will be dependent on what type of action you are trying to perform. If you can expand on this area we can help you figure out what you need to do or what hook you will need to use. For instance if you want to add content to a node on that day you could do the test in `hook_preprocess_node()`.

---
Tags: 7, nodes, rules, datetime, actions
---


# Question
Title: can we add two search form in single site?
I have a one search form which is used for all content type but i want another search form which is only for specific content type and show on specific page only. I have install the custom search module but there is no way to show that custom search module in structure block

# Answer
You can use the Custom Search module so it only searches in your specific content type.

1) Enable custom search and custom search blocks

2) Now go to `admin/structure/block` and configure `Custom Search 1`

3) Scroll down a bit and click on the blue `CONTENT` text

Then at the bottom, in `Content exclusion`, check mark the content types that you **do not** want to show.

4) In region settings, select the region you want this block to show up in.
> 0 votes

---
Tags: 7, search
---


title: Select translation: where?

text:
# Question
Title: Select translation: where?
In Drupal 7 (i18n) there is a possibility to select an existing node as a translation of another node.

In Drupal 8, is there also that possibility?

# Answer
> 4 votes
No, that was the old form of multilangual sites. This was removed in Drupal 8 in favor of entity translations.

Now every field had its own language instead of the node. This means the common properties of the node (nid, author, etc) can remain untranslated, while the values of the individual fields can be translated. (it prevents duplicate content)

So there is no way to select one node as a translation of another.

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


# Question
Title: How to reload a node page after Comment submit
I'm using AJAX Comments to allow users to submit command using AJAX. I want to refresh the page after comment is submited.

# Answer
> 2 votes
You can achieve this using below code:

```
 Drupal.ajax.prototype.commands.ajaxCommentsAfter = function(ajax, response, status) {
 try {
     location.reload();
 } catch (e) {
     console.log('ajaxComments-After: ' + e.name)
 }

```

};

# Answer
> 0 votes
Try ajaxComplete()

```
$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "ajax/use-proper-url" ) {
    location.reload();
  }
});

```

---
Tags: 7, ajax, comments
---


title: Why does this query raise an exception?

text:
# Question
Title: Why does this query raise an exception?
I am using the following code to query an ECK entity.

```
$query = \Drupal::database()->select('object__field_amount', 'f');
$query->fields('f', array('object__field_amount_value'));
$query->addExpression('MAX(object__field_amount_value)', 'maxvalue');
$query->execute()->fetchAssoc();

```

It raises the following exception.

> Drupal\Core\Entity\EntityStorageException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'maxvalue FROM object\__field\_amount f'

I've tried multiple other options, without result.

How do I avoid the code raises an exception?

# Answer
`MAXVALUE` is a reserved word in MySQL (Maria). Change `maxvalue` to `topvalue` or something else.
> 3 votes

---
Tags: 8, database
---


# Question
Title: How to set individual fields permission on content type fields based on roles using field permssion
I am using field permission module. I want some fields to be editable for other roles which I set using field permission module, but when I login as that user role I don't get the edit option on the node.

What I am actually trying to achieve is this:

1. I have created a content type with fields.
2. I want editor role users to submit pictures for that post.
3. They should not be able to edit other fields but just this.

# Answer
> 0 votes
Field permissions do not add permissions, but only take permissions away.

If a user is not allowed to edit a node, giving him the permission to edit a field won't work. Instead you must give him permission to edit all nodes (of a certain type) and deny access to all field he may not edit. (and yes that can be a struggle if you add fields in the future)

---
Tags: users, entities
---


title: Where do I place hook_cron()?

text:
# Question
Title: Where do I place hook_cron()?
I think I need to use `hook_cron()` to cause my new module to be run each time cron runs, but in what file and directory do I place this code? Is it in my new module or some other place.

Logically, it would seem that it should go some place other than my module, but I don't know where even though I've looked at documentation from various web sources. It seems like the "chicken & the egg" problem. If I put `hook_cron()` in my module how does Drupal know to tell cron to run my module? Maybe it's magic?

I'm using Drupal 8.

# Answer
All hooks by default go in the .module file, so it should go in the .module file.

It's not clear what you mean by "run my module", as modules aren't 'run', so I can't really give any more info.
> 2 votes

---
Tags: cron
---


# Question
Title: How to use webform submission data in a Rules Condition?
I want to send an email when a user fills in a webform, but only if it is our review form and if the user gave the feedback higher than a 7.

So we are asking how good we are, and the user gives us a value from 1 - 10, we want to send an email if that number is higher than 7.

Basically, I have installed the Rules and the Webform\_rules modules. Now I can make a rule with an action: 'After a form has been submitted'

Next I made the nid equal to the nid of the specific webform. And then I want make a second condition to compare the filled out value the be 7, 8, 9, or 10, so I make an data comparison condition. With the condition 'data' and the field name like: 'data:grade-value-raw' it just tells me there is no grade-value-raw

If I set the reaction to display the \[data:grade-value-raw\] on the page, it works.

Why can't I use it in the Rules Condition?

# Answer
The "clue" to what you're trying to get to work, is that you have access to all ***labels*** and all ***values*** of any field of a webform, ie:

* `[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

So in your case, you should be able to get it to work using something like `[data:grade-value]`.

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform)
* the *2nd attempt* explains what to do in case of Webform.

The above is a good start, but not sufficient to achieve your goal (= validate "*... a second condition to compare the filled out value the be 7, 8, 9, or 10, so I make an data comparison condition*", 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 (yes, "Rules Action", not "Rules Condition" ...) to `Add a variable`, with a value assigned to it equal to your `[data:grade-value-raw]` (and with a data type which is probably *integer*).
* Use the Conditional Rules module to perform the data comparison as in your question (if it is 7, 8, 9, or 10). However, in this data comparison you now refer to the value of the variable you just added (that's the clue!).

In this answer I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

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

# Answer
This doesn't answer your question directly but it's an alternative solution. You could do this without rules and just with webforms, assuming your rating in a select box.

In the emails section when editing the webform, rather than entering an email address you can select the "Component value". Choose your select box and then enter your email address for values 7, 8, 9 and 10.

That should only email if those values were selected
> 2 votes

# Answer
Add the condition in the rule using Conditional rules (rather than the conditional state itself). I've found that in many cases the conditional state of a rule can't always access the data of a form (entity forms same deal).

Create a If \[fieldname\] is greater than condition and it should work for you.
> 1 votes

---
Tags: rules, webforms
---


title: Disable cache for node body

text:
# Question
Title: Disable cache for node body
I would like to disable the cache of that specific part of the node content. Is it possible?

I'm aware I can disable the cache for the node itself using:

```
$build['#cache']['max-age'] = 0; // users
\Drupal::service('page_cache_kill_switch')->trigger(); // anon users

```

But I indeed would need to only deactivate for the body content.

Any ideas?

Thanks

# Answer
> 1 votes
The body is not cached on its own, but as part of cached nodes for logged in users or of cached pages for anonymous users. This is what you have already disabled with the code.

You can check this in the cache metadata. Render elements with cache keys get cached. If there is no cache key, then the cache tags, contexts and max-age are bubbled up and merged until they reach an element that has cache keys. This element is then cached including all merged cache metadata that is nested inside.

That means, that cache metadata you set in the body will have no effect on the body to be cached or not, but change, how elements on higher levels like the node or page are cached. For example a cache tag in the body will be included in the tags of the node and the page and if the tag gets invalidated, the cached node and page will both be invalidated.

---
Tags: nodes, 8, hooks, caching
---


# Question
Title: Include content of a block in a view template
I'm trying to create a Twig view that renders:

* Intro block
* View content
* outro block (yes, made up word for the opposite of *intro*)

The reason I'm putting these three things in one view is that I have a repeating background pattern; if each item is rendered alone, the background does not display smoothly across/through each element.

I've been trying to put this line - {% include 'block--intro.html.twig' %}, based upon block.html.twig - into the appropriate place of the view twig file, but when the page containing this view is rendered the {{ contents }} of the block is empty.

How should I be trying to do this?

I am using Drupal 8.2.4. The base theme is Bootstrap; we are using a subtheme of that.

# Answer
You can't mix different templates types like views and block templates. Every template has other variables and so the block template doesn't find the content variable in the views template context.

In your case for a View you could place the block in the header or footer in Views UI. For example a *Rendered entity - Block*.

In general you can use the module Twig Tweak instead of {% include %} to render a block template or any other entity template:

```
{{ drupal_entity('block_content', 1) }}

```

This works, because it renders the entity in its own variable scope and so you can place it everywhere in twig.

---

While entities normally render in their own template, block content is special, because it doesn't have a template on its own. So the command above only shows the fields. To get the block wrapper you need to use `drupal_block()`.
> 4 votes

---
Tags: theming, 8
---


# Question
Title: THEME_preprocess_field() not recognised in template.php
I'm using Drupal Bootstrap. Mail (password reset, user blocked etc..) from admin sends messages without preserving line breaks.

I tried this to fix this issue, but `THEME_preprocess_field(&$vars, $hook)` doesn't work for me.

# Answer
> 0 votes
Try with THEME\_preprocess\_field(&$variables, $hook), replace the **&$vars** with **&$variables**

---
Tags: entities, hooks, theming
---


# Question
Title: Get an image field of a specific size in REST API
How can i get an specific size of an image in the REST API?

I have created a view that displays as a **REST export**, the format of the view is:

* Format: Serializer
* Show: Entity

The image field is shown as:

```
field_image [
  {
    "target_id": "9",
    "alt": "Foo",
    "title": "",
    "width": "2304",
    "height": "3456",
    "target_type": "file",
    "target_uuid": "99d6732e-e9c3-4e05-be87-d2868e9f149d",
    "url": "http://mysite/sites/default/files/2016-12/foo-image-1313021.jpg"
  }
]

```

Where can I set the type of style(/admin/config/media/image-styles) that should return me in JSON format?

If I change the format by:

* Format: Serializer
* Show: Fields

It returns me the img tag.

# Answer
I ended up with the next configuration of my REST View. Not ideal but works...

FORMAT

* Format: Serializer
* Show: Fields

FIELDS

* Content: Title
* Content: Image
* Content: Data

The settings of the image field are:

* Formatter: Image
* **Image style: Max 650x650**

The post is returned as:

```
{
    "title": "Foo",
    "field_image": "<img src=\"/sites/default/files/styles/max_650x650/public/2016-12/foo-1313021.jpg?itok=UiQ2F7lI\" width=\"433\" height=\"650\" alt=\"Bar\" typeof=\"foaf:Image\" class=\"img-responsive\" />",
    "field_event_date": "2016-12-02T13:04:03"
}

```

And i apply the next Javascript function in the frontend:

```
// Get image tag source attribute
var getImgSrc = function( tag ) {
    var rex = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
    var m = rex.exec( tag );
    return m[1];
}
var src = getImgSrc( post_content.field_image );

```
> 0 votes

---
Tags: media, 8
---


# Question
Title: Adding PHP function code to a node returns Eval error
I activated the PHP filter and it works fine, except when I declare a function. I keep getting the following error.

> Fatal error: Cannot redeclare test\_function\_test() (previously declared in /web/htdocs/www.example.org/home/modules/php/php.module(80) : eval()'d code:3) in /web/htdocs/www.example.org/home/modules/php/php.module(80) : eval()'d code on line 1034

First, I tried with the following code.

```
function test_function_test() {
  echo "test";
}

```

Then, I tried using `function_exists()`.

```
if (!function_exists('test_function_test')) {
  function test_function_test() {
    echo "test";
  }
}

```

In both cases, I keep getting the same error message.

How can I use a define a function in the code passed to the PHP filter, without getting this error?

# Answer
> 0 votes
You can try adding declaration of the function in your module. But call it using php filter.

Moreover, in this case you will be able to edit code of your function with less chance of break the site.

---
Tags: input-formats
---


# Question
Title: how to override the timeline-twitter css
I embedded a feed from twitter into a block and I am trying to override the size of font by adding this to my css , but it still only picks up the css that is coming from twitter. is there any way to override this on my drupal site without logging into their twitter page?

.timeline-Tweet-text { font-size: 18px; !important; line-height: 24px; font-weight: 300; }

# Answer
In order to be able to style it, you'll need to stop using the standard twitter embed code and use another solution.

I suggest using the Twitter (https://www.drupal.org/project/twitter) and Oauth (https://www.drupal.org/project/oauth) modules for this.

This will allow you to create a view of your feed which you will be able to style easily.

There looks to be a pretty good recipe here: http://polso.info/integrating-twitter-feed-your-drupal-site

Good luck! Anne
> 1 votes

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


# Question
Title: How can I place the article date before the title?
I'm using the Basic theme and want to show the article date before the title. The problem is, that `{{ date }}` is only available in node.html.twig, whereas the title is created in page-tite.html.twig.

How can I place the article date before the title?

# Answer
> 3 votes
You can do this by implementing template\_preprocess\_page\_title() hook in your Theme (`THEME_NAME.theme`). Check example below:

```
/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function [THEME_NAME]_preprocess_page_title(&$variables) {
  // Check if page is node page, and is instance of Node.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && ($node instanceof \Drupal\node\NodeInterface)) {
    // Get created time of Node and convert to human readable, and append Node title.
    $variables['title'] = '<span class="created-date">' . date("d m Y", $node->created->getValue()[0]['value']) . "</span> " . $node->getTitle();
  }
}

```

Similar question is answered by @Linus's here.

# Answer
> 0 votes
I think, in Drupal 8 it would be not bad solution to define new block for it. In this block one get value of date field and place this block before block with node title.

How to create block programmatically, you can see in a example of module Examples.

---
Tags: theming, 8
---


# Question
Title: How to add a modal which then opens a ctools modal?
I am trying to set up a modal that opens a ctools modal from inside it. IOW the user sees the first modal, clicks on a button inside that modal and it opens a second modal on top of the first modal. Then when the second modal's work is done, it closes and user can still see the first modal.

I understand that ctools is limited to one modal at a time according to this DO issue. My second modal is a ctools modal. I tried to set up a jQuery modal and a bootstrap modal as the first modal, but closing the second ctools modal always closes my first modal.

Any pointers as to where I can find a workable solution to this?

# Answer
> 1 votes
> Any pointers as to where I can find a workable solution to this?

If you know jQuery and CSS you can create your own custom modal. Modal one has div id of `modal-1` and for two `modal-2`.

use the `z-index` css property, and make sure modal 2 is higher than 1, so it displays on top:

```
#modal-2 { z-index: 10; }
#modal-1 { z-index: 5; }

```

Use CSS to center the div, so it appears in the middle of the page, like this. Probably better to use `fixed` position rather than `absolute`, up to you.

Then with jQuery use the `.click()` function

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings)

      $( "#some-show-button" ).click(function() {
        $('#modal-1').fadeIn();
      });

      $( "#some-x-button", "#some-submit-button").click(function() {
        $('#modal-1').fadeOut();
      });

      $("#some-other-show-button").click(function() {
        $('#modal-2').fadeIn();
      });

      $( "#some-other-x-button", "#some-other-submit-button").click(function() {
        $('#modal-2').fadeOut();
      });

    }
  };
}(jQuery));

```

---
Tags: 7, chaos-tool-suite
---


title: How do I manage custom modules?

text:
# Question
Title: How do I manage custom modules?
I have planned to use Composer to manage Drupal core and third-party modules instead of pushing everything to Git and I am using drupal-composer/drupal-project to achieve it.

After running `composer create-project drupal-composer/drupal-project:7.x-dev d7 --stability dev --no-interaction`, a *d7* directory is created with some other directories, including the following ones.

* vendor
* web (It contains the Drupal core files.)

Its composer.json file is enough to install the same dependencies in another server, but if I use `composer install` in my server, how can I checkout my custom modules?

If I add custom modules and the composer.json file only in my repository, where do the custom modules go when I run during `composer install`? Do they go in sites/all/custom or the root directory?

Is there any other option available to manage my custom modules with Composer?

# Answer
> 4 votes
The contributed modules are in `web/sites/all/modules/contrib/`.

So, the suggested directory for the custom modules is `web/sites/all/modules/custom/`.

The other way to manage custom modules is to separate repository for the custom modules.

You can add your custom repositories to your `composer.json` in project root directory. Composer will look in all your repositories to find the packages your project requires. See Use PHP composer to clone git repo. Add your repositories under default `Drupal`.

After you add your repository to `composer.json` you have to tell Composer to install your custom modules to `web/sites/all/modules/custom/`. Add this line to `installer-paths`

```
"web/sites/all/modules/custom/{$name}/": ["type:drupal-custom-module"],

```

When you create your custom module, you must set type of your custom module in `composer.json` to `drupal-custom-module`.

---
Tags: 7, composer
---


# Question
Title: How to prevent certain bundled CKEditor plugins from loading
There is `hook_ckeditor_settings_alter()` to change/alter CKEditor settings. But I can't find a way to prevent certain CKEditor plugins from loading.

I am trying to achieve similar behaviors as here: https://www.drupal.org/node/2546048#comment-10188390 but that is for wysiwyg module, we don't use wysiwyg module.

# Answer
> 1 votes
We can disable CKEditor plugins by following hook as show with the example for disabling image and image2 plugins:

```
/**
 * Implements hook_ckeditor_settings_alter()
 */
function MYMODULE_ckeditor_settings_alter(&$settings, $conf) {
  // Comma separate names of plugins to remove.
  $plugins_to_remove = 'image,image2';
  $settings['removePlugins'] = !empty($settings['removePlugins'])
    ? $settings['removePlugins'] . ',' . $plugins_to_remove
    : $plugins_to_remove;
}

```

(taken from my own article: http://kb.detlus.com/articles/drupal/drupal-7-disable-ckeditor-bundled-plugins/)

# Answer
> 0 votes
CKeditor plugins are enabled/disabled directly from Ckeditor profils.

---
Tags: 7, wysiwyg
---


# Question
Title: Redirection should not lose the URL parameters
I have a rule and in condition I'm checking a path that if the current path is some path then in action I'm redirecting it to new url.

But the problem is that url has some parameters but in redirection it loses the parameters.

For example I have the following url:

```
first-url?param1=value1&param2=value2

```

and I want to redirect it to another url. But the url parameters should be append to the new url.

Is it possible in rules?

# Answer
To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.
> 3 votes

---
Tags: 7, rules, redirection
---


# Question
Title: Path is not available in Views filter criteria
I am creating a views with for node having fields **Title,Author,Created,Path(page url)**. Now how can I add exposed filter for path(page url) so that user can find the specific page content in list.

Once I try to add **Path** in filter criteria it not visible it only available in fields section.

# Answer
You can add path in Filters section if you installed views\_url\_alias module.

Please, take a look on screenshot.

I hope this helps.
> 0 votes

---
Tags: views, path-aliases
---


# Question
Title: How to override items per page in cloned view?
I have some Views page and there is a pager with 10 items limit per page. I cloned this View and I want to have 6 items per page in this cloned View, but this is not possible. Every time I try to change it, it's changed on the main View as well.

How I can override this for cloned View? Is there any way to do it programmatically somehow?

# Answer
> 0 votes
You can do this with the Views UI.

Click on `Display a specific number of items`

Then at top in **For** select `This block/page (override)`

**PS:** When you add fields, contextual filters, etc... anything under/besides a **BOLD/Bold** section, you need to do this there too, as each section has its own **For** setting.

---
Tags: views, 8, paging
---


# Question
Title: How do I remap folder to different folder in URL?
I have developed website in Drupal. There is folder(e.g., my-demo) which contains few PHP files which are developed in plain PHP. The my-demo directory is placed in the Drupal root directory.

Now I want to access this folder in a menu. If I put http://example.com/my-demo, it is accessible. I want the folder path to be like http://example.com/product-details/my-demo in the menu, without creating the product-details directory, because I have already mapped product-details to a path alias.

How can I achieve this?

# Answer
> 0 votes
Yes you can do this with remapping in .htaccess

Find this code:

```
# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

```

And add this line after it:

```
RewriteRule ^product-details/my-demo/(.*) my-demo/$1

```

So the complete version will be:

```
# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^product-details/my-demo/(.*) my-demo/$1

```

See documentation for more examples.

---
Tags: 7, navigation, .htaccess
---


# Question
Title: Why does drupal_set_message function encode all html tags?
Since I updated to Drupal 7.53 the function drupal\_set\_message does not work anymore as expected, as it encodes or strips all HTML tags. For example the code:

```
drupal_set_message("<b>This is important,</b> this not.");

```

used to print:

> **This is important,** this not

But since the update it prints:

> This is important, this not.

I could not find any change to that functions mentioned in the release messages. Can anybody explain to me what has happened?

By the way, I am using the Bootstrap theme, what was updates as well. Maybe the Theme is to blame?

# Answer
The messages added with `drupal_set_message()` are rendered in the page.tpl.php template file of the theme, if the file it is using one; otherwise, they are rendered through the template file defined from the System module.

By default, the System module and the core themes use the following code to print them.

```
<?php print $messages; ?>

```

There could be some HTML markup to wrap them, as in the Bartik theme, but that should not have the effect you are seeing.

```
  <?php if ($messages): ?>
    <div id="messages"><div class="section clearfix">
      <?php print $messages; ?>
    </div></div> <!-- /.section, /#messages -->
  <?php endif; ?>

```

The way those messages are printed has not been changed from recent updates to Drupal core, so I would check the used theme and any installed (and enabled) modules to find out what is happening.

Apart from looking the page.tpl.php template file used from your theme, you should check the implementation of `theme_status_messages()` (which is normally called from `template_preprocess_page()`) done from the theme you are using, any preprocess function for `theme_status_messages()` (`hook_preprocess_status_messages()`), and any preprocess function used for the page.tpl.php template file (`hook_preprocess_page()`). Keep in mind that preprocess functions can be implemented by any module, or the theme used for the rendered page.

As side note, it is usually better to use `t()` and its placeholders, with `drupal_set_message()`.

```
drupal_set_message(t("!important. This not.", array('!important' => '<b>This is important</b>')));

```

If you don't need to translate the message (e.g. because it is a debugging message), you could use `[format_string()][5]`.

```
drupal_set_message(format_string("!important. This not.", array('!important' => '<b>This is important</b>')));

```
> 2 votes

# Answer
The problem relies on bootstrap theme. In the 'templates\system' folder there is the **status-messages.func.php** file where the messages are altered by the \_bootstrap\_filter\_xss() function in terms of cross-site-scripting (XSS) vulnerabilities (as it described here).

You can read a similar issue here.
> 2 votes

---
Tags: 7, status-messages
---


# Question
Title: How to get the paragraph information in a custom display suite code item
I want to add a custom field for a paragraph item in display suite, but I don't know the name of variable.

I try a `print_r($entity)` and nothing is returned. How can I find out what the object name is?

# Answer
> 0 votes
> I'm using a view and want to display the first paragraph of text type and the first paragraph of data type . But only the first one . Currently they all come out in the view

In Views click on your paragraph field, mine is called "test".

Then in Multiple Field Settings, change Display to `1`

---
Tags: 7, paragraphs
---


# Question
Title: Is there a module to include translatable variables in content?
I'm building a bilingual site with a lot of content. We need to be able to edit and translate certain titles that affect many pages at once, like "Today's News" or "Sign up here." But I don't want to make them all fields on content types because there's too many of them.

Is there a module or plugin that allows you to places these variables inside the content? And allows you to edit/translate and show what pages they're on?

# Answer
Can't you wrap them in t() when fetching them?

**Note:** The author wants to be able to translate values from the variables table. I suggest a way to translate values from the variables table. No point in using contrib modules if core can do it just fine. That is, unless there are restrictions not mentioned in the original post that would make using the t() function impossible.
> 0 votes

---
Tags: 8
---


title: How to enable PHP in a field?

text:
# Question
Title: How to enable PHP in a field?
I have created a content type in Drupal 8 and I added a field named "body". But I'm unable to use PHP code in this field.

How can I enable PHP in my "body" field?

# Answer
> 9 votes
Using PHP in your body field is considered bad practice. Read: **What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?**

Even in the module page it clearly says:

> **Warning**
>
> Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site. There are better alternatives out there that do not expose such vulnerabilities on your site.

The proper way to add your PHP:

* Use a preprocess function in **theme\_name.theme** located in your theme's folder.
* Create a custom module that uses hooks or preprocess functions.

Furthermore, Twig has several filters and functions that you can make use of. Which in some cases, you don't even need to use PHP at all.

# Answer
> 4 votes
Install and configure PHP module.

> The PHP Filter module adds a PHP filter to your site, for use with text formats.

Note: The PHP filter core module has been removed from core starting with version 8.x. See also PHP filter overview.

---
Tags: theming, 8
---


title: How to render an array to twig

text:
# Question
Title: How to render an array to twig
I've a block with values in the following array structure.

```
        $block['tag'][] = $term;
        $block['image'][] = $url;
        $block['title'][] = $title;
        $block['description'][] = $description;

```

From the function build in block, I'm passing it to theme as

```
$build = [
      '#theme' => 'allofus_four_grids_block',
      '#test_var' => $this->t('Test Value'),
      '#doubles' => array('key' => $block),
    ];

```

Then inside the module, I'm passing it to twig as

```
'allofus_four_grids_block' => [
      'variables' => [
        'block' => array('key' => array()),
      ],
      'path' => drupal_get_path('theme', 'basis') . '/templates/custom-blocks',
    ],

```

And in the twig I'm iterating it as

```
{% for key,value in block %}
    Key : {{ key }}
    Value : {{ value }}
    {% for key,text in value %}
        Key : {{ key }}
        Value : {{ text }}

    {% endfor %}

{% endfor %}

```

But this is not giving me the values?

# Answer
> 1 votes
Here you declare

```
'allofus_four_grids_block' => [
      'variables' => [
        'block' => array('key' => array()),
      ],
      'path' => drupal_get_path('theme', 'basis') . '/templates/custom-blocks',
    ],

```

So you need to use the variable block :

```
$build = [
      '#theme' => 'allofus_four_grids_block',
      '#test_var' => $this->t('Test Value'),
      '#block' => array('key' => $block),
    ];

```

Not #doubles

---
Tags: theming, 8, hooks
---


# Question
Title: How to fetch views field label in hook_views_pre_render?
How to fetch views field label to modify in hook\_views\_pre\_render ?

```
  function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'mytype'){
    // Here I want to fetch the field label but I am not getting how to fetch field label
  }
}

```

# Answer
Try `$view->field[{field machine name}]->options['label']`

The `$view` object has a property 'field', which is an array of all fields set in your view. You need to select the one labeled 'Name'.

Each field is listed using its machine name as key, hence `{field machine name}` as a placeholder. You need to replace that with the actual machine name.

The field in that list again is an object, with a property 'options'. This is an array of all options, including alterations, whether the field is excluded or not, etc. In those options is also an index called 'label', which contains the field's label.
> 2 votes

---
Tags: views
---


# Question
Title: What is the purpose of modulename.api.php?
What is the basic concept behind hooks? refers to modulename.api.php.

Does this apply to Drupal 8? What is this file? Is there an example of how to code it somewhere?

# Answer
> 11 votes
An `.api.php` file contains the hooks that a certain module supports, and is available for reference.

It offers documentation and example code on how to use the hooks in other modules. It is not specific to Drupal 8 as several modules in Drupal 7 offer it as well.

It does not actually implement or call the hooks and is for reference only.

As for an example of how to write it, it depends on the different hooks your module implements. Explain the different input and return parameters, adding additional data alterations as you see fit.

search.api.php is one of many examples in core. Hooks are either invoked, as for example, in common.inc:

```
$updaters = \Drupal::moduleHandler()->invokeAll('updater_info');

```

That is the the current way in procedural code. In object-oriented terms, with Dependency Injection, refer to this example in ModuleInstaller:

```
$this->moduleHandler->invokeAll('module_preinstall', array($module));

```

There are also *alter* hooks, like this one in BreadCrumbManager:

```
$this->moduleHandler->alter('system_breadcrumb', $breadcrumb, $route_match, $context);

```

---
Tags: 8, hooks
---


# Question
Title: NID as a contextual filter doesn't work on some nodes
I have a view where the NID is getting passed as a contextual filter for a specific content type, but some nodes doesn't pass at all and for some of them there is no problem.

I've checked the database, and I can see that the node NID I am trying to expose is there, but I still can't see it in Preview with contextual filters.

# Answer
Finally I configured what was the problem. There were two referenced fields related with Relationship in view, and for those two relations I have checked the box "Require this relationship". So whenever I created content without any of those fields, content view was empty. When I unchecked "Require this relationship" boxes, everything works good. How ever thanks for your effords to help me.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Clear data stored with drupal_static() and cache_set()
I have a custom module in Drupal 7 where I am caching data from REST calls using `drupal_static()` and `cache_set()`.

```
function _mymodule_call() {
  $data = &drupal_static(__FUNCTION__);
  if ( ! isset($data) ) {
    if ($cache = cache_get(__FUNCTION__)) {
      $data = $cache->data;
    }
    else {
      $data = my_api_call();

      if ( is_object($lists) ) {
        // cache for one hour
        cache_set(__FUNCTION__, $data, 'cache', time() + 3600);
      }
    }
  }
  return $data;
}

```

I want to make an admin feature where we can specifically clear these cached values. I suppose the cache key would be `_mymodule_call`. How do I clear them from the cache?

# Answer
> 1 votes
I made a test script, and it turns out that in my code above, `_mymodule_call` is the `$cid`, because I created my cache in the `_mymodule_call` function like so: `cache_set(__FUNCTION__, $data, 'cache', time() + 3600);`.

Thanks to mpdonadio for noting that you have to specify the `$bin` argument when you use `cache_clear_all()`. In my case, since I wasn't specifying it in `cache_set()`, it defaults to `'cache'`.

Here's my script:

```
$> cat cache_test.php
<?php
// set the cache
cache_set('test_key', 'hello there ' . mt_rand(), 'cache');
$data = cache_get('test_key');
// display it
print_r($data);
// clear it
cache_clear_all('test_key', 'cache');
// retrieve it (should be empty)
$data = cache_get('test_key');
// display the emptied(?) cache
var_dump($data);
print_r($data);

```

And here's its output:

```
$> drush scr cache_test.php
stdClass Object
(
    [cid] => test_key
    [data] => hello there 1718114879
    [created] => 1482938803
    [expire] => 0
    [serialized] => 0
)
bool(false)

```

# Answer
> 4 votes
The Drupal way is to have a `$reset` parameter to your function. It would look something like:

```
function _mymodule_call($reset = FALSE) {
  if ($reset) {
    // do stuff
  }
  // ...
}

```

`node_load()` is probably the best example of this.

In your specific case, you can pass the `$reset` parameter to `drupal_static()` or explicitly call `drupal_static_reset()`. For the cache backend, you need to think whether you want to just rework the logic and just do the `cache_set()` or explicitly call `cache_clear_all($cid)` (my guess is the former).

And remember, that `drupal_static()` is only effective when you need the value multiple times *during the same request*. This does not persist between page loads (or any other HTTP request that get handled by Drupal).

---
Tags: 7, caching
---


# Question
Title: Backup and Migrate writing empty files locally
When I do either a scheduled or a manual backup, that's all I get. When I also write to NodeSquirrel, the NodeSquirrel backups are fine.

The problem started when I moved the private file folder to a level below the Drupal user "home" directory (it's a CentOS/cPanel server), to avoid these backups getting added to the overall server backup files - or so I originally thought (see below).

I've since figured out that I can exclude the files from the backup via a script. I pointed the private files directory back the original directory (one level below the web root), but I'm still getting empty files, even though Backup and Migrate sends me messages that the backup completed successfully.

I've checked permissions; I can manually write to that directory as the Drupal user (via nano). Anyone else experienced this?

Update:

Now when I back up the database ONLY, it works as expected. I actually get a compressed .sql file that looks like what I'd expect. But when I try to back up the public files directory, it reports "Public Files Directory backed up successfully to XYZ-2016-12-20T22-20-22 (444.61 MB) in destination Manual Backups Directory in 7 min 42 sec." However, this is what's in the directory:

-rw-r--r-- 1 dUser dUser 0 Dec 20 22:28 XYZ-2016-12-20T22-20-22.tar.gz -rw-rw-r-- 1 dUser dUser 0 Dec 20 22:28 XYZ-2016-12-20T22-20-22.tar.gz.info

Have altered max\_execution time in php.ini, and tried changing dir permissions to 775 and ownership to dUser:webserverUser to no avail.

Next tried drush bam-backup files. First time I got "Unable to create or write to the save directory 'private://backup\_migrate/manual'." (!!!) And drush was operating under root! So I changed permissions to 777 on the whole directory structure and the drush back up was successful, but why? It did kick out an error, though: "Error while sending QUERY packet. PID=7537 database.inc:2227".

So now I'm quite confused. Was it one of the updates I did to Drupal core? I don't believe the backup\_migrate module had an update in that time frame.

TIA for any insights or advice!

# Answer
Found out the problem: a file system quota on that particular user on the server. Drush finally gave me this clue when I ran it as the web user:

`drush bam-backup files
dm-0: write failed, user block limit reached.
file_put_contents(): Only 0 of 400 bytes written, possibly out of free disk space files.inc:411 [warning]
Public Files Directory backed up successfully to XYZ-2016-12-27T23-28-18 ( bytes) in destination [success]
Manual Backups Directory in 12 min 59 sec.
Error while sending QUERY packet. PID=19337 database.inc:2227`

Of course there was plenty of disk space, just not available to that user, and I never saw that message when running the command as root. There was enough space available to write the database backups, just not the files directory backup (600MB). Of course, BAM sent me emails saying the backup was successful. I still don't know what the error sending the QUERY packet is about, but the earlier problem of mysql crashing noted did not reappear. Also, I discovered that the web user was not the owner of the module - I forgot to change the ownership after having drush 'update all' earlier (as root); that could have caused the other problems, but the main issue was the disk quota.

In any case, drush bam-backup archive finally worked. Hope this helps someone else in the future.
> 0 votes

---
Tags: backups
---


# Question
Title: How to show paragraph bundles of different types in a view of content containing paragraphs?
I am using the Paragraphs module and I want to show the paragraphs of one type at the beginning of the view and the paragraph of a different type at the end. How do I distinguish paragraphs of different types (since the field name is the same)?

I see that they are doing it here but my view doesn't have those options : https://www.drupal.org/node/2592021

ALSO I want to be able to insert this view of paragraphs into a view of the corresponding content. How can I do that?

# Answer
You need to create a brand new view. Go to `/admin/structure/views/add`

For **Show:** select `Paragraph Items`

Once in the View, add fields, and you should be able to add `Paragraphs item: [Name]`

> but I want to see the content that has these paragraphs, not just the paragraphs

Then you will need to use Views Fields View to **embed this view as a field** in your other (node) view.

You will need to add a contextual filter of nid (to this paragraphs view).

Now in our other view (Node view) add views embed view as a field.

I think there is an option (checkbox) to automatically pass the contextual filter of your current node view to the embed view.

If not, simply add nid as a field in your node view, then when you add the view embed view field, use the replacement pattern of the nid as contextual filter.
> 1 votes

---
Tags: 7, paragraphs
---


# Question
Title: How to share fields between commerce variation types?
Assume I have more than 100 different variation products and all of them share same fields ( such as commission rate, Brand, Weight and etc). As I understood so far, I need to create 100 product variation first.

Now, my question is:

Do I need to add each of these fields for each variation separately? or is there any way to add them only one? e.g how can I add these fields to the product entity so that every time I create a variation, it automatically adds all these fields, similar to sku and price?

p.s: I use commerce\_kickstart-7.x-2.40

Any help will be highly appreciated!

Thanks

# Answer
> 0 votes
It sounds like what you're wanting to do is create a group of product variations where you only have to specifically set the unique field value per variation. If that's the case, it isn't possible. We tried to implement some sort of field inheritance model where you could set default field values for each variation at the product display level, but it never developed.

The closest thing is the Bulk Product Creation module, which does let you create a whole set of related product variations at once. I don't believe it's been integrated into Inline Entity Form / Kickstart 2.x, though, so you may want to play with it first in a development environment before trying it in your live database.

---
Tags: commerce
---


# Question
Title: Apache Solr Proximity Search and sort by Distance
I wrote a custom module to perform a search of an index I created using Search API and Search API Solr Search. The search is a proximity search that finds the closest locations using a bounding box, but I can't figure out how to SORT the results I get back by the closest. Here is my module code in entirety:

```
<?php

function s_test() {

  $index      = search_api_index_load("articles");
  $query      = new SearchApiQuery($index);

  $lat        = 41.920110;
  $lon        = -87.680433;

  //get min/max lat and long
  $check_radius = 25; // radius of bounding circle in miles
  $earth_radius = 3960;  // earth's mean radius, miles

  // first-cut bounding box (in degrees)
  $max_lat = $lat + rad2deg($check_radius/$earth_radius);
  $min_lat = $lat - rad2deg($check_radius/$earth_radius);

  // compensate for degrees longitude getting smaller with increasing latitude
  $max_lon = $lon + rad2deg($check_radius/$earth_radius/cos(deg2rad($lat)));
  $min_lon = $lon - rad2deg($check_radius/$earth_radius/cos(deg2rad($lat)));

  // set the bounding box
  $filter = $query->createFilter('AND');
  $filter->condition('latitude', $max_lat, '<=');
  $filter->condition('latitude', $min_lat, '>=');
  $filter->condition('longitude', $max_lon, '<=');
  $filter->condition('longitude', $min_lon, '>=');
  $query->filter($filter);

  // run query
  $data       = $query->execute();
  $results    = $data['results'];

  print_r($results);
}

function s_index() {
  $index      = search_api_index_load("articles");

  $index->reindex();
  search_api_index_items($index);
  print '<pre>';
  print_r($index);
  print '</pre>';
}

function test_query_menu() {
  //create the search page
  $items['test-search'] = array(
    'title' => t('Search'),
    'page callback' => 's_test',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM
  );
  //create a re-index page
  $items['test-index'] = array(
    'title' => t('Index'),
    'page callback' => 's_index',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM
  );
  return $items;
}

/**
 * Implements hook_entity_property_info_alter().
 */
function test_query_entity_property_info_alter(&$info) {
  $info['node']['properties']['latitude'] = array(
    'type' => 'decimal',
    'label' => t('Latitude'),
    'sanitized' => TRUE,
    'getter callback' => 'test_query_search_api_property_latitude_getter_callback',
  );
  $info['node']['properties']['longitude'] = array(
    'type' => 'decimal',
    'label' => t('Longitude'),
    'sanitized' => TRUE,
    'getter callback' => 'test_query_search_api_property_longitude_getter_callback',
  );
  $info['node']['properties']['latlongpair'] = array(
    'type' => 'string',
    'label' => t('LatLong Pair'),
    'sanitized' => TRUE,
    'getter callback' => 'test_query_search_api_property_latlongpair_getter_callback',
  );
  $info['node']['properties']['logo_uri'] = array(
    'type' => 'string',
    'label' => t('LOGO URI'),
    'sanitized' => TRUE,
    'getter callback' => 'test_query_search_api_property_logo_uri_getter_callback',
  );
}

/**
 * Getter callback for latitude.
 */
function test_query_search_api_property_latitude_getter_callback($item) {
  return $item->field_address[LANGUAGE_NONE][0]['latitude'];
}

/**
 * Getter callback for longitude.
 */
function test_query_search_api_property_longitude_getter_callback($item) {
  return $item->field_address[LANGUAGE_NONE][0]['longitude'];
}

/**
 * Getter callback for latitude/longitude pair.
 */
function test_query_search_api_property_latlongpair_getter_callback($item) {
  return $item->field_address[LANGUAGE_NONE][0]['latitude'] . ',' . $item->field_address[LANGUAGE_NONE][0]['longitude'];
}

/**
 * Getter callback for logo uri.
 */
function test_query_search_api_property_logo_uri_getter_callback($item) {
  return $item->field_image[LANGUAGE_NONE][0]['uri'];
}

```

Basically I exposed my latitude and longitude to Solr and used those to set the bounding box and this works find to return results close to me, but I don't see any field in the results set that would allow me to sort by the node with the closest location.

I also tried installing the Search API Location module, but I still can't find anything in the results set to sort by.

I'm using Location and Location CCK module to get the lat/long.

If anyone has experience/insight with this that would be groovy.

# Answer
> 0 votes
Assuming you are using Drupal 7, see http://tech-tamer.com/multi-location-proximity-search-in-drupal-7-with-solr/ for some ideas and code samples.

---
Tags: location, search
---


# Question
Title: How to add a custom field to a taxonomy term
I am developing a module and I would like to know how to add a field to a taxonomy term?

My section is named `special` and I want to add terms in this section

I have this code:

```
function add($form,&$form_state) {
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('name'),
        '#required' => TRUE,
    );

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

    $form['#submit'][] = 'special_add_submit';

    return $form;
}

function special_add_submit ($form, &$form_state) {
    $instance = array(
        'field_name' => 'nombre',
        'entity_type' => 'taxonomy_term',
        // This is the vocabulary
        'bundle' => 'special',
        'label' => t('Relates to option'),
        'description' => t('This is the description'),
        'required' => true,
        'widget' => array(
        'type' => 'text_textfield',
        'settings'=> array(
            'max_width'=>80)
        ),
        );
    field_create_instance($instance);
}

```

How to do that?

i create a field named `name` when i save that field i want to add the value to taxonomy term named `special`

# Answer
here is how i can do it

```
  $newterm = new stdClass();
  $newterm->name = 'fashion'; // The name of the new term
  $newterm->vid = 2; // The ID of the parent vocabulary
  taxonomy_term_save($newterm);

```
> 0 votes

---
Tags: 7, entities, taxonomy-terms
---


# Question
Title: how to make a row in a view a different style depending on the content type
I have a view with two content types. I can use views conditional to add a field depending on the content type, but how do I add a style to the entire row of content depending on the content type, for example I want content of type Article to have a class so that I can color it blue, while content of type "statistical data" will be white .

# Answer
> 0 votes
In the left top, behind format you can click the settings button. This shows you the style options dialog, where you can define a row class.

This class fields accepts views tokens (though does not provide the overview of them). So you should add a field for the content type, hide it from display if you please. Discover the token name of this field by checking the rewrite section and finally place this token in the row class field.

In my example I use the value of a php field to add row classes:

---
Tags: 7, views
---


# Question
Title: What is the equivalent of module_load_include()?
I have a good amount of experience with D7 but not much with D8, so I'm wondering about the "proper" D8 way of doing things here.

So I've got ModuleA and ModuleB

ModuleB depends on ModuleA.

I need to call a function from ModuleA inside of ModuleB.

In D7, this was done by module\_load\_include(), and D8 appears to have both this function as well as the ModuleHandler class.

I am trying to instantiate this class and use the load method, but it is throwing an error because I am passing nothing to the constructor:

$module\_handler = new \Drupal\Core\Extension\ModuleHandler; $module\_handler-\>load('ilib\_connect');

```
TypeError: Argument 3 passed to Drupal\Core\Extension\ModuleHandler::__construct() must implement interface Drupal\Core\Cache\CacheBackendInterface, none given, called in /var/www/company/web/modules/custom/ilib_sso/ilib_sso.module on line 31 in Drupal\Core\Extension\ModuleHandler->__construct() (line 109 of core/lib/Drupal/Core/Extension/ModuleHandler.php).

```

So I'm not passing anything currently to the constructor (not sure what precisely to pass), and calling the method statically is not a problem, because the load() method references its object and thus causes this error:

```
Error: Using $this when not in object context in Drupal\Core\Extension\ModuleHandler::load() (line 122 of core/lib/Drupal/Core/Extension/ModuleHandler.php).

```

So how am I supposed to use this particular class? Or should I just use module\_load\_include()?

What is the Drupal 8 way of doing things?

# Answer
> 7 votes
The answer is that the load method isn't the correct method, and there's a specific loadInclude() method.

```
\Drupal::moduleHandler()->loadInclude('ilib_connect', 'module');

```

---
Tags: 8
---


# Question
Title: Monitoring field changes in custom content type
I have custom content type with "price" field.

I would like to log the information about when the price has been changed (by administrator). All I need is date and old/new value of that field (for each entity of my custom content type).

But how to monitor such changes? Can I use any hook for it?

# Answer
### Step 1 - Detecting changes

You can make this work using the Rules module:

* **Rules Event**: Before saving content.
* **Rules Condition (1st)**: "Entity has field", whereas you should specify these values:
    + "node" (saved content) for the "data selector" of entity.
    + the machine name of your price field.
* **Rules Condition (2nd)**: Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different. For this you add an additional Rules Condition which is a ***Data comparison***. And the actual data to be compared are:

+ original value of the field, which you should be able to find/select by first using as data selector the `node-unchanged:...(unchanged content)`, followed by selecting the field name of your field from the additional list that is shown after you selected that `node-unchanged:...(unchanged content)`.
    + updated value of the field, which you should be able to find/select by first using as data selector the `node:...(saved content)`, followed by selecting the field name of your field from the additional list that is shown after you selected that `node:...(saved content)`.

### Step 2 - Logging changes

By using the Message module, you can create your custom logging of changes detected by the Rules module. For way more details on this, refer to the answer to "What is a good flexible way to send auto system emails to users?".
> 0 votes

---
Tags: 7, entities, forms
---


# Question
Title: Accidentally deleted sites/all/modules in Drupal 7
Let's say I was having a really rough day and I accidentally deleted the sites/all/modules directory in Drupal 7. Could I simply unzip my last back up of Drupal and copy that directory over to the server? Are there any other considerations or steps I should do and if this won't work, how should I go about fixing it? Thanks!

Running Drupal 7.50

# Answer
> 7 votes
Assuming the backup files you have are the same as the ones that were deleted, that should be fine.

You'll probably want to flush the cache but other than that there shouldn't be any problems in theory.

---
Tags: 7, backups
---


# Question
Title: Php Access User Data from external script
Currently my Drupal installation is at www.example.com/wiki/

I was wondering if it is possible in Drupal 8.2.4 to access the current user uid from an external php script.

The script is located at www.example.com/someScript.php

I've tried this before

```
include_once('./includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

global $user;

if ($user->uid) {
    print "Logged in";
} else {
   print "Logged out";
}

```

# Answer
You can following file authorize.php to do it like this:

```
<?php
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

$autoloader = require_once 'autoload.php';

function authorize_access_allowed(Request $request) {
  $account = \Drupal::service('authentication')->authenticate($request);
  if ($account) {
    \Drupal::currentUser()->setAccount($account);
  }
  return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
}

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->prepareLegacyRequest($request);
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

authorize_access_allowed($request);
$user = Drupal::currentUser();

if ($user->id()) {
    print "Logged in";
} else {
   print "Logged out";
}

```
> 3 votes

---
Tags: 8, users, sessions
---


# Question
Title: How to resolve 'Fields pending deletion' and force deletion of said field?
I'm stuck with an uninstallable module. Drupal insists that there are *Fields pending deletion* and that the module can not be uninstalled. I've run cron zillion times already as advised for such situations but without success. Cron runs fine, but drupal insists that still, *Fields pending deletion*.

Visiting `/admin/reports/fields` gives no clues - the fields provided by that module are not listed. I even tried using drupal console to uninstall module with `--force` switch, but also without success.

I also tried `drush field-info` in hope to get some clues, but that's apparently not yet implemented as drush `8.1.2` gives fatal error:

> Call to undefined function `field_info_fields()`.

How do I make drupal delete those fields that pending deletion? Do I have to do this manually in database?

I've seen few tables like `field_deleted_data_f5e7b87e32` or `field_deleted_revision_be01eddd10` but they are all empty. Is that even relevant?

# Answer
You could force field deletion using drush with the command:

```
drush php-eval  'field_purge_batch(500);'

```

or you could install devel module and go to */devel/php* and run

```
field_purge_batch(500);

```
> 6 votes

---
Tags: entities, installation
---


# Question
Title: Can the BaseFieldOverride class be used to implement hook_entity_bundle_info()?
I need to implement `hook_entity_bundle_info()`, and I noticed that the documentation includes a link to Finalize API for creating, overriding, and altering code-defined bundle fields. In short, that issue says that is wrong to use the `BaseFieldDefinition` class because that class marks the field as a base field, which is not true, since the field is being added to a bundle.

Can the `BaseFieldOverride` class be used to implement `hook_entity_bundle_info()`?

Doing so, the example given for `hook_entity_bundle_info()` would become the following one.

```
function hook_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $fields = [];
    $base_field_definition = BaseFieldDefinition::create('string')
      ->setLabel(t('More text'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedMoreText');
    $fields['mymodule_text_more'] = BaseFieldOverride::createFromBaseFieldDefinition($base_field_definition, $bundle);
    return $fields;
  }
}

```

# Answer
According to the issue you linked the answer is **no**:

> So, in theory, contrib modules can implement non-config-based bundle fields, but we don't provide an implementation class with which to do so.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to create a product without a variation?
I'm migrating to drupal commerce (kickstart 2) from woocommerce and contao isotope.

My biggest problem was/is understanding the terminology behind it - product types, variations, etc.

In woocommerce and isotope the product categories would be for example: \- Books \- Computers \- T-Shirts.

Each category would then have individual products in it, and each product would have optional variation.

I'm having hard time understanding this in kickstart2. More than that, is it even possible to create a product without variations? How can I create a store of simple unique products that would belong to different categories (woocommerce terminology), without variables.

For example:

* Books: product1, product2, product 3, ... (no variables)
* PCs: -- || -- ...

Thanks.

# Answer
It is - as You said - difference of terminology. The easiest way for You would be trying this: https://simplytest.me/ Here You can quickly test Drupal modules and whole distributions. Please try Commerce Kickstart with this tool and during install click to install demo content.

There You'll see that Variations are more like Categories in Your meaning: Each product display must have one or more product variations, which is why each product display type has a matching product variation type. Different product variation types have different fields, used for storing images, attributes such as color and size, as well as any other information.

And Categories are more like taxonomy - You can list colors, sizes etc there and reuse it in multiple products.

Hope i helped You a little :)
> 0 votes

---
Tags: commerce
---


# Question
Title: is it ok to manually remove menu_links entries from db?
To my surprise, I removed one menu item from the main menu, and it correctly dissapeared from the admin ui, but there still is an entry in the table called menu\_links. There is nothing unusual about the entry. How does drupal know it should not be used ? Can I manually remove it ?

The problem is, I use custom code that traverses the menu\_links table to generate an alternative menu. This custom code just sees the menu item and keeps on displaying it in the alternative menu. So, is that approach wrong ?

# Answer
The `menu_links` table contains a lot of automatically generated rows. These come from the `hook_menu()` implementation of modules. Deleting these rows will likely result in them returning on the next time you clear the cache, because menus will be rebuilt than and the systems scans through all `hook_menu()` implementations adding new links.

If you look closely at the `menu_links` table, you'll notice there is a boolean field `hidden`. A value of 1 tells Drupal not to show this item in menu's.

So you can either filter out all hidden items (you only need `hidden = 0` since the value -1 represents a menu callback), or you can have a look at the Drupal menu functions. There are a lot of functions with `menu` and `tree`, but if I am not mistaken you are looking for `menu_build_tree`.
> 1 votes

---
Tags: 7, database, navigation
---


# Question
Title: How do I submit a user registration form in code?
I have tried to save registration data in a controller.

```
$values = \Drupal::request()->request->all();

     $formBuilder = \Drupal::service('entity.form_builder');
     $form = $formBuilder->getForm(User::create(array()), 'register', array());
    $formObject = new RegisterForm(\Drupal::entityManager(),
                    \Drupal::languageManager(), \Drupal::service('entity.query'));

     $form_state = (new FormState())->setValues($values);
                //$formObject->form($form,$form_state);
     $entity = $formObject->buildEntity($form,$form_state);
     $formObject->setEntity($entity);
     $formObject->form($form,$form_state);
     $formObject->submitForm($form,$form_state);
     $formObject->save($form,$form_state);

```

Above code produces this error:

> Fatal error: \__clone method called on non-object in /home/vagrant/www/drupal8/drupal-8.0.1/core/lib/Drupal/Core/Entity/EntityForm.php on line

It seems I need to inject an "entity" before `buildEntity()`.

How did Drupal 8 manage to create a new user? Maybe the container injected that entity some where, but I am unable to find it.

# Answer
This is what I'm using for creating users. You can just use the entity\_create() part.

```
/**
 * Creates a new user account.
 * This function makes sure the account has a unique and valid user name.
 * The only case where the account creation can fail is if the e-mail
 * address is malformed or already taken.
 *
 * @param string $mail
 *   The e-mail address of the new account.
 * @param string $name
 *   The optional login name for the new account.
 *   If no value is provided, the name is derived form the email address.
 * @param string $password
 *   The password for the new account. If empty, random password will be created.
 * @param int $status
 *   The optional status for the new account.
 * @param array $roles
 *   The optional list os user role IDs.
 *
 * @return \Drupal\user\Entity\User
 *   Returns new user object.
 * @throws \InvalidArgumentException
 *   If the email address is not valid an InvalidArgumentException is thrown.
 * @throws \Exception
 *   If new unique user could not be created an exception is thrown.
 */
function mymodule_create_user($mail, $name = NULL, $password = NULL, $status = 1, array $roles = []) {
  // Make sure we have the user name.
  // If not, use the e-mail address and remove unwanted characters.
  // If the user name is provided it will be used as is.
  if (empty($name)) {
    $name = preg_replace("\W|_", '', $mail);
  }

  // Validate the e-mail address first.
  if (!\Drupal::service('email.validator')->isValid($mail)) {
    throw new \InvalidArgumentException('Invalid e-mail address.');
  }

  // Create password if it was not provided.
  $password = $password ? $password : user_password();

  // Try 20 unique user names before giving up.
  $run = 0;
  while ($run <= 20) {
    /** @var \Drupal\user\Entity\User $user */
    $user = entity_create('user', [
      'name' => $run == 0 ? $name : ($name . $run),
      'pass' => $password,
      'mail' => $mail,
      'init' => $mail,
      'status' => $status,
      'roles' => $roles
    ]);

    // Validate the object.
    $errors = $user->validate();

    if ($errors->count() == 0) {
      $user->save();
      return $user;
    } else {
      $run++;
    }
  }

  throw new \Exception('Couldn\'t create unique user within given loop limit.');
}

```
> 0 votes

# Answer
if you just want to create new user, it is easy as you create the user object and fill it and save it:

```
$user = \Drupal\user\Entity\User::create();
$user->setPassword($values->getValue('pass'));
$user->enforceIsNew();
$user->setEmail($values->getValue('mail'));
$user->setUsername($values->getValue('name'));
$user->activate();
$user->save();

```

but in my case for example I wanted drupal to do other stuff like send welcome email...etc, so what i did, instead of last step ( $user-\>save() ):

```
$formObject = new RegisterForm($this->entityManager, $this->languageManager, $this->entityQuery);
$formObject->setEntity($user);
$formObject->save($form,$form_state); // $form and $form_state can be created like you did.
// if you want to get the newly created user
$user = $formObject->getEntity();

```

on the other hand I have tried to get your code working, and the following was the outcome code:

```
$formObject = $this->entityManager->getFormObject('user','register');
$formObject->setEntity($user);
$formStateObject = (new FormState())->setFormObject($formObject);
$form = [];
$form = $formObject->buildForm($form,$formStateObject);
$formObject->validateForm($form,$formStateObject);
$formObject->submitForm($form,$formStateObject);
$formObject->save($form,$formStateObject);

```

Hope that helps.
> 1 votes

---
Tags: forms, 8
---


# Question
Title: How to purge cached content every day via cache tag?
Drupal 8 page has a day specific element which is valid for current day. I would like to add a cache tag so that it can be purged in varnish/fastly periodically. Is there a way to invalidate cache tag periodically on Drupal8?

**Here is few FAQs/As:**

1. Why can't use max-age?

max-age can be used, but it's page level header which can get quite confusing when more than one component try to set it. Cache tag is kind of self-contained to the component.

2. Why don't run cron?

Trying to avoid explicit cron/job to do this as it's environment specific.

# Answer
> 4 votes
Here is the code that flush cache on first hit of a day:

```
  public function build() {
    ...
    ...
    ...
    $this->handleCacheTag($build['#cache']['tags']);
  }

  protected function handleCacheTag(&$tags) {
    // Get the current date number.
    $current_date_number = date('z');
    $last_date_number = \Drupal::state()->get('module_name.foo.date_counter', $current_date_number);
    // If last date in settings is different from current day, invalidate
    // tags.
    if ($last_date_number < $current_date_number) {
      $invalid_tags = range($last_date_number, $current_date_number);
      array_walk($invalid_tags, function(&$invalid_tag){
        $invalid_tag = 'foo:date.' . $invalid_tag;
      });
      Cache::invalidateTags($invalid_tags);
    }
    \Drupal::state()->set('module_name.foo.date_counter', $current_date_number);
    $tags[] = 'foo:date.' . $current_date_number;
  }

```

---
Tags: 8, caching, proxies
---


# Question
Title: I need to switch from database logging to syslog
I'm running a drupal 6 website and I was thinking of speeding it up following these steps:

1. Completely stop database logging
2. Enable syslog

How do I configure Drupal to use syslog?
What if I enable just syslog and disable the database log? Do I have to further configure stuff?

# Answer
This article explains the whole process into details.

The very bottom line is activating the Syslog module (a core module), and configure it on admin/settings/logging/syslog. It should already work out-of-the-box.

To make sure you can find the log file, you can set it in /etc/syslog.conf and /etc/rsyslog.d/50-default.conf.
> 0 votes

---
Tags: 6, database
---


# Question
Title: How to get entity id of newly created entity using entity_get_controller
I am crating the new entity in drupal a below,

```
$entity = new stdClass();
$entity->type = 'entity_type';
$entity->id = 0;
$entity->title = 'Entity Title';

//Add data to fields
$entity->field_introduction = array
            (
                'und' => array
                (
                    "0" => array
                    (
                        'value' => $strIntroduction
                    )
                )
            );

     .
     .
     .
     .

    //After adding all the fields, I am saving entity as follows,

entity_get_controller('summary_report')->save($entity);

```

Entity get saved successfully. After this I want entity id for the further manipulations. How I get this newly created entity id.

# Answer
Assuming `id` is the name of your ID entity key, use this after the save:

```
$id = $entity->id;

```

You also have the option of using `entity_extract_keys` if you want to do it more generically:

```
list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

```
> 4 votes

---
Tags: 7, entities
---


# Question
Title: RouteNotFoundException thrown when trying to reroute
I am converting a Drupal 7 module to Drupal 8. The purpose of this module is to have shorter URLs which can be shared, as an alternative of /node/123 the module should send people typing /n/123 to the same content.

I feel like I am pretty close to competion but there is 1 more issue. When I try using the 'littlurl' I get this error `Symfony\Component\Routing\Exception\RouteNotFoundException: Route "node" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of C:\Users\SAMUEL\Sites\devdesktop\Module3\core\lib\Drupal\Core\Routing\RouteProvider.php).`

routing.yml

```
littlurl.node:
  path: /n/{nodeid}
  defaults:
    _controller: '\Drupal\littlurl\Controller\DefaultController::nodeForward'
  requirements:
    _permission: 'access content'

littlurl.user:
  path: /u/{userid}
  defaults:
    _controller: '\Drupal\littlurl\Controller\DefaultController::userForward'
  requirements:
    _permission: 'access content'

littlurl.taxonomy:
  path: /t/{taxid}
  defaults:
    _controller: '\Drupal\littlurl\Controller\DefaultController::taxonomyForward'
  requirements:
    _permission: 'access content'

```

controller.php file

```
<?php /**
 * @file
 * Contains \Drupal\littlurl\Controller\DefaultController.
 */

namespace Drupal\littlurl\Controller;

use Drupal\Core\Controller\ControllerBase;
use \Symfony\Component\HttpFoundation\RedirectResponse;
/*use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;*/

/**
 * Default controller for the littlurl module.
 */
class DefaultController extends ControllerBase {

  public function nodeForward($nodeid) {
    $route_parameters[0] = $nodeid;
    $options['absolute'] = TRUE;
    $url = $this->url("node", $route_parameters, $options);
    $response = new RedirectResponse($url);
    $response->send();
  }

  public function userForward($userid) {
    $route_parameters[0] = $userid;
    $options['absolute'] = TRUE;
    $url = $this->url("user", $route_parameters, $options);
    $response = new RedirectResponse($url);
    $response->send();
  }

  public function taxonomyForward($taxid) {
    $route_parameters[0] = $taxid;
    $options['absolute'] = TRUE;
    $url = $this->url("taxonomy", $route_parameters, $options);
    $response = new RedirectResponse($url);
    $response->send();
  }

}

```

# Answer
> 1 votes
These are the routes for content entities in a drupal standard install:

```
 entity.block_content.canonical                        /block/{block_content}
 entity.comment.canonical                              /comment/{comment}
 entity.contact_form.canonical                         /contact/{contact_form}
 entity.menu_link_content.canonical                    /admin/structure/menu/item/{menu_link_content}/edit
 entity.node.canonical                                 /node/{node}
 entity.taxonomy_term.canonical                        /taxonomy/term/{taxonomy_term}
 entity.user.canonical                                 /user/{user}

```

In this list the route parameter names are in `{}`. Put the parameter name as key in an array:

```
$route_parameters = ['node' => $nodeid];

```

Don't send the response, return it:

```
return $response;

```

---
Tags: 8, uri
---