title: Dropdown as an unexposed field in views

text:
# Question
Title: Dropdown as an unexposed field in views
I'm developing a complaint portal for administration. All complaints are submitted by sites users. I'm fetching these complaints using views and don't know how to add active/Inactive as drop down options in each complaint. As everybody knows complaints' status stays active until it resolves. Active/inactive field is not existed in content type form.

This is for admin ease, admin can change the status of the complaint active or inactive.

Please let know if anyone has any experience regarding this.

# Answer
> 1 votes
I have done this task. Use Field Permissions module to hide a field from user end. You can set permissions when you create or edit field. Then install editable fields and in creating views, add a field that have multi values (like list type field) and change the Format from default to editable. That's it

# Answer
> 1 votes
You can use the Field Permissions module according to module's page:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Then set permissions for your active/inactive field to be for admins only, then the field will not show for general users but admins will be able to change the status when they view each complaint.

---
Tags: 7, views
---


# Question
Title: Showing more detailed error messages to user
im making an app with titanium that connects to a drupal backend. im using the awesome library (https://github.com/jbeuckm/drupal-client).

how can i show more detailed error messages (e.g. email/username has already been taken)?

i only get a 406 error code in ios when i register a new user that has already been registered.

```
error: {"success":false,"code":406,"source":{"url":"http://domain/user/register.json","method":"POST","ondatastream":null},"type":"error","error":"HTTP error"}

```

i noticed that when i connect with android there are more detailed messages available (e.source.statusText for instance).

any ideas?

update:

in android i get the information that i would need (statusText). why cant i access it in ios?

```
error: {"code":-1,"source":{"autoRedirect":true,"status":406,"allResponseHeaders":"Date:Mon, 13 Jul 2015 10:09:47 GMT\nServer:Apache/2.2.15 (Red Hat)\nExpires:Sun, 19 Nov 1978 05:00:00 GMT\nCache-Control:no-cache, must-revalidate, post-check=0, pre-check=0\nContent-Length:259\nContent-Type:application/json\nKeep-Alive:timeout=15, max=100\nConnection:Keep-Alive\n","connected":false,"password":null,"validatesSecureCertificate":false,"tlsVersion":0,"responseText":"{\"form_errors\":{\"name\":\"The name <em class=\\\"placeholder\\\">editor83</em> is already taken.\",\"mail\":\"The e-mail address <em class=\\\"placeholder\\\">editor83@vodes.net</em> is already registered. <a href=\\\"/user/password\\\">Have you forgotten your password?</a>\"}}","username":null,"responseXML":null,"statusText":"Not Acceptable : The name editor83 is already taken. The e-mail address editor83@vodes.net is already registered. Have you forgotten your password?","apiName":"Ti.Network.HTTPClient","location":"http://editors-testdrupal.rhcloud.com/rest/v1/user/register.json","readyState":3,"domain":null,"responseData":{"height":0,"bubbleParent":true,"type":2,"mimeType":"application/json","apiName":"Ti.Blob","nativePath":null,"file":null,"text":null,"length":259,"width":0},"connectionType":"POST","autoEncodeUrl":true,"bubbleParent":true,"_events":{"disposehandle":{}}},"error":"Not Acceptable : The name editor83 is already taken. The e-mail address editor83@vodes.net is already registered. Have you forgotten your password?","success":false}
[INFO] :   ALERT: (KrollRuntimeThread) [47,17536] Not Acceptable : The name editor83 is already taken. The e-mail address editor83@vodes.net is already registered. Have you forgotten your password?
[INFO] :   [object Object]account was not created

```

**update 2:**

it seems to be more of a ecplise/android/ios issue, so ive posted the question on the main forum.

https://stackoverflow.com/questions/31381522/different-rest-object-output-in-android-and-ios

if i get an answer ill post it here as well.

# Answer
You might want to check services.alter.api.php

As described in this post

```
<?php
/**
 * Allows alteration of error data before the status code or message are returned.
 *
 * @param array $error_alter_array
 *   An associative array with the following keys:
 *     - 'code': the HTTP status code.
 *     - 'header_message': the message returned as part of the error response
 *       (for instance, "404 Not found").
 *     - 'body_data': data that was passed to the thrown exception.
 * @param array $controller
 *   The current controller definition.
 * @param array $arguments
 *   Arguments passed to the current controller.
 *
 * @see RESTServer->handleException()
*/
function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {

}

```
> 0 votes

# Answer
Coming a bit late to the party but from project page of the sandbox module REST Error Message:

> Extension for the Services module returning a JSON formatted error message instead of a WSOD with error info only through the HTTP header. In many cases this is needed by the application making the request to react appropriate. At the same time it outputs human readable output, hinting developers directly what is going on in the browser.
>
> Usage: Any code and message set with the function services\_error($message, $code = 0, $data = NULL) by the Services module or in a custom \[YOUR-SERVICE\].service.inc file is respected. That way you can provide API specific error data for your service.
> 0 votes

---
Tags: 8
---


# Question
Title: Multiple submits form and Ajax: Select which submit button is triggered
As I can't find a way to split a Drupal Commerce pane into several forms (so far it creates several field-sets) I had to create several submit buttons in the same form. But it's the same submit button that always gets triggered.

I have these 2 "forms":

```
- Field 1.1
- Field 1.2
-> Submit 1

- Field 2.1
->Submit 2

```

I believe this would not be a problem if I would not use ajax to submit the forms, but I do by using `'event' => 'click'` so that the form is submited when ENTER is pressed.

My problem is that if I press ENTER from the ***field 2.1*** it's the ***Submit 1*** that gets triggered.

**Any idea on how to select the right submit button with the click event?**

# Answer
My solution was to remove the Drupal click event:

```
'event' => 'click',

```

And to manually add it via jQuery by finding the next input button:

```
$('input.form-text', context).once('field_validation_keydown').keydown(function(event) {
  if (event.which == 13) {
    $(this).parent().nextAll('input.ajax-processed').trigger('mousedown');
  }
});

```

But if anyone has a better solution, I'm curious to know about it.
> 0 votes

# Answer
For every form element (button) add the `#name` property and it should be unique in that form

e.g.

```
$form['button_1'] = array(
    '#type' => 'button',
    '#name' => 'button_1',
...

$form['submit_1'] = array(
    '#type' => 'submit',
    '#name' => 'submit_1',
...

```
> 0 votes

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


# Question
Title: How to access List type from an option set in conditions of the Rules module?
Iam trying to access an option set(weight\_options) within which we have a List type that holds weight , represented as below

```
 "entity" : [ "commerce-line-item:commerce-product" ],
 "field" : "field_weight_options"

```

**field\_weight\_options** is a option set within which we have a **field\_weight** which is a List type that holds values like 1lb , 2lb etc

I was able to drill through till `commerce-line-item:commerce-product:field_weight_options:set-id` (which is a option set), using Data Comparison within the Rules module.

I am not able to figure out how to access the list **field\_weight** and its **values** Eg: 1lb , 2lb which are with in the option set using Data Comparison within rules module.

Any help/pointers?

# Answer
> 0 votes
These are the Rules Conditions you should use:

* ***Entity has field*** "`field_weight_options`", which is the machine name of the field you want to check.
* ***List contains item*** (for your `field_weight_options`, which is a list since it is a multi value field) and with the value (such as "`2lb`") you want to check for.

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

PS: This answer applies to D7.

---
Tags: commerce, entities, rules
---


title: Get active trails's siblings in menus

text:
# Question
Title: Get active trails's siblings in menus
I'm developing a custom theme using sub-theme just for learning purpose. In custom theme, I have added a custom block in which I need to display main menus' sub items if in\_active\_trail. I have already tried many times and wasted a lot time but unsuccessful.

1. Block **should display** when Level 1 is in\_active\_trails and it has child(s).
2. Block **should not display** when Level 1 in\_active\_trails but it has no child.
3. If any **Level 2** is current page, display Level 2 and 3 menu items expect level 1.
4. Same as ***point 3***, if **Level 3** is current page then display level 3 and 2 items.

See attached image below for more understanding what I want to do.

**Main Menu hierarchy**

# Answer
> 0 votes
Here is the solution Menu Block. Install and configure it.

It works for me.

---
Tags: 7, theming, navigation
---


# Question
Title: Set permission for a specific column in view for table format in drupal 8
I have created a view in table format and added a field as global custom text field. I want to show this field to administrator only, not to other created roles. How can I do that?

# Answer
**you need to do something like this in global php field :**

```
$uid = 1;
$user = \Drupal\user\Entity\User::load($uid);
$roles = $user->getRoles();
$v=$roles[1];
if($v == "administrator")
{
echo "your-content";
 }

```

Global php field will be available as Replacement pattern add that variable in your custom text field.
> 0 votes

---
Tags: views
---


title: Make an Inbox block for privatemsg

text:
# Question
Title: Make an Inbox block for privatemsg
## Question

I would like to make a block for printing messages from the user.

I already have a snippet of code which print me the last 5 messages, but I want to add more information like the author and the date.

## Snippet of code

```
global $user;

$query = _privatemsg_assemble_query('list', $user, 'inbox');

$list = array();
$count=0;
foreach ($query->execute() as $thread) {
  if ($count <=5) {
    $list[] = l($thread->subject, 'messages/view/'. $thread->thread_id);
    $count++;
  } else {
    break;
  }
}
 if ($list) {
  print theme('item_list', array('items'=>$list));
}
   else {
echo '<p>You still have no message yet</p>';
}

```

# Answer
Using `print_r($thread);` in your code gives this.

```
stdClass Object
(
    [thread_id] => 2
    [subject] => Testing
    [last_updated] => 1443004733
    [has_tokens] => 0
    [is_new] => 0
    [last_reply_to_mid] => 2
    [participants] => user_187,user_298
)

```

The below gives an array of the participants names.

```
    $participants = $thread->participants;
    $msg_users = explode(",",$participants);
    $prefix = 'user_';

    $authors = array();
    foreach ($msg_users as $msg_user) {
        if (substr($msg_user, 0, strlen($prefix)) == $prefix) {
        $msg_user = substr($msg_user, strlen($prefix));
        $msg_user_names = user_load($msg_user)->name;
        $authors[] = $msg_user_names;
    }
}

```

And something like the below gives the date.

```
print date("Y-m-d\TH:i:s\Z", $thread->last_updated);

```

I'm sure you can work out what to based on that.

ps. I've wanted this exact thing so thanks for the snippet :)
> 0 votes

# Answer
Niall Murphy pretty much summed up everything the OP wanted, but I was looking for the ability to also get the **body** of the message. So for those who are looking for a solution to get the body (or something else related to the thread), here's what I found.

This answer proved to be a great start: https://drupal.stackexchange.com/a/220672/61171

As described there, you can use the *privatemsg\_thread\_load()* function to load the entire thread/message array and get pretty much everything you need.

So I used the code in the OP's example to get the thread id and in the loop I loaded the thread with this:

```
$threadArray = privatemsg_thread_load($thread->thread_id, $account = NULL, $start = NULL, $useAccessDenied = FALSE);

```

You can tidy that up to fit your needs. But anyway, now if you do:

```
print_r($threadArray)

```

you will see the whole thread array and pick up what you need. For example to get the body, just go:

```
$body = $threadArray['messages'][$thread->thread_id]->body;

```
> 0 votes

---
Tags: 7, blocks, privatemsg
---


title: Store a field on a node

text:
# Question
Title: Store a field on a node
I altered the node form and added an `manage_file`-field; then, I added a callback on the `#entity_builders` property.

```
$fid = $form_state->getValue('file')[0];
$file = File::load($fid);

$file->setPermanent();
$file->save();

// $node->set('field_file', $file);
$node->field_file->setValue([
  'target_id' => $file->id(),
]);

```

However this gives me the following error:

> The file used in the File field may not be referenced.

At this point, I cannot use file\_usage, since the node is not yet saved.

How can I solve this?

# Answer
> 0 votes
Set the status of the created file to something other than PERMANENT.

So replace

```
$file->setPermanent();

```

with

```
$file->status = 0;

```

The file field will then set the status to `permanent` and add the file\_usage metadata.

---
Tags: 8, forms, files
---


title: Hide/Show fields value in nodes

text:
# Question
Title: Hide/Show fields value in nodes
I have a content type = Article. There I have 2 field. What I want is, If field 1 is empty or does not contain any value, replace this field with field 2, (with same css and html structure) else keep showing content of field 1 by default.

Is there any way to this in D8?

# Answer
Create **node--articles.html.twig** and place it in your theme's templates folder.

```
{% if content.field_name.0 is empty %}
    <div class="something">{{ content.field_name_other }}</div>
{% else %}
    <div class="something">{{ content.field_name }}</div>
{% endif %}

```

**Note:**
> 3 votes

---
Tags: 8, nodes, entities
---


title: Where is the .htaccess file?

text:
# Question
Title: Where is the .htaccess file?
I have just installed a Drupal 8 website using `drush dl drupal-8 --select`. I have rewrite issues because there is no `.htaccess` in my root directory.

Where can I find the default `.htaccess` file for Drupal 8?

# Answer
> 2 votes
If you download Drupal from here, there is the .htaccess file in main directory.

How do you downloaded Drupal source code?

# Answer
> 2 votes
I executed the command you quoted, and I got the following files. (I executed `ls -alF` in the directory where Drupal 8.3.0 was copied from Drush.)

> -rw-rw-rw- 1 kiamlaluno kiamlaluno 262 Apr 6 02:12 autoload.php
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 2309 Apr 6 02:12 composer.json
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 152480 Apr 6 02:12 composer.lock
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 6 02:12 core/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 1025 Apr 6 02:12 .csslintrc
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 350 Apr 6 02:12 .editorconfig
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 206 Apr 6 02:12 .eslintignore
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 41 Apr 6 02:12 .eslintrc.json
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 1346 Apr 6 02:12 example.gitignore
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 3671 Apr 6 02:12 .gitattributes
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 7866 Apr 6 02:12 .htaccess
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 549 Apr 6 02:12 index.php
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 18092 Nov 17 00:57 LICENSE.txt
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 6 02:12 modules/
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 6 02:12 profiles/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 5889 Apr 6 02:12 README.txt
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 1596 Apr 6 02:12 robots.txt
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 6 02:12 sites/
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 6 02:12 themes/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 848 Apr 6 02:12 update.php
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 6 02:38 vendor/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 4555 Apr 6 02:12 web.config

If you don't see .htaccess it is because files starting with a dot are normally considered hidden, and the CLI doesn't normally show those files, except when telling the command to show all the files.

Alternatively, you could run `composer create-project drupal/drupal your_site_directory 8.3.*@dev --no-dev` if you have Composer installed, which copies the following files/directories.

> -rw-rw-rw- 1 kiamlaluno kiamlaluno 262 Apr 14 11:34 autoload.php
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 2247 Apr 14 11:34 composer.json
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 152480 Apr 14 11:34 composer.lock
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 14 11:35 core/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 1025 Apr 14 11:34 .csslintrc
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 350 Apr 14 11:34 .editorconfig
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 206 Apr 14 11:34 .eslintignore
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 41 Apr 14 11:34 .eslintrc.json
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 1346 Apr 14 11:35 example.gitignore
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 3671 Apr 14 11:34 .gitattributes
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 7866 Apr 14 11:34 .htaccess
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 549 Apr 14 11:35 index.php
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 14 11:35 modules/
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 14 11:35 profiles/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 5889 Apr 14 11:34 README.txt
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 1596 Apr 14 11:35 robots.txt
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 14 11:35 sites/
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 14 11:35 themes/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 848 Apr 14 11:35 update.php
> drwxrwxrwx 0 kiamlaluno kiamlaluno 0 Apr 14 11:36 vendor/
> -rw-rw-rw- 1 kiamlaluno kiamlaluno 4555 Apr 14 11:35 web.config

In both the cases, the .htaccess file is copied.

---
Tags: .htaccess
---


# Question
Title: some images not displaying after migrating to local host
I copied a website from the server to local environment and after seeing that everything is displayed I noticed that the images in all blog posts are not being displayed. I googled this problem and found that a lot of people had it before me and tried applying their ways to solve the problem but none of them were successful for me. I think I am missing something. Please correct me if there is something I might have missed. Here's a list of things I have done

1. Compared the image paths and both are the same src="/sites/default/files/image.jpg"
2. Checked the .htaccess file in sites/default/files and no differences there too
3. Cleaned the cache

It is not a multisite and it is drupal ver 7.31

# Answer
> 2 votes
The reason you are having the problem is because you have your website on localhost/folders. And you Drupal installation expects your website to be in locahost. So there is to easy ways to solve this problem. Either you move everything up directory and all your files are in the localhost.

```
cd /Applications/MAMP/htdocs/testwebsite # Move to the website folder directory.
sudo mv * .[^.]* .. # Move everything up one directory.
cd .. # Move to localhost directory.
sudo rm -rf testwebsite     # Remove testwebsite directory.

```

Or you can created a temporary soft link on your localhost so your Drupal installation can find the sites folder on the localhost.

```
cd /Applications/MAMP/htdocs/ # Move to the webserver directory.
sudo ln -s testwebsite/sites sites/ # This is going to created the soft link .

```

# Answer
> 0 votes
just change the image paths src="/sites/default/files/image.jpg" to src="sites/default/files/image.jpg"

and it will work

# Answer
> -2 votes
You can create a virtual host in apache in the same way it was done on your server.

---
Tags: media, migrations
---


# Question
Title: How to execute hook_cron after a rule with event Cron maintenance tasks are performed?
I have a `rule` with event `Cron maintenance tasks are performed`.

It is executed when a cron run.

I have implemented `hook_cron` in my custom module and I want this hook\_cron should be run after that rule is executed.

But the problem is my `hook_cron` executed first and then that `rule` is executed.

Is there any way to run my `hook_cron` after that `rule`?

# Answer
> 0 votes
You can adjust the weight of your module so that it gets executed after Rules.

See this question for more details.

---
Tags: 7, rules, hooks, cron
---


# Question
Title: Use the same login credentials with different core versions
I have a Drupal 7 site, and I createda new Drupal 8 site. I would like to use the login credential from the Drupal 7 site in the Drupal 8 site.

How can I achieve this?

# Answer
> 0 votes
You could set up the existing Drupal 7 site as an OAuth provider and then set up the Drupal 8 site to allow for OAuth logins and then you could share credentials between the sites.

You won't get any sync for free but at least you wouldn't have to enter the password again.

---
Tags: 8, authentication-authorization
---


# Question
Title: How to display node image in page header for custom theme?
I'm extending the Tweme theme (a Bootstrap subtheme) and I want the "banner\_image" field on the node page to be displayed in the header.

The page.tpl.html template from Tweme has the markup for the header, but this doesn't work because (I believe...) that template doesn't have access to the `$content` variable:

```
print render($content['field_review_nationality']);

```

The node.tpl.html template *does* have access to `$content`, but the header isn't present in that template.

Where/how do I render my "banner\_image" field?

# Answer
You can find @var `$node` on page.tpl.php. you can display your field using this code.

```
<?php
if(isset($node->field_review_nationality) && !empty($node->field_review_nationality['und'][0]['uri'])) {
   <img src="<?php print file_create_url($node->field_review_nationality['und'][0]['uri']); ?>"/>
}
?>

```

If you have a style of the image then you can display using below code.

```
<?php print theme('image_style', array('path' => $node->field_review_nationality['und'][0]['uri'], 'style_name' => [STYLE NAME])); ?>

```
> 1 votes

---
Tags: 7, theming, entities
---


# Question
Title: Render Custom Menu Block from Menu Tree Array of Links Programmatically
**Here's what I have:** A custom menu (side nav) that mimics the main/secondary menu tree which shows the entire subtree of the root menu item (Dine, Play, Stay) you're under.

This sidenav can be shortened with a checkbox field in the content type. If checked, the sidenav shows the checked page as the root and all children, recursively, but omits any parents of the checked page. I've successfully created that menu and this all works on the checked pages.

This yields:

This is done by creating both menus, then adding a "hide" css class to one of them in the template\_preprocess\_page() function, depending on the checkbox of the current node.

**MY ISSUE:** The final thing I need it to do is when you are on a CHILD page of a parent with the shortened nav checked, I need it to still show that shortened nav. So on the example above, when on the Visitor FAQ page, it needs to show the shortened menu from Visitor Tips (with the current page bolded or whatever). So it needs to grab the field from the parent node, and if it is true, grab the shortened submenu array, which I've done, but I haven't been able to render the menu tree array into html correctly.

Here's the current code for grabbing the submenu (from the full menu), and it saves the menu array in `$alternateSecondaryMenu`. I also tried saving in $vars\['secondary\_nav'\], which is the key Drupal uses for the rendered menu array, but I think the menu has already rendered by the time it calls preprocess\_page(). I just can't figure out how to render that menu tree. (The menu is 4 levels deep, level 0 being the root menu item, so this only happens on level 1 or level 2.)

**In template.php:**

```
function THEME_preprocess_page(&$vars) {

  // Follow active-trail and check if short/long menu is toggled
  // ***********************************************************
  if(!empty($vars['secondary_nav'])) {

    // Level 1
    foreach($vars['secondary_nav'] as &$topmenuitem) { // for each top level item
      if(!empty($topmenuitem['#title'])) {
        if(in_array('active-trail', $topmenuitem['#attributes']['class'])) { // check if in active-trail (parent)

          // load the node of the parent menu item
          $firstnid = str_replace('node/','',$topmenuitem['#href']);
          $firstnode = node_load($firstnid);

          // check for shortened menu checkbox
          if (array_key_exists('field_show_menu_as_parent',$firstnode) && $firstnode->field_show_menu_as_parent && $firstnode->field_show_menu_as_parent['und'][0]['value']) {

            dsm("1. YES, shortened menu.");

            // Saving this submenu in these variables
            $vars['secondary_nav'] = $topmenuitem; // this is the drupal-made array that shows the menu in question
            $alternateSecondaryMenu = $topmenuitem; // just saving to some other variable, too.

          } else {
            dsm("1. NO shortened Menu for you!");
          }

          // Level 2 (same as level one)
          foreach($topmenuitem['#below'] as &$secondmenuitem) {
            if(!empty($secondmenuitem['#title'])) {
              if(in_array('active-trail', $secondmenuitem['#attributes']['class'])) {
                $secondnid = str_replace('node/','',$secondmenuitem['#href']);
                $secondnode = node_load($secondnid);
                if (array_key_exists('field_show_menu_as_parent',$secondnode) && $secondnode->field_show_menu_as_parent && $secondnode->field_show_menu_as_parent['und'][0]['value']) {
                  dsm("2. YES, shortened menu.");
                  $vars['secondary_nav'] = $secondmenuitem;
                  $alternateSecondaryMenu = $secondmenuitem;
                } else {
                  dsm("2. NO shortened menu for you!");
                }
              }
            }
          }
        }
      }
    }
  }

  dsm(drupal_render($alternateSecondaryMenu));
  // Only renders an <li> of the current node, not the <ul> or the children <li>, even though it has the whole menu tree.
  dsm($vars['secondary_nav']);
  // doesn't render anything because this preprocess_page() is called after the elements of the page have already rendered, right?
}

```

I am using Panelizer to display and Menu Block to create the menu (only modules that ones that might be relevant).

Do I need to call the theme\_menu\_tree() and theme\_menu\_link() functions on this array again to render it, somehow? I wasn't able to get render() or drupal\_render() to work. Also tried doing this with menu\_preprocessing/tree functions but was having difficulty getting the checkbox value in the nodes. Any ideas or help would be GREATLY appreciated.

Thanks!

# Answer
> 0 votes
This is sort of a hackish solution but probably the easiest to set up. I would suggest rendering the every level in the entire menu tree the same in all locations. You can omit the parents by deleting them in jQuery.

Based upon the location URL pattern or other criteria (for example your boolean checkbox could affect the body element class) you can pick the chunk of the menu you want to use at jQuery.ready time on the client side.

If the element is initially set as 'display: none;' then you can do this cherrypicking and then show the element. (In some recent cases I found it easier to get the menus into shape this way on the client side than fighting with different rendering parameters. The end result is about the same and it is easy for PHP to generate the same menu everywhere quickly).

---
Tags: 7, theming, hooks, panels, navigation
---


# Question
Title: How to work with caching and conditional rendering in a template?
I've added a custom module function to allow the `is_front` conditional to work inside of a block template. The purpose is to display the site slogan on the homepage, but not across the rest of the site. The rule works correctly, but the site's cache is causing it to render incorrectly. If I clear the cache from the front page, the slogan displays sitewide. If I clear the cache from another site page, then the slogan doesn't display on the front page.

I'm presuming it is because the block's display is being cached in some way. Is there a simple way around this other than adding a second instance of the block?

# Answer
> 1 votes
Here are some solutions I can think of:

**Solution 1: Use CSS (easiest)**

Make sure the slogan has some classname you can refer to. Example: `site-slogan`. Use body classes to change slogan visibility. Here's some rough CSS to get you started.

```
/* Hide slogan for all pages */
#block-site-branding .site-slogan {
  display: none;
}
/* Show slogan for front page */
body.path-frontpage #block-site-branding .site-slogan {
  display: block;
}

```

**Solution 2: Use 2 block instances (not recommended)**

* Setup one block instance, say `block-site-branding-front` for the home page and configure it to show the slogan. Make this block visible only for `<front>` page.
* Setup another block instance, say `block-site-branding-inner` for the inner pages and configure it to hide the slogan. Make this block visible for all but `<front>` page.

You can also define a custom block in a custom module, but that would be an overkill. I think the first solution should do the trick.

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


# Question
Title: How do I migrate data (nodes, users, and images)?
What is the best way to migrate the following data from Drupal 5 to Drupal 8?

* Nodes (different content types)
* Nodes with images
* Usernodes (this is a special node type in Drupal 5)
* User accounts
* User profiles
* Images (special content type)

I want to setup a total new installation of Drupal 8 and then import the data from my old Drupal 5 site (which is still online).

There are a lot of migrate modules (in Drupal 8 Core) and other helpful modules (e.g. feeds, node import), but I do **not** want to migrate data with 2 steps.

What is the best way to migrate the data directly from the Drupal 5 database into my Drupal 8 installation?

Thank you.

# Answer
> 2 votes
To do this, you will require some coding skills (or maybe you can hire a programmer). You might have to do one or more of the following:

I don't know if there exists any way to do an easy D5 \> D6 migration? If yes, then consider migrating your data to D6 first and then use the D8 core migration modules to import the D6 stuff into D8. Good luck!

---
Tags: 8, migrations, upgrading
---


# Question
Title: How to logout a specific user programatically?
I need to logout a specific user programmatically whose uid is known to me.

I think I need to destroy the session. Is there any table in drupal store that value?

# Answer
Use drupal\_session\_destroy\_uid function.

> Ends a specific user's session(s).

Example:

```
drupal_session_destroy_uid($uid_to_logout);

```
> 5 votes

# Answer
I used

`\Drupal::service('session_manager')->delete($uid);`

for D8
> 1 votes

# Answer
You can condition in this code to logout user

```
// Programmatically logs out the current user
global $user;
$tmp = NULL;
session_destroy();
user_module_invoke('logout', $tmp, $user);
$user = drupal_anonymous_user(); //or any user you get from database

```
> 0 votes

---
Tags: users
---


# Question
Title: How do I get the node ID from the taxonomy term ID?
In Drupal 7, we are using `taxonomy_select_nodes()` to get a list of nodes using a taxonomy term.

What is the equivalent in versions after Drupal 7?

# Answer
> 1 votes
Use loadByProperties():

```
$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties(['field_tags' => $tid]);

```

---
Tags: nodes, taxonomy-terms
---


title: Multilanguage page title

text:
# Question
Title: Multilanguage page title
I've created a multilingual drupal page (English as default and german). On the english page the title works correctly, but on the german page the title is still Drupal (I changed it in the settings and it works in my browser tab header)

How can I make it work?

supermew

# Answer
> 0 votes
Here are a few pointers which might help:

* If you are talking about the name of your site, then please use the *Admin \> Configuration \> System \> Site information* page to configure it - once in English and once in German.
* If you are talking about a *page* node you created, then:
    + Make sure that you enable translations for the *title* property from content translation settings.
    + Make sure you use the *Translate* tab on the node to input the German title for your page.
* Having done everything above, if you still do not see the German title on the German version of your page, try clearing cache from the *Configuration \> Development \> Performance* page.

**References:**

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


# Question
Title: How to edit misc/print.css without changing core
I want to edit core/misc/print.css that the Book module is referencing, and I don't know how.

If I should move the print.css somewhere and load a new print.css in my theme.info, or is there another way make changes to the core/misc/print.css without changing core?

# Answer
You don't need to edit any core file, to achieve what you are trying to do. Since you are talking of a theme, you just need to replace the template file used from the Book module. This is what done from the Stable theme, which has its own book-export-html.html.twig.

The only reference to the misc/print.css file is in book-export-html.html.twig; there isn't any core library with a reference to that file, and this makes things easier for a theme.
book-export-html.html.twig contains the following code.

```
  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
    <link type="text/css" rel="stylesheet" href="misc/print.css" />
  </head>

```

In the template file for your theme, you just replace it with the following, if you don't want to use any print.css file.

```
  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
  </head>

```

If you just need to use a different print.css file for your theme, then you can simply edit the file path, and provide your own CSS file.

```
  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
    <link type="text/css" rel="stylesheet" href="the_path_relative_to_the_theme_folder/print.css" />
  </head>

```
> 4 votes

---
Tags: theming, 8
---


# Question
Title: How to make sure no emails go out after importing users?
I'm creating a new Drupal site and importing users from our existing website. I want to make sure users don't receive any email notifications of any kind from our new website during this process. What things should I check to ensure this?

I am using Drupal 7.54.

# Answer
> 2 votes
You can turn off user mail on registration in account settings.

/admin/config/people/accounts

or if you'd like to see what is being sent by the system, but not have it go out to your users checkout the MailLog module. We use it to test email functionality during development. It has a checkbox to turn off all mail going out from your Drupal site.

# Answer
> 3 votes
You can use the Development Environment module for this. Some more details about it (from the project page):

> When developing Drupal sites, we are often working in a development environment in which we want behaviors different than we would like on a production environment. An example of this is sending emails - it's often preferable to not send emails from a development environment, as they can end up in our client's email boxes. This is particularly true when there is a production (live) version of the site on the web, as users may receive emails from your development environment, which will be both confusing, and any links to the site within the emails will be unusable by anyone without access to that development environment.
>
> This module aims to provide various settings which are specific to development environments only.

Disclosure: I developed this module.

# Answer
> 2 votes
You could use the Reroute Email module. From its project page:

> This module intercepts all outgoing emails from a Drupal site and reroutes them to a predefined configurable email address.
>
> This is useful in case where you do not want email sent from a Drupal site to reach the users. For example, if you copy a live site to a test site for the purpose of development, and you do not want any email sent to real users of the original site. Or you want to check the emails sent for uniform formatting, footers, ...etc.

---
Tags: users, migrations, emails
---


# Question
Title: How can I add special classes to only all blocks that's generated in certain region?
I want to add some classes to each block that generated in custom region automatically.
For example I want to all blocks that generated within sidebar-left have some special classes and in addition I don't want to those blocks in other regions have those classes.

I try to use something like below code to add desired class to each block that's generated in sidebar-left:

**region--sidebar-left.html.twig**

```
{%
  set classes = [
    'region',
    'region-' ~ region,
  ]
%}
{% if content %}
  <div{{ attributes.addClass(classes) }}>
    {{ content }}
  </div>
{% endif %}

```

But it seems there isn't any loop functionality Like below to I can use for each blocks and add my desired classes to them:

```
{% for item in items %}
  <div class="my-desired-class">
    {{ content }}
  </div>
{% endif %}

```

# Answer
I am afraid this is no longer possible, according to Region-specific block templates are not available in Drupal 8.

> In Drupal 7 it was possible to specify separate block templates per region, such as block--header.tpl.php and block--footer.php to output different HTML for blocks placed in the header and footer regions. It was also possible to adjust variables based on region in hook\_preprocess\_block(). Both of these features have been removed.
>
> It is suggested you use standard CSS cascading selectors to style blocks differently on different parts of the page.

Therefore, you have 2 options:

1) In your **page.html.twig** you add a parent/wrapper class or id

```
{% if page.sidebar %}
    <div class="my-sidebar">
       {{ page.sidebar}}
    </div>
{% endif %}

```

Then in CSS use your parent/wrapper to style your blocks `.my-sidebar .block { border: solid red; }`

2) Individually create a **block--block--\[id\].html.twig** for each of your sidebar blocks and add `my-desired-class` here.
> 6 votes

---
Tags: theming, 8, blocks
---


# Question
Title: Create a view with mix of content and files
Is there a way to create a view that will allow showing listing of two entity types, for example combine items from the *Content* and *File Entity Files* views?

Lets say we wish to show a listing of all content belonging to a user. We create a view for Content entity, then add user as a required relationship, but this does not show the file fields to be added to the view.

# Answer
Thats tough to answer without a little more information.

It depends on whether or not they share anything in common. Views over on the right hand side of the UI has a menu for what are called relationships. You could for example setup a content type based view and then add a relationship to the user who created the content type node. After the relationship was created you'd then have access to information stored (fields) on the user as well as the fields from the content type itself. What these relationships are doing behind the scenes in views is setting up SQL joins between the various tables in your Drupal database.

Another thing you might want to look into is entity references and taxonomy tags. Both of those can be used to setup connecting points between pieces of content that can be rendered by a view much in the same way.
> 2 votes

# Answer
You could use SearchAPI module.

> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine.

With this module you can creare an index with different entity types (nodes, terms, users, files) and show them in a view.
> 1 votes

---
Tags: views, 8
---


# Question
Title: Are there conditions where invalidated cache items are returned?
Why do we invalidate cache tags instead of clear cached items with those tags? Under what conditions would the invalidated cache be returned?

# Answer
> 3 votes
See my presentation on Drupal 8 Caching about that topic: https://md-systems.github.io/drupal-8-caching/#/6/6 for how you can still get invalid items. And https://md-systems.github.io/drupal-8-caching/#/6/5 on how cache tag invalidation works.

The reason why cache tags invalidate instead of delete is scalability. Invalidating a cache tag does not require us to touch each single cache entry, we just need a single update query to increase the invalidation counter that is checked when cache entries are loaded. Common cache tags like renderered, image style cache tags and other frequently used cache tags could be on tens or hundreds of thousands of cache entries, deleting them all at once would take a very long time on MySQL and other cache backends like Memcache have no API to do do something like that at all.

---
Tags: 8, caching
---


# Question
Title: get timestamp of most recent comment of an article
I need the date of the last created/updated comment of an article. Are there any API functions in drupal 8 like node-\>most\_recent\_comment ? Or do I have to check every comments date of a node in a loop?

EDIT - Solution:

```
$node->comment->last_comment_timestamp;

```

Note that you'll have to change -\>comment to the actual field name of the comments on your node.

# Answer
As @IvanJaros pointed out the comments statistics are stored in a database table. You don't need an API function to get them. The comment module does this for you and places them in the field while loading the node from storage:

```
function comment_entity_storage_load($entities, $entity_type) {
  ...
  // Load comment information from the database and update the entity's
  // comment statistics properties, which are defined on each CommentItem field.
  $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
  foreach ($result as $record) {
    // Skip fields that entity does not have.
    if (!$entities[$record->entity_id]->hasField($record->field_name)) {
      continue;
    }
    $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
    $comment_statistics->cid = $record->cid;
    $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
    $comment_statistics->last_comment_name = $record->last_comment_name;
    $comment_statistics->last_comment_uid = $record->last_comment_uid;
    $comment_statistics->comment_count = $record->comment_count;
  }
}

```

So you can access the statistics directly from the node field:

```
$node->comment->last_comment_timestamp;
$node->comment->last_comment_name;
$node->comment->last_comment_uid;
$node->comment->comment_count;

```
> 3 votes

# Answer
I think you can do this:

```
$node->get('field_comments')->__get('created')->value;

```

Note that you'll have to change `field_comments` to the actual field name of the comments on your node.
> 0 votes

---
Tags: 8, comments
---


# Question
Title: How to implement a searchable addresses database (for a form)?
I'm not sure if I should ask this type of question in this site, but I already tried to ask in the Drupal forum here with no reply so far.

I'm trying to find out the best way to implement a solution in an existing Drupal 7 site that must meet the following requirements:

1. a option to import addresses to the database from a csv/xls file, with:
    * fields: id, city, locality, street, street-number, postal code
    * around 100000 records/addresses
2. a form that include a address section/field(s) with a search functionality to search the addresses
    * where the user would fill up some of the address fields (ex: city, street; or just street)
        + and it would show a list with the matched addresses
        + that would be sorted by relevance
            - for example: is more relevant if it's found in both "street" and "city" fields, than only in the "street" field (ideally it would be nice to replicate the google maps search)
3. a option to export the submitted form values to a csv/xls (if this is too of topic, just ignore this step (3)) (The site is on a Drupal 7, with mysql 5.5, and php 5.5)

Previously the client had tried to implement the import requirement, but it was to slow (a few days just to load the csv file), using the feeds plugin and a taxonomy structure to save part of the address fields.

I'm relatively new to Drupal backend development, mostly frontend, theming (templates with html, js, css/sass, and just a bit of php) in Drupal and doing some simple forms in backend, but I have some MySQL and PHP background.

So I was thinking in building a module to:

* create database tables of:
    + addresses (fields: id, city, locality, ...)
    + addresses\_searchable, where it would have addresses strings fields, by converting the strings:
        - to lowercase
        - replacing non-latin text to US-ASCII (ex: "á", "à" to "a")
        - in order to help speeding up the search
            * when using "like" in Drupal database search api
    + form\_submitions (fields: id (of the submitted form), name, ... (other form fields) , adress\_id)
* create a form . using ajax to load the search addresses list by pressing a button
* set up a backend page (using permissions) for the import and export pages
    + import:
        - include a button to load addresses file (csv/xls), and other to run latest loaded file, and show a progress bar, and a log with possible errors
    + export:
        - using a button to download all form submissions up to now, or up to / after a selected date

From what I researched so far:

* for reading files:
    + xls: could use the Drupal module phpexcel
    + csv: by using PHP native functions
* to search the addresses:
    + by checking the Drupal api,
    + there is a Search API module that maybe would be the way to go
        - I haven't used it before, but maybe it would work if i create a entity for the address with the matching fields. Would be faster that a dedicated table?
        - in case it's better this way maybe, i could still use the address table as a temporary table, just to speed up the importing of the csv/xls addresses file

I'm not sure if this is the best approach to the problem, and what are the best practices to implement this in Drupal 7. Or even if it is something that should other solution/framework like for example:

* use something like Laravel (v5.4) (which i also would have to learn), and load the forms in Drupal 7 through a iframe that would show the form from the other server and framework.

I've searched Google but I’m still a bit confused. Can someone point me in the right direction?

# Answer
> 2 votes
My first approach would be to build a basic importer using the BatchAPI and create a custom entity to hold the address data (NOT a content type), combined with Address Field for proper storage.

Then, I would use Search API and Search API Solr to index and store those entities, afterwhich you can build custom forms with Form API or use Views to expose and search the index - which will be much faster than Drupal db queries. Whenever possible, keep MySQL from doing work, as this is what will bog down your site.

This keeps things close to "Drupal native" while solving many of the performance issues you raised with Solr.

You can use Form API to build forms with #ajax callbacks to query and return data from Search API queries as well.

The import will never be lightning fast unless you're not using the Drupal API to store them as entities. When you don't store them as entities, you lose a lot of the flexibility of say, plugging into Views or Search API without a decent bit of work. You couldn't also add fields with field API, at that point it's just flat data, so say goodbye to easy addition of taxonomy fields or using Address Field.

With Solr constantly indexing new and updated entities, having the import be lightning fast isn't really a priority (IMO) as long as it is reasonable. If you have millions of addresses, Drupal will only be able to parse rows so fast, and a lot of this is due to the event system (save an entity, fields attach, hooks fire, alters fire, etc) on every call to `entity_save`. The price you pay in speed here is paid off later when you want to manipulate or integrate that data with the contrib space.

The gist I linked to was an experiment I was doing with the Data module and CSV files. This loads the entire CSV file and dumps its contents into MySQL using load infile. This will plant data into a database very quickly, but, as I said, you will have a lot more work trying to get Drupal to recognize, communicate with, and extend that data.

Another approach, totally non-Drupal, would be to import the data to a PostgreSQL (9.4+) database or a no-SQL equivalent, possibly even something like Firebase, and execute searches against that. Then again, this is almost the same as doing Search API + Search API Solr, except you'd have to build the wrappers to create and send queries to those servers. So, it is still valid to offload all of this work in a separate system just to crunch data. It really depends on how much programming you feel like doing.

Just to be clear, there are a handful of options here, it just depends on how much you can stomach if it doesn't use Drupal in some way. Personally, I would not want to give up the flexibility the Drupal API provides in terms of understanding your data model, and therefore, I would create a custom entity and start there. It will be slower, but in the end provide more points of integration for you in the module ecosystem.

# Answer
> 0 votes
A possible approach is to just import your data in a MySQL database (one or more tables, up to your ownn imagination). And then use the Forena module (disclosure: I'm a co-maintainer) to build whatever reports (and/or charts) related to those data.

To really make it fency, you could combine this also with DataTables, e.g. to implement it's typical search facilities that come with it.

On top of that, you can export data via Forena to any of the typical formats, such as CSV, XLS, etc.

PS: another variation is to not even import your data, and just have Forena access your existing data from within Drupal. All that's needed for this to work, is that your data base format is supported by Forena (such as PDO compliant, Oracle, MS SQL, SQLite, MySQL, etc).

---
Tags: 7, entities, database, search, performance
---


# Question
Title: How to display a field only if option (x) isn't selected
In one of my content types, I have a **Status** field *(field\_status)* which is a **List(text)** field displaying 3 radio button options set to the following key|label values:

* 0|In Stock
* 1|Under Deposit
* 2|Sold

I have a custom twig template file for this content type and was wondering how I would display the value if the option isn't 0 (In Stock). In Stock is pretty much the default option so when the item is sold/under deposit, I want a "Sold/Under Deposit" banner to appear in the upper corner of the picture of the item.

Also, I have a view displaying a list of these content types so how would I only show this value again if the selection isn't "In Stock". I don't have a custom template for the view as I did it all in the UI so I'm hoping there's a way to do this there as well.

I feel like this should be a simple solution but for some reason I'm having issues with it.

I figured it would be something like the following but this doesn't seem to work:

```
{% if field_status is not ['0'] %}
  {{ field_status }}
{% endif %}

```

I'm assuming my syntax is wrong. What would be the proper way of doing this?

# Answer
> 0 votes
Ok, so I knew I was overthinking my issue. The way I got this to work for me was the following:

In a pre-process function I created the itemstatus variable with the following code:

```
function THEME_preprocess_node(&$vars) {
  $vars['itemstatus'] = $vars['content']['field_status'][0]['#markup'];
}

```

And then just applied it to my twig template like so:

```
{% if itemstatus != "In Stock" %}
  <div class="corner-ribbon">
    {{ itemstatus }}
  </div>
{% endif %}

```

# Answer
> 0 votes
Create a file in template folder : node--articles.html.twig

```
             {% if content.field_gif_image|render is not empty %}
             <div class="field-image-wrapper article-gif">{{ content.field_gif_image }}</div>
             {% elseif content.field_image|render is not empty %}
             <div class="field-image-wrapper">{{ content.field_image }}</div>
             {% endif %}
             {{ content.body }}
             {{ content.field_more_on }}

```

Fields defined are just for reference, hope It can give you a clue of how to do this.

---
Tags: theming, 8
---


# Question
Title: Why date field is picking the user's timezone?
I have a date field with default value set to `now`. I have selected the `site's timezone` in the date field settings.

So for every user the date field value should be according to the `site's timezone`. But on node forms I can see the date field value is different for every user according to the timezone set on that user profile form.

Why the field value is not according to the `site's timezone`. it should be same for all the users.

If I disable this settings `Users may set their own time zone` in the regional settings then every thing works fine.

Is there any configuration I'm missing?

# Answer
In Drupal, dates stored in the DB do not have any timezone fixed to them; it presumes all date fields are consistent in timezone and relies on the system's timezone setting to offset everything to its correct date for displaying.

There are two different offset settings: the field's timezone settings (which adjust from user's timezone input to the site's timezone) & the user's timezone setting which adjust display from the site's timezone to the user's timezone.

Needless to say, the various offset settings can make for a confusing situation to adjust to your needs.

If you want to keep the field adjusted to the site's settings **and** have the users still adjust for their own time zone, you should customize the display of your field so the time zone is presented in an unambiguous format.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: How to print YAML form in custom block under drupal 8
The accordion section was created in custom block under drupal 8. And I want to show yaml form in description of that accordion section. So, I would like to ask how to print YAML form in custom block.

# Answer
Install the module insert Block

Enable and configure the insert block text format in 'admin/config/content/formats'

Make a new block with your form so that your form is available as a block.

In your accordion block you can call your form block with the special insert block tags \[block:module=delta\]. Make sure the 'insert block' text type is selected.
> 0 votes

---
Tags: theming
---


# Question
Title: drupal behat test assert authenticated by role with given fields
I am trying to run the following behat step:

```
@Given I am logged in as a user with the :role role(s) and I have the following fields:

```

This is defined in DrupalContext.php on lines 68-106. I have a standard behat install from composer. When I run this, I get the following error:

> --- FeatureContext has missing steps. Define them with these snippets:
>
> /\** * @Given I am logged in as a user with the :arg1 and I have the following fields: \*/ public function iAmLoggedInAsAUserWithTheAndIHaveTheFollowingFields($arg1, TableNode $table) { throw new PendingException(); }

I am still pretty new to OOPHP so when I read this I took it to mean that it couldn't find the original method. I added a use statement in my feature/bootstrap/FeatureContext.php:

```
use Drupal\DrupalExtension\Context\assertAuthenticatedByRole;

```

But I still get the same results. Here is my implementation of the behat scenario:

```
@api
Scenario: An administrator should not be able to create a page content
  Given I am logged in as a user with the 'administrator' and I have the
  following fields:
    | field_user_username     | drupaltest  |

```

# Answer
You have a typo in your Given condition - you need to have `role(s)` after administrator.

```
Given I am logged in as a user with the 'administrator' role(s) and I have the following fields:

```
> 2 votes

---
Tags: 7, testing
---


# Question
Title: Should I include arguments in views_embed_view or in a hook_views_pre_view function?
I have a tonne of views across my site and pretty much all of them need to have their arguments passed programmatically.

I'm wondering which method is best assuming I'm using views\_embed\_view to print all of them.

Thanks.

# Answer
> 2 votes
`views_embed_view` takes arguments as the third parameter. Since you have to use that to print a view on-demand, might as well pass them along there.

---
Tags: 7, views
---


# Question
Title: How to use User Points to buy/sell a custom content type?
I'm currently working on an educational project as a sort of final keystone project for my major in undergrad. The project is a online artwork trading game, in which students take on the role of being an art dealer/collector, and buy, sell, trade, and advertise artworks to each other on the site. I chose to use Drupal as a CMS due to its flexibility, but relative user-friendliness, as I won't be maintaining the project after my graduation in a few weeks.

I've polished off most of the site's features, with the exception of one, the currency system. At the moment, I have used the User Points module to create a virtual currency (guilders) for students to use when trading their artworks. I have also created the artworks as a custom content type. I am trying to make it so that students can buy/sell or just straight trade artworks between each other. I've attempted to install the Drupal Commerce module and pursue that route, which doesn't seem to be working. I've also tried making it so that students can manipulate node ownership, but it looked like that would create a permissions nightmare eventually, leaving me at a loss as of what to do. Due to the fact I won't be around to maintain the site, my original question of module recommendations really more is a recommendation of a solution that's not overly technical, and is fairly stable. My professor (who is an Art Historian) will be maintaining the project, and while he has taken an introductory computer science course, an astute programmer he is not.

TL;DR: I need a way for users to use userpoints to buy/sell a custom content type between themselves, and I need to keep the solution as stable as possible due to long-term maintenance concerns.

# Answer
> 3 votes
Use the integration between the User Points module and the Rules module to create some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

```
{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer 25 user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved".

The above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

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

---
Tags: userpoints
---


title: Why are most of the commands missing?

text:
# Question
Title: Why are most of the commands missing?
Most of console commands are missing from the output of `drupal list`.

I am using Drupal Console version 0.11.3, which outputs the following error message.

> \[WARNING\] In order to list all of the available commands you should install Drupal first.

The multi-site is correctly configured.

I have created an empty /sites/default/settings.php and it is still not working, i.e. it still not showing most of the Drupal console commands.

Why do I get that error message?

# Answer
> 3 votes
Specifying the root resolved this for me. Having used composer to install drupal through drupal-composer/drupal-project the site is put in a "web" folder so the following worked.

```
drupal --root=/var/www/html/web list

```

I had also run the init command beforehand

```
drupal --root=/var/www/html/web init

```

---
Tags: 8, console
---


# Question
Title: Feed content type field with configuration value
I have a config form with several config variables where i save some user preferences like «position» or «weight»

Now, at the moment of generating a content type i want to feed a select field with the «position» config formerly mentioned saved values as options for this field.

I saw i would may create a reference field as a view reference. So i guess i would do before a view printing those values, but i guess if there is a more convenient way to do this.

I prefer to do it without code, using the gui.

PS: I'm doing this with a simple config form, for customer's reasons i can not use Configuration Entity Types :-/

# Answer
> 0 votes
finally, I decided to do a custom autocomplete for the field with a validation in the form submission :-S

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


# Question
Title: How to make Views sorting case-sensitive?
Ascending alphabetical sorting in a Views string field works like this:

```
1
2
3
a
A
b
B

```

But I want it like this:

```
1
2
3
A
B
a
b

```

Is there any way to do this?

# Answer
What you're want to do is a sort by a character's byte value. MySQL has a function for this, `BINARY()`, which you could use in your `ORDER BY` criteria (e.g. `ORDER by BINARY(title)`).

Drupal Views doesn't have any default sorting handlers that use this function, so the only way to do it in views is by creating your own custom sort handler.
> 2 votes

---
Tags: 7, views
---


title: Webform submitted data field names

text:
# Question
Title: Webform submitted data field names
I am beginning a module which implements the hook\_webform\_submission\_insert. I am successfully getting the following data from my implementation of that hook:

```
stdClass Object
(
    [nid] => 3401
    [uid] => 1
    [submitted] => 1425491295
    [remote_addr] => http://myserver.com
    [is_draft] => 0
    [data] => Array
        (
            [2] => Array
                (
                    [value] => Array
                        (
                            [0] => Chandler Mann
                        )

                )

            [3] => Array
                (
                    [value] => Array
                        (
                            [0] => tecutij@yahoo.com
                        )

                )
.
.
.

```

I need to write code to programmatically map each value index to node fields in a process of creating nodes from custom code.

**However, as the output above does not have field names, it's difficult to map correctly to the necessary node fields.**

Can anyone advice how I might discover what name webform assigns to the field#id 2, 3 etc as in my code sample above?

# Answer
> 2 votes
The `$node` argument to `hook_webform_submission_insert()` contains the info you're looking for. For a Webform node, you'll find an array `$node->webform->components` where, for example, `$node->webform->components[2]` would correspond to the item whose value is "Chandler Mann" in your data.

# Answer
> 2 votes
The `$submission->data` array is keyed by Webform internal component IDs, which you can't see from the admin interface.

You can build a helper array mapping form keys to component IDs:

```
$compMap = array();
foreach ($node->webform['components'] as $c) {
  $compMap[$c['form_key']] = $c['cid'];
}

```

Then you can get the values by form keys as follows:

```
if (array_key_exists($compMap[$key], $submission->data)) {
  $value = $submission->data[$compMap[$key]]['value'][0];
}
else {
  // No value was entered for this field.
}

```

Note, that the value will be in the `['value'][0]` element only for "simple" fields, like text or number. For other types, e.g. reference fields, check your data.

---
Tags: webforms
---


# Question
Title: Custom form using custom template, submit the form don't call its validate and submit handlers
I created a simple custom module where I created a Class Form using a custom template form. If I don't use my custom template (I comment my \_theme hook from my .module), when I submit my form, class methods handlers validate and submit are called. But When I use my custom form template, If I submit my form, validate and submit class methods handlers aren't called, I don't understand why.

This is my code; I begin with my templates/form--myformtest-form.html.twig template.

```
<h1>TEST</h1>
<form{{ element }}></form>

```

My myformtest.module code is the following.

```
/**
 * Implements hook_theme().
 */
function myformtest_theme($existing, $type, $theme, $path)
{
  return array(
    'form__myformtest_form' => array(
      'render element' => 'form',
      'template' => 'form--myformtest-form',
    ),
  );
}

```

If I comment this hook, my form use the default theme form template. In this case, submit the form call validate and submit class handlers methods. If I don't comment this hook, my form use my custom template. Then when I access to my custom form page and valid the form, validate and submit handler are never called.

This is the simple code from my src/Form/MyformtestForm.php class.

```
class MyformtestForm extends FormBase {
  //...
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['textfieldtest'] = [
      '#type' => 'textfield',
      '#title' => $this->t('textfieldtest'),
      '#maxlength' => 64,
      '#size' => 64,
    ];

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

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    ksm("MyformtestForm Validate handler!");
    // logs never displayed when I use my custom template. If I don't use the custom template, this log appears.
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    ksm("MyformtestForm Submit handler");
    // logs never displayed when I use my custom template. If I don't use the custom template, this log appears.
  }

```

Why handlers aren't called when my form use my custom override? How can I call them?

These are the variables existing from my custom template when I load my form page.

>

# Answer
You need "base hook" in there, I believe.

Here's an example:

```
/**
 * Implements hook_theme().
 */
function formcustomtemplate_theme() {
  return array(
    'form__my_form_test' => array(
      'render element' => 'form',
      'template' => 'form--myformtest-form',
      'base hook' => 'form',
    ),
  );
}

```

If you are using a custom theme, and you don't need the template in your module, the approach of creating a new theme hook for your custom form is unnecessary.
Rather than create a new theme hook, use hook\_theme\_suggestions\_alter in your theme:

```
/**
 * Implements hook_theme_suggestions_alter().
 */
function mytheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#theme'])) {
    $suggestions[] = 'form__' . $variables['element']['#theme'][0];
  }

}

```

then create the appopriate template in your theme.

then to see the theme suggestions output to the page, turn on twig debugging:

https://drupalize.me/blog/201405/lets-debug-twig-drupal-8

You'll see template suggestions in the markup:

```
<!-- FILE NAME SUGGESTIONS:
   * form--myformtest-form.html.twig
   x form.html.twig
-->

```

You can see that it's not yet picking up your template, so create a template file by copying the form.html.twig and renaming it.

To check where Drupal is looking for templates using the "form" hook, you can print out the theme registry from hook\_theme\_registry\_alter:

```
 "form" => array:6 [▼
    "template" => "form"
    "path" => "themes/custom/mycustomtheme/templates/form"
    "type" => "theme_engine"
    "theme path" => "themes/custom/mycustomtheme”
    "render element" => "element"
    "preprocess functions" => array:4 [ …4]

```

This lets you know that you need to put the template in that directory.
> 3 votes

# Answer
This might prove useful for people who want to style each element of the form.

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */

function MODULE_NAME_form_YOUR_FORM_ID_alter(&$form, FormStateInterface &$form_state) {
  $form['#theme'] = ['CUSTOM_NAME'];
}

```

Afterwards I set up my hook with the needed element.

```
/**
 * Implements hook_theme().
 */
function MODULE_NAME_theme($existing, $type, $theme, $path) {
  return [
    'CUSTOM_NAME' => [
      'render element' => 'form',
    ],
  ];
}

```

I named my template accordingly(CUSTOM\_NAME.html.twig). Here, you can render your `$form` elements accordingly(ex: `{{ form.name }}`, coming from `$form['name']`).

And last but BELIEVE ME, not least, and most importantly, do not forget to include the form\_build\_id and form\_token variables.

```
  {{ form.form_build_id }} {# required #}
  {{ form.form_id }} {# required #}
  {{ form.form_token }} {# required #}

```

The answer to the question is already chosen, this one is just a simple as it gets explanation for how to theme your form more thoroughly.

Cheers
> 1 votes

# Answer
if you worked with drupal 7 , in drupal 7 we render `drupal_render_children($form);` in our markups to drupal render hidden and csrf fields, According to From.html.twig

> Available variables
>
> ```
> attributes: A list of HTML attributes for the wrapper element.
> children: The child elements of the form.
>
> ```

if you want first render the elements as you want then you should finally render `{{ children}}` as drupal 7 method.

**So** first render your desire elements then render `{{ children }}`,your should try something like

```
<h1>TEST</h1>
<div class="myclass">{{ element }} </div>
// other elements
// and finally
{{ children }}

```
> 0 votes

# Answer
I also think that the rendering of your form is the problem. Take a look at the default form templates in core, like form.html.twig.

https://api.drupal.org/api/drupal/core!modules!system!templates!form.html.twig/8.2.x

May you try it in that way and use {{ children }} or render the fields step by step with something like {{ element.textfieldtest }}.

So I would use this code

```
<h1>TEST</h1>
<form{{ attributes }}>
  {{ children }}
</form>

```

You can also dump the output in the template with `{{ dump }}` and look which variables you have. Here is a link for enabling the twig debugging https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates
> 0 votes

---
Tags: theming, forms, 8
---


# Question
Title: How do I deliver a nested JSON array for content reference with export view display?
I created a product content type with content reference to article(one product to many articles). Then I added field "Content: ID" "Content: Title" and "(field\_article: Content) Content: Title" to a new REST export View. "(field\_article: Content) Content: Title" come from the relationship "Content referenced from field\_article" I added in advanced.  The output is:

```
[
    {
        "nid":"3",
        "title":"Product1 title",
        "article_title":"Article1 title"
    },
    {
        "nid":"3",
        "title":"Product1 title",
        "article_title":"Article2 title"
    }
]

```

What I would like to achieve is something like this:

```
[
    {
        "nid":"3",
        "title":"Product1 title",
        "articles":
            [
                {
                    "title":"Article1 title"
                },
                {
                    "title":"Article2 title"
                }
            ]
    }
]

```

How to implement this?

UPDATED: I also tried aggregation, but in case of REST export View as the format is Serializer, no "group by" option in format setting but hal\_json, json and xml options, while "Aggregation settings" appears on each filed. In this case, I don't know how to set "aggregation settings" group by node id. Also I cannot find document about aggregation settings of field in "Fields" section.

# Answer
I've created a very simple module REST Export Nested to support nested JSON using Views Field Views.

After installing "REST Export Nested":

1. Install and enable Views Field Views
2. Create view display of referenced content (Articles in your case) of type "REST export" or "REST export nested"
3. Add a relationship to the parent entity and contextual filter of parent entity ID
4. Create a view display of the parent entity of type "REST export nested"
5. Add required fields (e.g. "nid", "title")
6. Add a field of type "Views field" (e.g. "articles"), configure with the correct View and display and pass "nid" as the contextual filter

The module doesn't depend on Views Field View and may work with other fields which produce a JSON string.
> 2 votes

# Answer
If you don't want to write your own REST api plugin you may want to try using jsonapi module that uses the jsonapi.org specification.

Jsonapi provides field collections by default.
> 0 votes

---
Tags: views, 8
---


# Question
Title: What cache should be cleared for front end theming work?
When theming I work with CSS files and templates files. What cache should I clear while retaining performance?

And what would be the equivalent drush command?

I think drush cc all clears too many things right?

# Answer
Here's the comprehensive list of cache-clear options and the underlying API functions & what they do:

That should let you fine target the cache to clear when it's needed.

Depending on your workflow, you might also want to force the cache off (e.g. `$conf['preprocess_css'] = 0;` & `$conf['preprocess_js'] = 0;`) in **local.settings.php** for your local dev environment so it doesn't interfere with feedback.
> 2 votes

# Answer
For CSS/JS you can do `drush cc css-js` in Drupal 7.
> 1 votes

---
Tags: drush, caching
---


# Question
Title: FormStateInterface::setValidationHandlers not working properly?
I'm using Drupal 8. Within `\Drupal\Core\Form\Form\FormBuilder::buildForm`, if `$cache_check == TRUE`, i.e. - the form has a `form_id` and a `build_form_id`, then the `$form_state` object which results from the call made to `retrieveForm()` in `\Drupal\Core\Form\FormBuilder::buildForm()` is overwritten by the `form_state` that is cloned prior to the retrieval.

This would seem to effectively nullify any modification done to the `$form_state` object within the `buildForm()` method of a Form class implementing `FormInterface`. Is this correct?

For example, `MyForm` class extends `FormBase` -- which implements `FormInterface`. If I make a call to `$form_state->setValidateHandlers()` within the `buildForm` method in `MyForm`, the extra validate handler methods set in that call will never be invoked, as the `$form_state` object will be overwritten after being rebuilt within `MyForm::buildForm()`.

Is this the expected behavior? i.e. - Is it not expected to be able to alter the `$form_state` within `buildForm()` in this way?

If that is the case, then is simply using the more "Drupal 7-ish" syntax of `$form['#validate'] = ['::method1', '::method2']` the accepted/best-practice way to accomplish multiple validate handlers?

This will work, because the `$form` array does not get overwritten after the `MyForm::buildForm()` method is invoked. However, if this is the accepted/best-practice way to achieve multiple validate handlers, how would one set a validate handler that exists outside of the current form class (in this example's case, `MyForm`)?

# Answer
You should add the below method in drupal 8. I hope it should work. // buildForm

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

    $form['company_name'] = array(
        '#type' => 'textfield',
        '#title' => $this->t('Company Name'),
        '#required' => 'TRUE',
        '#placeholder' => $this->t('Your company name'),
    );
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#validate' => array('::validateForm', '::method1', '::method2'),
    );

    return $form;

}

public function validateForm(array &$form, FormStateInterface $form_state) {
   // do your code stuff..
}

public function method1(array &$form, FormStateInterface $form_state) {
  // do your code stuff..
}

public function method2(array &$form, FormStateInterface $form_state) {
  // do your code stuff..
}

```
> 1 votes

# Answer
Thanks for your answer. I know that adding the validate handlers to the $form array will work, because (as I pointed out in my original post) the $form array is not being overwritten in the base class after MyForm::buildForm() is invoked.

However, the documentation clearly states that using $form\_state-\>setValidateHandlers() in the MyForm::buildForm() method should add those extra handlers and cause them to be invoked on submission of the form. My real question I suppose is, is it true that the setValidateHandlers() method can be used within a subclass' buildForm() method to accomplish this, or is that not the case? Is attaching the handlers to the #validate element on the $form array's triggering element considered the best-practice way to do this now?

If so, then the documentation for setValidateHandlers() may need to be changed. I've filed an issue for this on drupal.org hoping for an "official" response, at https://www.drupal.org/node/2869254. At the time of this writing though, I haven't received any response there.

Thanks again Satheesh!
> 0 votes

---
Tags: forms
---


# Question
Title: Aggregated CSS/JS file names, when regenerated?
What triggers the aggregated/compressed CSS/JS file names to be regenerated?

Because of the default header for `.css` and `.js` set in Drupal's stock `.htaccess` is 2 weeks, this causes issues with Varnish which obviously just obeys the headers it receives from the application.

Caching `.css/.js` for 2 weeks isn't really necessary, our web servers can serve hundreds of requests for static files per second. It's the Drupal requests that always worry me. So I can change the `.htaccess` (though I actually override the `Cache-control: max-age` header in Varnish so we don't have to modify stock files provided by Drupal).

I have noticed that regeneration can sometimes can be triggered with a `drush cc css-js` but possibly only if the aggregated files are over a certain age.
Does anyone know what the logic is behind this?

Rather than overriding the header sent by Drupal, it would be useful to know when the file names are regenerated, because that's obviously a way of making sure that HTML code cached in Varnish is picking up a new set of CSS/JS files.

# Answer
You're looking for drupal\_build\_css\_cache & drupal\_build\_js\_cache. The building happens when the file doesn't exist or when the combination of files used in the aggregate is different than before.

Looking at drupal\_clear\_css\_cache & drupal\_clear\_js\_cache the variable gets removed & any file older than 30 days gets deleted. By removing the variable, drupal will then check to see if the contents of the file has changed, if yes a new aggregate will be built. So the file name is built by using a hash of the files content and the quick lookup is built by a hash of the file names used.

If you want something that's a little smarter than core, doesn't cause a stamped of writes to the variables table on a cache clear, and keeps files around based upon usage instead of a 30 day window give Advanced CSS/JS Aggregation a try.
> 4 votes

# Answer
Completing mikeytown2 answer, this worked to clear up the aggregated names and forced a regeneration in my case:

```
drush vdel drupal_css_cache_files
drush vdel drupal_js_cache_files
drush vdel javascript_parsed

```
> 0 votes

---
Tags: theming, caching, css-js-aggregation
---


# Question
Title: change order of shipping services in checkout
I build two Shipping services in a drupal commerce shop. One with calculated rates. One with 0€ for pickup by the customer. It looks like this:  But i would like to change the order and make shipping service with costs as default. I tried to change the wight of the calculation rules, but without effect. Is it true, that I need a module for this task? It would be no problem, but I don't won't to overlook a easy solution.

# Answer
> 1 votes
Unfortunately, there's a pending feature request to make these orderable via the user interface, but in the meantime you're dependent on code to change their ordering. The hook to use is hook\_commerce\_shipping\_collect\_rates(), and what you need to do is alter the weight value of the line items in the $order-\>shipping\_rates array.

---
Tags: commerce
---


# Question
Title: Why do cron.php still run automatically in each o'clock when I had stopped it?
I am curious on this. I had switch off it on my setting-\>system-\>cron to permanently stop it. However, the mail will hourly send the mail to www-data.

The mail content as below:

curl: (22) The requested URL returned error: 403 Forbidden Error running the periodic maintenance for /etc/drupal/7/sites/default: CURL exit code 22 Requested URL: http://localhost/drupal7/cron.php

Please help. Thanks.

=========================================================================== I found a clue. My mail title shows up:

if test -x /usr/share/drupal7/scripts/cron.sh ; then /usr/share/drupal7/scripts/cron.sh ; fi

So, I check the path and get known cron.sh this file. I paste the content. I am not good at bash. What is this bash meaning for? Would you simply explain this? I would thank you very much.

```
#!/bin/sh

for site in /etc/drupal/7/sites/* ; do
    BASE_URL=""
    CRON_KEY=""
    FULL_URL=""

    if [ ! "`basename $site`" = "all" ]; then
            for file in $site/baseurl.php $site/settings.php; do
                    [ -f "$file" ] && BASE_URL=`grep '^$base_url' $file | cut -d"'" -f2`
                    [ "X$BASE_URL" != "X" ] && break
            done

            for file in $site/cronkey.php $site/settings.php; do
                    [ -f "$file" ] && CRON_KEY=`grep '^$cron_key' $file | cut -d"'" -f2`
                    [ "X$CRON_KEY" != "X" ] && break
            done

            if [ "X$BASE_URL" = "X" ] ; then
                    if [ -f "$site/settings.php" ]; then
                            BASE_URL='http://localhost/drupal7'
                    else
                            break
                    fi
            fi

            if [ "X$CRON_KEY" = "X" ] ; then
                    FULL_URL="$BASE_URL/cron.php"
            else
                    FULL_URL="$BASE_URL/cron.php?cron_key=$CRON_KEY"
            fi

            if curl -S --fail --silent --compressed --insecure --location $FULL_URL ; then
                    # Success!
                    true
            else
                    echo "Error running the periodic maintenance for      $site: CURL exit code $?"
                    echo "Requested URL: $FULL_URL"
            fi
    fi
done

```

# Answer
> 1 votes
The **Run cron every** setting only disables Drupal's automatic cron job firing within page requests. This is a lightweight option (previously known as Poorman's cron) for sites that have some minor cron tasks that can be handled before serving a page request.

It doesn't disable any external cron requests from crontab, Jenkins, or any other task runner service that might be calling **cron.php**. You will need to configure your server to disable this.

---
Tags: cron
---


# Question
Title: How Can I Prevent Webform Being Displayed in Front Page
I've installed panopoly distribution and Webform module. I've also created a webform called contact form and added the contact form in a pane as a block. The problem is: The contact Form (webform) is being displaying in the front page as new content.

I've also tried various settings including:

* Untick all options from publishing option (Administration » Structure » Content types » Webform)

to remove that but nothing works.

How can I remove webform from being displayed in the front page in Drupal 7?

# Answer
I solved this issue. There is a operation in panopoly called `Demote from front page` in `Administration » Content`.

This operation works like charm.
> 0 votes

# Answer
The publishing options at Administration » Structure » Content types » Webform are defaults. Edit the particular webform node and uncheck "Promoted to front page".
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: How to theme table row to link particular column data?
I have created a list of table records in admin section using the following code.

```
class userDownloadedFiles extends ControllerBase{ public function userList() {
$header = array(

  array('data' => $this->t('Username'), 'field' => 'name', 'sort' => 'asc'),
  array('data' => $this->t('Email'), 'field' => 'mail', 'sort' => 'asc'),
);

$db = \Drupal::database();
$query = $db->select('users','u');
$query->innerJoin('users_field_data','ufd','u.uid=ufd.uid');
$query->fields('ufd', array('name','mail'));
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')
                    ->orderByHeader($header);
// Limit the rows to 20 for each page.
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')
                    ->limit(20);
$result = $pager->execute();

// Populate the rows.
$rows = array();
foreach($result as $row) {
  //Get URL to user profile
  $profile_url = \Drupal::service('path.alias_manager')->getAliasByPath('/user/'.$row->uid);

  $rows[] = array('data' => array(
    'name' => "<a href='$profile_url'>$row->name</a>",
    'mail' => $row->mail,
  ));
}

// The table description.
$build = array(
  '#markup' => t('List of users who have downloaded model drawing or requested an account for downloading one.')
);

// Generate the table.
$build['user_info_table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#empty' =>t('There are no records yet.'),
  '#rows' => $rows,
);

// Finally add the pager.
$build['pager'] = array(
  '#type' => 'pager'
);
return $build;  }}

```

But the a tag used in username column is displayed as it is not appearing as link. This is how it appearing

Please guide me how to make it likable and how would I do it for other columns too.

# Answer
You can try using the render element syntax for a Link element, like this:

```
$rows[] = array(
  'name' => array(
    '#title' => $row->name,
    '#type' => 'link',
    '#url' => $profile_url
  ),
  'mail' => array(
    '#title' => $row->mail,
    '#type' => 'link',
    '#url' => 'mailto:' .  $row->mail,
  ),
);

```

That way you can stick to a more consistent coding style, i.e. render arrays for presentation.
> 2 votes

# Answer
You need to create your link using FormattableMarkup:

```
use Drupal\Component\Render\FormattableMarkup;

$rows[] = array('data' => array(
  'name' => new FormattableMarkup('<a href=":link">@name</a>', [':link' => $profile_url, '@name' => $row->name]),
  'mail' => $row->mail,
));

```
> 1 votes

---
Tags: theming, navigation
---


title: How do I use jQuery in page.html.twig?

text:
# Question
Title: How do I use jQuery in page.html.twig?
In Drupal 7 I used some JavaScript that required jQuery in the page.tpl.php file using the following code.

```
<script type="text/javascript">
    (function($) {
    $( ".mobile-menu-button" ).click(function() {
    $(".navigation").toggleClass( "visible" );
    $(this).toggleClass( "active" );
});
    })(jQuery);
</script>

```

Hod do I do this in Drupal 8? I have tried many ways of adding this code (with and without the jQuery argument above) in page.html.twig without success. I can see the code in the page source, but it fails to work.

# Answer
> 0 votes
You need to write JavaScript in a js file in your theme, declare a library within your theme and attach it globally or inside of a theme page attachments hook. You also need to depend on jquery from core in your library yaml definition as well.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

---
Tags: theming, javascript
---


title: Dynamic content-type creation

text:
# Question
Title: Dynamic content-type creation
I have this scenario in my application:

Every registered member, can manage up to 3 content-types. And manage nodes based on their own content-types. They can manage their own content-types and nodes.

edit: the number of registered members might reach more than 1000

How can I approach this?

opening *administer content-types* permission for authenticated-users is definitely not an option. Also there could be a lot of confusions regarding dynamic permission, custom roles, etc...

Is creating content-type of node-content-types possible?

Are there any contributed modules or distribution for this specific features?

Thanks

edit02: Some explanations, I hope it's clear..

* user can manage his content-types by: creating new content type, edit/delete existing ones. he also can manage his nodes too.
* also, different user, cannot see other's content-types, but can see other's published nodes
* All content types (and it's fields) shouldn't be overlapped. maybe the user's name is included in the content-type machine name generator (and field's) to avoid duplicates
* I'm not sure about the idea *"creating content-type of node-content-type"*

# Answer
this could be done, but I think it's too broad for the Q&A approach of Drupal Answers. In general, if I was to try this, I would start with this:

* add an integer field to the user (to track number of content types)
* using Field Permissions, hide that field from anyone but admin

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

* create a role with the appropriate permissions to add content types
* if permission allows viewing the content type list, use Rules to check that url against role to ensure new 'content type moderators' cannot access the list and redirect with a message

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

* override the hook\_form\_alter() to check the integer value of the hidden field on content type creation, redirect or show message if user is at limit
* override the form submit() function to increment the integer value of the hidden field on content type creation, and create perhaps a custom block, menu entry or other element to allow the user access to edit the content type later on
> 1 votes

# Answer
Another approach to consider: Organic Groups (with permissions like "registered users can create their own group, of which they are the *owner*, so that they can "manage" whatever is related to that group).

Probably combined with Rules (like to automate some things trigger by Organic groups related "events") and/or Content Access (to secure group related "stuff", e.g. as a rules related "action" ) ...

Not sure yet if you'd need anything related to the Flag module (which is often used in combination with Rules). In your case anything related to "user specific, which might not be possible / handled by the Organic Groups module.

Depending on how your question can further be enhanced (more specific about what you actually want), I might be able to further enhance this answer also.
> 0 votes

# Answer
Try and see if Webform: https://www.drupal.org/project/webform does what you want to achieve.
> -1 votes

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


# Question
Title: How to set checkbox if validation fails?
I am creating a form which has checkbox, and options for checkbox are coming dynamically. In submit function I am rebuilding form if validation fails. all values are rendering but previously checked checkbox is not checking.

below is the code:

```
function modulename_form(){
      $header = array();
      $rows = array();
      $conditions = '';
      $orderby = array( 'pass_lname' => 'ASC');
      $unmapped_data = capcup_get_unmapped_passengers_data($conditions , $orderby);

      foreach ($unmapped_data as $key => $value) {
        $user = user_load($value->pass_uid);
        $insertion = !empty($value->pass_insertion)? $value->pass_insertion . ' ': '';
        if (empty($buttons)) {
          $row['name'] = '<a href="mailto:'  . $user->mail . '">' . check_plain($value->pass_lname . ' ' . $insertion . $value->pass_fname) . '</a>';
        }
        else {
          $row['name'] = '<a target="_blank" href="/passagier/'  . $value->passenger_uid . '">' . check_plain($value->passenger_lname . ' ' . $insertion . $value->passenger_fname) . '</a>';
        }
        $row['phone'] = $value->pass_tel;
        $row['practicecode'] = $value->pass_practcode;
          $form['active'] =  array(
          '#type' => 'checkbox',
          '#return_value' => $value->pass_uid,
          '#attributes' => array(
              'name' => array('nodes[' . $value->pass_uid . ']'),
            )
          );
          $row['active'] =  drupal_render($form['active']);
        $rows[$value->pass_uid] = $row;
      }

      $form['nodes'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => t('No passenger available.'),
      );
return $form;
}

```

submit function:

```
function modulename_submit($form, $form_state) {
  if (in_array('boat', $account->roles)) {
      $form_state['rebuild'] = TRUE;
      form_set_error('boat_user_info][emailaddress', 'Dit e-mailadres is al in gebruik.');
      return FALSE;
    }
}

```

I am writing form function like above because to get structure like below image:

When form will rebuilt all fields will remembered there previous value but checkbox is not remembered its value. I tried by adding `default_value` and all but not worked. Please suggest me how can I achieve that.

# Answer
> 0 votes
All form validations should be done in form validate function and not in submit function. Read this article

Hope it helps. :)

---
Tags: 7, forms
---


# Question
Title: Display specific node type in different path
I have created a new content-type `Document Template`. I need to display the contents of type `Document template` in a different path.

```
localhost/site_name/document_templates

```

not in

```
localhost/site_name.

```

What should I do?

# Answer
> 1 votes
Create a `View` with `Page` display. Set its `Path` to `document_templates`. Add a `Filter criteria` for `Content: Type (= Document Template)`. Hit save. Now visit your url `localhost/site_name/document_templates`. You will see your content of type `Document Template`.

# Answer
> 1 votes
Use the pathauto module and configure it so this content type automatically gets the right path settings by default when creating a node. https://www.drupal.org/project/pathauto

---
Tags: 7, theming, nodes
---