# Question
Title: How do I programmatically set cache age?
Drupal 8:

I have the code for a block successfully doing its work and returning it. The block is called "RacerProfile" and it dumps all its content into variable "$pageContent". At the very end it returns the #markup. Ok. Now how do I tell this to invalidate every six hours?

```
/**
 * Provides a 'Racer Profile' Block
 *
 * @Block(
 *   id = "racer_profile",
 *   admin_label = @Translation("Slider v1 block")
 * )
 */
class RacerProfile extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build()
    {
    // does all the work to make $pageContent via non-drupal database queries
    return array('#markup' => $this->t($pageContent),  );
    }
 }

```

In other Drupal answers, I've seen "D8 has cache tags and contexts that will automatically invalidate the block if something changes." Ok, my code is checking a second database. There's no way for Drupal to know what's changing over there. (Without checking, obviously.) So how do I add cache tags with specified timeouts? I can't find examples.

Notes:

-Obviously, this is not related to the Maximum Cache age within the admin area of Configuration \> Performance \> Caching \> Page cache maximum age. I don't want this to apply to the entire site, just this block.

-Obviously, this is not related to settings.php in any way either, since again I don't want to have this apply to the entire site, and the various modules will have different timeout requirements.

-The traffic for the site is relatively low volume, so if rendering a thing four times a day even it only needs to be done once a day isn't a problem. Every six hours means that it's changed before people wake up across four time zones. Mostly. ;)

-(edit addition) The block needs to have its cache controlled for anonymous users.

# Answer
This is all done from the render array itself. The nitty gritty details are documented in Cacheability of render arrays.

In your case, you need to do something like

```
return [
  '#markup' => $this->t($pageContent),
  '#cache' => [
    'max-age' => 86400, // one day in seconds
  ],
];

```

This uses the `#cache` entry for the render array, and sets the max-age to be one day. This is where you would also add in your cache contexts.

As a side note, try to avoid using `'#markup'`. Use themeable elements, either though code or Twig.
> 3 votes

# Answer
For cache settings of the dynamic cache see the answer from @MPD .

For the whole page you can set a global max-age in admin/config/development/performance.

The parameter is "Page cache maximum age". This is a bit misleading, because the Internal Page Cache does not respect this parameter \*), but only puts this value in the response header for reverse proxies and browser caches.

For a high traffic site I would recommend to disable the Internal Page Cache (but keep the dynamic cache!) and use varnish, which will respect the max-age header and provides fine tuning for further handling of the headers.

Edit:

\*) The reason for this behavior is, that Internal Page Cache uses Cache::PERMANENT, if the expire date is in the past:

```
$date = $response->getExpires()->getTimestamp();
$expire = ($date > time()) ? $date : Cache::PERMANENT;

```

And this expire date is set to "9-Nov-1978" by `FinishResponseSubscriber`:

```
 /**
   * Disable caching in ancient browsers and for HTTP/1.0 proxies and clients.
   *
   * HTTP/1.0 proxies do not support the Vary header, so prevent any caching by
   * sending an Expires date in the past. HTTP/1.1 clients ignore the Expires
   * header if a Cache-Control: max-age= directive is specified (see RFC 2616,
   * section 14.9.3).
   *
   * @param \Symfony\Component\HttpFoundation\Response $response
   *   A response object.
   */
  protected function setExpiresNoCache(Response $response) {
    $response->setExpires(\DateTime::createFromFormat('j-M-Y H:i:s T', '19-Nov-1978 05:00:00 UTC'));
  }

```
> 0 votes

# Answer
Confirming with previous comments in the thread that the best (if not easiest) way to make Drupal's Internal Page Cache "respect" the cache lifetime is to create an Event Subscriber that modifies the FinishResponseSubscriber shown above.

See boilerplate code for doing so at Anonymous user cache control
> 0 votes

---
Tags: 8, caching
---


# Question
Title: How do you modify modules/templates without waiting for the cache?
I'm a beginner at both php and drupal, I know some PHP, at least enough to modify templates and add/remove content from modules, but what irks me is that I always have to wait around 60 seconds for the changes to be visible.

Now I've heard about using the Admin Menu to flush all caches, I've tried every single module that claims to flush the cache, but I still have to wait 60 seconds for the changes to appear

I've also tried disabling the cache by modifying settings.php, to no avail.

As I've said, I'm a beginner at both php and drupal, is this a browser-side cache? or am I missing something?

# Answer
> 0 votes
This most likely is a server-side-cache related issue. I have also experienced this with my hosting. Try contacting your hosting provider about this issue or try to find a setting to turn off the server cache in your hosting's admin panel.

---
Tags: caching
---


# Question
Title: How can i use taxonomy name in url page using a view
I have a taxonomy terms like:

* christmas
* wedding

How can I build a view with url page like this: `www.site.com/%` being `%` christmas or wedding,

If users go to `www.site.com/christmas` just display nodes with christmas taxonomy.

If users go to `www.site.com/wedding` just display nodes with wedding taxonomy.

I have to do `n` views with same fields that why I want to do just one generic view.

# Answer
The PathAuto module allows you to easily change the URLs for the default taxonomy listings (which do what you describe).

Install the module and go to Administration \> Configuration \> Search and metadata \> URL aliases.

You can set a pattern for your vocabulary that is just `[term:name]` BUT there are good reasons not to do that (for example if a category overlaps with a default path). Something like `holiday/[term:name]` is likely a better choice.

For more options on PathAuto see the recipes from Drupal.org.

If you need more control over the display you can override the view that generates term pages.
> 1 votes

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


# Question
Title: Why can't I change anything in hook_node_view_alter?
I'm trying to change one of the side panels, no clue what is rendering it but it displays a list of OG members.

Anyways, in `template_block_view` and `hook_page_alter`, the widget has already been rendered into HTML. The only place I've been able to find where its still in pre-render form is `hook_node_view_alter` but no matter what I do to the `$build` variable, it has precisely 0 effect on anything (yes, I made sure the function is being called).

So if its not to change the view, what is `hook_node_view_alter` for? This is on drupal 7.

# Answer
`hook_node_view` and `hook_node_view_alter` are only going to give you control over the inner content of a particular `$node` that you may be viewing. Such as the inner content when going to www.mysite/node/2

Now if you have additional "blocks" or maybe as you called them "side panels", these are not a part of the `$node` array and thus cannot be changed in hook\_node\_view or alter. If the side panel is indeed a block, then you can change it's output with `hook_block_view` and `hook_block_view_alter`. Among other things depending on what you are trying to do. The process is to find the block ID, and target it inside your hook. However I may be wrong, because it really depends on what the block is.

You will need to provide a printscreen showing exactly what you are talking about if we are going to figure out the right direction you should take on altering it.

I would suggest downloading the "devel" module, enabling it, then look at the ouptut from `hook_block_view_alter` and see if it's what you're looking for.

```
function mymodule_block_view_alter(&$data, $block) {
  dpm($block); //make sure the module devel is installed and enabled for this function
}

```
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: How to get node Bundle in hook_form_alter on field config form?
Can you wonderful people help me out please? I am altering the field config form `(content types > plan > manage fields > edit field)` and cannot seem to get the proper bundle out. Every time I call the `bundle()` function it returns the string `"field_config"`. However the bundle is supposed to be `"plan"`. Perhaps it's different because I am on the field config form, and not a node form?

Below is my code, the things I've tried and the field object showing the proper bundle. Does anyone know of another solution for me to get `"plan"` out?

```
<?php

use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\ContentEntityForm;

/**
 * Implements hook_form_alter().
 */
function rent_plan_custom_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
// print $form_id;

  switch ($form_id) {

    case 'field_config_edit_form':

        print $form['#title'];

        $field = $form_state->getFormObject()->getEntity();
        $field_name = $field->getName();  //returns correct field_plan_purpose

        //first try
        print $field->bundle(); //<---THIS RETURNS "field_config"

        //second try
        $bundle = FALSE;
        if ($form_object = $form_state->getFormObject()) {
            if ($form_object instanceof Drupal\Core\Entity\ContentEntityForm) {
                $bundle = $form_object->getEntity()->bundle();
            } elseif ($form_object instanceof Drupal\field_ui\Form\FieldConfigEditForm) {
                $bundle = $form_object->getEntity()->bundle();
            }
            print $bundle; //<---THIS RETURNS "field_config"
        }

        //Field Object Results Below
        print '<pre>';
        print_r($field);
        print '</pre>';

    break;
  }
}

```

**Results from print\_r($field)**

```
Drupal\field\Entity\FieldConfig Object
(
    [deleted:protected] =>
    [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
        (
            [id:protected] => node.field_plan_purpose
            [field_name:protected] => field_plan_purpose
            [entity_type:protected] => node
            [type:protected] => text_long
            [module:protected] => text
            [settings:protected] => Array

            ... lots of more stuff
        )

    [id:protected] => node.plan.field_plan_purpose
    [field_name:protected] => field_plan_purpose
    [field_type:protected] => text_long
    [entity_type:protected] => node
    [bundle:protected] => plan
    [label:protected] => Purpose
    [description:protected] =>
    [settings:protected] => Array
        (
        )

    ...lots more stuff
)

```

# Answer
You're looking for `FieldDefinitionInterface::getTargetBundle`

> Gets the bundle the field is attached to.
>
> This method should not be confused with EntityInterface::bundle() (configurable fields are config entities, and thus implement both interfaces):
>
> * FieldDefinitionInterface::getTargetBundle() answers "as a field, which bundle are you attached to?".
> * EntityInterface::bundle() answers "as a (config) entity, what is your own bundle?" (not relevant in our case, the config entity types used to store the definitions of configurable fields do not have bundles).

e.g.

```
$target_bundle = $field->getTargetBundle();

```
> 5 votes

# Answer
`FieldConfigBase` has a method on it(\*) called `getTargetBundle()`. That will retrieve the field name. To be safe, you should also probably use `getTargetEntityTypeId()` to make sure you are dealing with a node:

```
$entity_type = $field->getTargetEntityTypeId();
$bundle = $field->getTargetBundle();
if ($entity_type === 'node' && $bundle === 'plan') {
  do_something_awesome();
}

```

Using a class-aware editor, like PHPStorm, will make things like this a lot easier because you add type-hints, and then it will autocomplete for you. In most OO code and some procedural code, a good IDE will automagiclly figure out your types, so you don't need to add the hinting.

(\*) You should really be looking at the interface(s) that these define. The one of interest in this case is `FieldDefinitionInterface`.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Add class on row by modifying view.tpl.php file
I am trying to add some classes on the specific row in one of my view table. I have tried to use MYTHEME\_preprocess\_views\_view\_table, but failed. Nothing changed on my page.(Here is my previous question link:How to add css class to specific rows base on fields in order commerce view page, if you have any idea about this, I am interested in hearing from you). So I decided to create a new view.tpl.php file to display them. However, nothing showed on my page again.

Here is a screenshot includes: 1.my view theme detector 2.my code 3.result on Chrome

I can find my file being used by my view, however, I don't see any changes on my page. Does anyone know what mistake I have made? Or any idea about how to add class on specific row.

**Update:**

I have already cleared the cache several times.

**Finally:** Normally, Chris Happy's answer should work. But there might be some problem with my website, so we figured it out my problem by using JQuery. Thank you for @Chris Happy's help.

# Answer
> 1 votes
I tested it out, and it didn't work for me....until I cleared the cache!

Just go to yoursite.com/admin/config/development/performance/ and click "clear all caches".

**Update**: since clearing the cache didn't work, check if you are editing the right file: delete all the code in the tpl.php file.

* If the view disappears, you are editing the right file.
* If it still shows, close your editor window and select the file again.

---
Tags: 7, views, theming
---


# Question
Title: Domain Access: Subdomain -> same views-path - different view?
I am a beginner by module domain-access and have a question.

standarddomain: `example.com`
subdomain: `m.example.com`

In my standarddomain i use a views-page with path `example.com/myviewsgallery` (Views A) - this viewspage show 50 results, has a special pager and so on.

On my subdomain I need the same path `m.example.com/myviewsgallery` but here I will use an other (minimized) Views (Views B) with reduced results and other pager (and so on). The mobile version is intended to display reduced content.

I would like to use a mobile-switcher that automatically redirects the mobile user to the mobile subdomain - to the same path as on the desktop version.

But the problem is, I cant use a other (reduced) View-Page on my mobile-subdomain which has the same Views-path like standardomain.

At the moment:

* `example.com/myviewsgallery` (show Views A)
* `m.example.com/myviewsgallery` (show Views A too, but i need Views B under this path)

Is there anyone here who can tell me how to solve this problem?

Excuse me my bad English, I hope nevertheless that I could bring the problem understandably.

Many thanks in advance Matthias

# Answer
Based off @Sugandh Khanna answer, follow these steps:

1. Make View 2 as an attachment and attached to View 1.
2. In mobile view, add the css `.view-content { display: none }`
3. In desktop view, add the css `.attachment { display: none }`
> 0 votes

---
Tags: 7, views, domain-access
---


title: How to show comment reply form

text:
# Question
Title: How to show comment reply form
I have installed ajax comments module. There is a "reply" link to show comment reply form. I want to show comment reply form under comments without click reply link. Is it possible?

# Answer
> 0 votes
if (you = JS) {

use `document.getElementById('yourLinkID').click();`

} else if (you = JS && you = jQuery){

use `$('.content-type #LinkID').click();`

} else {

// can't think of anything, either then an option in the UI. I don't have much experience with Drupal comments.

}

---
Tags: forms, ajax, comments
---


# Question
Title: Drupal 7 REST services - Suppress API output of NULL
I've an API service callback function which ties up with its own module template to give an HTML output.
As per my understanding, default content type of API output is `application/json`, so I had to override it manually to `text/html`.

However, I'm still getting a `null` output always no matter whatever I try. Can someone please help me suppress this unwanted `null` output?

### custom\_module.module

```
function api_callback_function($a) {
  if (!headers_sent()) {
    drupal_add_http_header('Content-Type', 'text/html');
  }
  print theme('custom_template_name_alias', array(
    'b' => $a
  ));
  return;
}

function custom_module_theme() {
  $themes = array(
    'custom_template_name_alias' => array(
      'template' => 'something-only', // name of template file, sans file extension
      'variables' => array(
        'b' => NULL
      ),
    )
  );
  return $themes;
}

```

### something-only.tpl.php

```
<?php
$c = $variables['b'];
$path = drupal_get_path('module', 'custom_module');
global $base_url;
?>
<!doctype html><html class="no-js" lang="en">
  <head>
    <!-- HEAD related HTML code comes here -->
  </head>
  <body>
    <div>Current value of variable 'b' = <?php echo $c; ?></div>
  </body>
</html>

```

### Output

>

# Answer
You're returning null from the callback, so it makes sense that it's printing null.

Remove the return, or return the themed string instead.

The former is probably safest, as you can be sure the default theme wrappers for the page won't be invoked.
> 1 votes

---
Tags: 7, services
---


# Question
Title: Only Admin allowed to alter order in 'Review' state
How can I make an Order with status of Review read-only to the creator user? And once the Admin updates to state to 'Payment', the creator user can continue as normal?

# Answer
The best way to achieve this might be with a custom module. You could use `hook_form_alter()` to alter the order edit form and add a validation function that checks the order status and the logged in user ID - and throw a form validation error before saving if you want to prevent them.

You might be able to accomplish this point-and-click-style with the Rules Forms module (https://www.drupal.org/project/rules\_forms) which adds the ability to trigger Rules events during form validation. I haven't tried that module myself, so I can't say for sure.
> 0 votes

---
Tags: commerce
---


# Question
Title: Drupal Authentication with ActiveDirectory
I'm trying to make Drupal work with ActiveDirectory just for authentication. I'm using Lightweight Directory Access Protocol.

I always get this message:

> Warning: ldap\_search(): Search: No such object in LdapServer-\>search() (line 257 of D:\wwwroot\drupal\sites\all\modules\ldap\ldap\_servers\LdapServer.class.php).
> Test sandbox-edu LDAP Server Configuration Binding with DN for non-anonymous search (testuser@sandbox.edu). Using password entered in form.
> Successfully bound to server
> Failed to find test user userone by searching on sAMAccountName = user one.
> No such object

Here are the settings of the Server Properties:

```
sid = SANDBOX_EDU
name = sandbox-edu
status = 1
type = ad
address = LDAP://10.100.100.2
port = 389
tls = 0
bind_method = 1
basedn = Array
binddn = testuser@sandbox.edu
user_dn_expression = cn=%username,%basedn
user_attr = sAMAccountName
mail_attr =
ldap_to_drupal_user =
testing_drupal_username = userone

```

Can anyone who were able to get this module working with ActiveDirectory show us a sample of the setting?

If there's any other way other than using this module, please also recommend. I really need Drupal to work with ActiveDirectory for authentication because we have many students here.

# Answer
> 1 votes
I have the following set of parameters that allow authentication by Active Directory 2003:

```
server type: "Active Directory LDAP"
server address: ad.example.com
ldap port: 389
binding method for Searches: Bind with Users Credentials
base DNs for LDAP user entries: cn=users,dc=example,dc=com
username attribute: sAMAccountName
expression for user DN: %username@company.com
email attribute: mail

```

I think the problem mainly stems from the fact that AD typically does not have the login name in the LDAP DN.

# Answer
> 0 votes
If you are interested in a SSO module for Drupal you could look at my answer of a previous question here:

Automated login with LDAP always returns error

Or read below:

> Perhaps not a direct answer to you question about the LDAP module but I managed to enable SSO in a Windows domain environment with the Webserver authentication (https://www.drupal.org/project/webserver\_auth) module.
>
> You need to force Windows Authentication in your IIS site and disable Anonymous authentication. The Webserver authentication module is also capable of creating accounts when a Windows Domain user is visiting your site and is not registered in Drupal.

---
Tags: 7, users, authentication-authorization
---


title: Potluck (Food) Menu Sign up form

text:
# Question
Title: Potluck (Food) Menu Sign up form
I am looking a way to create a food menu sign up sheet. Login user can select food menu from the list, If somebody picks the food, it is disabled, so nobody can sign up for that item again. Is there anything like this out there?

# Answer
> 1 votes
You could try a wishlist or gift registry module. Here's one. I haven't tried this but it should disable or remove items from the list once people select them.

https://www.drupal.org/project/wishlist

Please note that this question has multiple or too many possible answers, so it might get disabled.

---
Tags: forms, navigation
---


# Question
Title: Reset View result counter after changing page (manually or with Twig)
**Drupal 8**

I have a View that uses the `View result counter` starting at '0'. It works great, except for the fact that when you change to `Next page` the counter doesn't start off at '0' again, but rather continues on.

I tried using Twig modulus to get a circular-list (always reset back to 0), the reason I use 10 is because my pager displays 10 items.

```
{{ counter % 10 }}

```

It doesn't work, it always prints 0 for some reason. But if I do `{{ 11 % 7 }}` it prints the correct result which is '4'.

Does anyone know either of these:

* Can I force view to restart counter at '0' when it goes to other pages int he pager?
* Why is Twig not printing the proper math result of `{{ counter % 10}}` ? (Keep in mind that doing things like `{{ counter + 1 }}` don't work either. For some reason it only works when you use only numbers like `{{ 1 + 3 }}` )

Thanks.

# Answer
It doesn't work because counter is actually an object with the value as a property, that's done to properly handle markup or special characters and preventing them from being escaped multiple times.

Depending on what template you're overriding and where, you could possibly do this in twig, especially if you are where you are loop over the rows already, although that might be a bit complicated.

My/the backend developer approach would be to make your own counter views field/plugin that doesn't consider the pager. This logic happens in `\Drupal\views\Plugin\views\field\Counter::getValue()`. So you can copy this class into a custom module, rename to `NoPagerCounter` or so, and change the annotation to `@ViewsField("no_pager_counter")`. Then you remove the pager related part in the `getValue()`. Now you just need to implement `hook_views_data()` and define this as a field, just like `views_views_data` does with the counter:

```
  $data['views']['no_pager_counter'] = array(
    'title' => t('View result counter (no pager)'),
    'help' => t('Displays the actual position of the view result'),
    'field' => array(
      'id' => 'no_pager_counter',
    ),
  );

```

(Possibly with a better title/help, I just switched the ids)

Another variant of that would be to add an option for this to the existing class and provide a core patch/feature request for this. If others agree that it is useful then it might eventually get committed and you don't need to maintain custom code, but you will have to maintain the patch until then.
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to concatenate all token values of a list in a single field within a Rules loop?
I am attempting to send a list of uploaded files on a newly created node via email.

In a content type, I have a File Field that allows unlimited values.

Within Rules, I created a loop calling the current item "current\_file".

I am trying to concatenate all of the values into one longtext field called "file\_list".

I intend to use the token for the value of "file\_list" in the body of an email.

Unfortunately, I am unable to do so.

While in Data Selection mode, I can access the tokens created by the loop:

However, while in Direct Input mode, the tokens are not available to me. They are not listed in the "Replacement patterns" section.

When I attempt to fill the value with the following, I have no success:

```
[node:field-file-list]
[current-file:file:url]

```

What can be done to make the tokens available to me in Direct Input mode?

If I am doing this incorrectly, is there a different way for me to concatenate all of the URLs of each file so that I can put it in the body of an email action?

# Answer
This answer assumes that you have basic knowledge in using the Rules module and understand how to use a loop to return all values of a field with unlimited allowed inputs.

(Also, this will only cover reacting on a newly created node.)

---

So the main issue was that loop variables in rules were not available to me while in "Direct Input" mode BUT were available "Data Selection" mode.

I needed to concatenate all of the file names and file urls for an unlimited value file field and output them in an un-ordered html list in a Long Text field (Filtered HTML).

There may be a better way to do this, but this was currently the only way I could make this work.

---

## 1.) Create Extra Fields

Since the Loop variable tokens are not available in Direct Input mode BUT regular Field tokens are, we are going to put the loop variable info into the new fields AND THEN concatenate them.

You will create fields for the following:

* Uploading the files (File Field set to accept unlimited values)
* File Name field (Long text field. It is important that this is set to plain text. I experienced issues when this was not plain text)
* File Path/URL field (Also long text, also plain text for the same reason)
* File List field in plain text (Long text field in plain text. This is the field that will grab all of the concatenated values. It will make sense later. This also needs to be plain text or Rules will not concatenate the values for some reason).
* File List field in filtered html (Long text field with filtered html. This is the field that will be displayed to the users.)

In the above fields, only the very first and very last fields will be visible to the users. The rest should be hidden with the Field Permissions module.

The extra fields are just going to be used by the Rules module.

---

## 2.) Create a Loop

Since this file field has unlimited inputs, you will create a loop and select the File field.

I have named the current file in the loop "current\_file".

---

## 3.) Grab the File name

Within the newly created loop, we will create an action to "Set a Data value". It will grab the newly created File Name field and grab the value of the current file's file name.

Be sure that you are not in direct input mode or the tokens will not be available to you.

## 4.) Grab the File's URL

This step is similar to the last.

Add another action to "Set Data Value" for the newly created File URL/Path field. Set it to grab data from the current file's file URL.

Once again, be sure that you are not in direct input mode or the tokens will not be available to you.

## 5.) Concatenate the Values

Finally, in the Plain Text File List field, we are going to concatenate the values.

We first enter in the token that represents the current field and below it, we will add on the current file name and path.

This time, be sure to be in Direct Input mode so that you type in whatever you like:

## 6.) Add ul tags

Make sure that this is outside of the loop.

Add an action to Set a Data value that adds ul tags around the value.

## 7.) Put the Concatenated Values into the Filtered HTML field

We are going to add another action to Set a Data value. It will put the value of the Plain Text File list into the Filtered HTML File List field.

The reason two different file list fields were created is because concatenating in a filtered html field does not work for some reason.

## 8.) See the Results

If all of the steps are followed, you should be given an un-ordered HTML list of each uploaded file that is linked to its file url:

I feel like this 'should' be able to be accomplished in far less steps, but this was the only way I could solve the problem.
> 0 votes

# Answer
If what you're looking for is not available, then just make it available, which is "*a different way to concatenate all of the URLs of each file*" (as in your question). Read on for more details ...

Have a look at this example of a Rule (in Rules export format), which is a variation of what you're asking for:

```
{ "rules_show_list_of_fields" : {
    "LABEL" : "Show list of fields",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "StartOfList-" },
          "PROVIDE" : { "variable_added" : { "email_list" : "List of eMail IDs" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email" : "Current eMail" },
          "DO" : [
            { "data_set" : {
                "data" : [ "email-list" ],
                "value" : "[email-list:value][current-email:value]-"
              }
            }
          ]
        }
      },
      { "data_set" : { "data" : [ "email-list" ], "value" : "[email-list:value]EndOfList" } },
      { "drupal_message" : { "message" : "The value of the email_list variable is: [email-list:value]." } }
    ]
  }
}

```

Here is a summary of what this rule does:

* Add a new variable `email_list`.
* Init the `email_list` value with some prefix.
* For each item within the loop, append the value of that item, followed by a separator character.
* Add a suffix to the `email_list` value.

In my case I'm using a multi value text field with machine name `field_email_addresses`, which contains eMail Ids, and just want to dispay a Status message with a concatenation of those eMail IDs, separated by a "`-`", and with a prefix (=`StartOfList`) / suffix (=`EndOfList`). And I also use Rules Events "Update existing node".

Replace the machine name of my list field to your list field, and replace all 'eMail' by 'file' and you should be able to import this rule in your own site (if you have the Rules UI enabled).

Not sure if you want the prefix or suffix, and/or the separator character (="`-`"). Adapt or remove any of these to fit your needs.

*Voilà* ...

### Demo

Here is how the Status message looks like after you create a new node, or update an existing node (of type Article):

> The value of the email\_list variable is: StartOfList-user2@example.com-user4@example.com-EndOfList.
> 1 votes

---
Tags: 7, rules, files, tokens
---


# Question
Title: Programmatically get menu links filtered by language
In Drupal 8, I'm trying to get my menu which has translated menu item filtered by a given language.

So far, I was able to get my menu tree :

```
    $menu_parameters = $this->menuLinkTree->getCurrentRouteMenuTreeParameters('main');
    $menu_tree = $this->menuLinkTree->load('main', $menu_parameters);
    $manipulators = array(
        // Only show links that are accessible for the current user.
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        // Use the default sorting of menu links.
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $menu_tree = $this->menuLinkTree->transform($menu_tree, $manipulators);

```

But I still have "stand alone" links in both language.

I looked into manipulators and parameters, but couldn't see anything related to translation.

Maybe using MenuTreeParameters::addCondition, but i'm missing something here.

Any help would be greatly appreciated.

# Answer
@pbonnefoi. I've played a lot around with a filtering of menu items by language while worked on menu block multilingual task.

Here what I got:
`Drupal\menu_link_content\Plugin\Menu\MenuLinkContent` is responsible for retrieving of menu\_link entity, but this class hides from us `getEntity()` method, using one we could get menu link language (`$link->getEntity()->get('langcode')`)

So the trick is:

1. Extend this plugin by a new method `getLanguage()` and register it.
This plugin used in the `menu.tree_storage` service, also you need to change link provider class and plugin class to yours.
2. Create a new manipulator `yourmodule.menu_manipulators:filterByLang`,
and use it wherever you want like:
`['callable' =>
'yourmodule.menu_manipulators:filterByLang', 'args' => ['langcode'
=> $langcode]]`

Result code can be something like:

```
class MenuMultilingualServiceProvider extends ServiceProviderBase {

  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('menu.tree_storage');
    $definition->setClass('Drupal\yourmodule\Menu\MenuTreeStorageMultilingual');
  }
}

class MenuTreeStorageMultilingual extends MenuTreeStorage {
  protected function doCollectRoutesAndDefinitions(array $tree, array &$definitions) {
    foreach ($definitions as &$definition) {
      if ($definition['provider'] == 'menu_link_content') {
        $definition['class'] = 'Drupal\yourmodule\Plugin\Menu\MenuLinkContentMultilingual';
      }
    }
    return parent::doCollectRoutesAndDefinitions($tree, $definitions);
  }

  protected function loadLinks($menu_name, MenuTreeParameters $parameters) {
    $links = parent::loadLinks($menu_name, $parameters);
    foreach ($links as &$link) {
      if ($link['provider'] == 'menu_link_content') {
        $link['class'] = 'Drupal\yourmodule\Plugin\Menu\MenuLinkContentMultilingual';
      }
    }
    return $links;
  }

}

```

UPDATE: Also tuutti created another solution for that using a new menu tree manipulator `menu_block_current_language_tree_manipulator::filterLanguages` inside a new menu block type.

Here is his sandbox https://www.drupal.org/sandbox/tuutti/2832329

Also welcome to the discussion regarding translatable menu links on the d.o https://www.drupal.org/node/2466553

UPDATE 2: I've created a module for the end user to bring multilingual features to the menu blocks https://www.drupal.org/sandbox/matsbla/2831709

You can refer to it as an example of all said above.
> 0 votes

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


# Question
Title: Why is there a convention to use test-specific namespaces for unit tests?
My team and I have noticed that the Drupal convention is to create a separate namespace for unit tests (as opposed to the namespace define by, lets say, the custom module we are testing).

If they shared a namespace then we could, for example, easily override a function like `t()` for our tests. I know there are lots of ways to handle things like the `t()` function, but this convention of creating a new name space eliminates this particular option. Can anyone speak to why? What is the benefit?

# Answer
There are few reasons why tests are in different namespaces.

Drupal have several different types of tests

* WebTestBase (WTB), aka simpletests or integration tests
* BrowsertestBase (BTB), integration tests (all WTB will eventually be replaced by equivalent BTB)
* KernelTestBase (KTB), a barely bootstrapped version of Drupal, not an integration test but a lot more than a true unit test
* JavascriptTestBase (JSTB), an integration test that is Javascript aware
* UnitTestCase and PHPUnit\_Framework\_TestCase, unit tests

Note that integration are also called functional tests. I am going to ignore the difference between UnitTestCase and PHPUnit\_Framework\_TestCase right now and lump them together as unit tests.

The five different test types are all in different namespaces so the test discovery process can find them and place them into five groups. The test runner allows the various test groups to be run together, and also invoke them properly during runs.

For example, if making a big change, you can run all unit tests locally as a sanity check (running all of the take about a minute on a normalish local machine).

Tests associated with a particular module are also in the modules namespace, so you can easily run all tests for that module, and they won't be discovered if that module is disabled. For example, integration tests take along time (usually between 30 seconds and 4 minutes each). You can just run all of the Field UI tests at ones if you are doing work there.

The test runner also allows you to run all of the tests in a particular directory. This allows you to target a particular core subsystem that isn't in a module. For example, you can run all of the database kernel tests at once this way.

Some subsystems also define their own test bases. For example, the migration system defines its own test bases to centralize common functionality and to to have a common setup.

Tests also make frequent use of traits to share code between different types of tests.

The particular case you mention is an oddity. In a perfect world, the `t()` function wouldn't be used in object oriented code; the injected translation service would be used which could then be mocked in unit tests instead of needing to use shenanigans like shadowed globals.
> 1 votes

---
Tags: 8, testing
---


title: Unable to access admin

text:
# Question
Title: Unable to access admin
I am trying to access the admin of my Drupal site but .../admin and .../user are not working. When I try to access those pages I get the 404 page. I believe this may have been redirected similar to https://www.drupal.org/project/rename\_admin\_paths.

I have access to the database and files where would this configuration change be stored?

# Answer
Please specify the drupal version you are using and is there any problem with non admin pages.

Also ensure the following:

* Include .htaccess files
* Enable clean urls
* Clear caches
> 1 votes

# Answer
You have installed rename\_admin\_paths module.

Above image is the configuration page of rename\_admin\_paths.

Once you save this page. You admin and user url is changed. So you are getting 404 error.

You need to go to any link through admin menu. Then you can check the url and see the replacement of "admin".

Now from module list you can not go configure because it will go previous link. Let me know if you faced difficulty.
> 1 votes

# Answer
When everything else failse, you can use the non-clean URLs: ?q=user to login, ?q=admin/...
> 0 votes

# Answer
I was using Drupal 7.3

I finally found what I was after, we have a reverse proxy server and I looked into the configuration and found the correct address which was overriding the publicly available one.

I used that address and added */user* on the end and it worked.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Custom Content Entity type - allow fields to be managed
I've created a custom content entity type in Drupal 8. I've tied it in with the Field UI so it can be fielded, and I added some fields in the entity definition using BaseFieldDefinition.

One of the fields I added was this:

```
$fields['message'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('Message'))
  ->setDescription(t('The message to be shown'))
  ->setTranslatable(FALSE)
  ->setRevisionable(FALSE)
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'text_default',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('view', TRUE)
  ->setDisplayOptions('form', array(
    'type' => 'text_textfield',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('form', TRUE);

```

I want to set a default Text Format for this field, however I'm not sure how to do so. I don't know if I can do it in the code above, but I'm thinking that if I could edit the field settings on the 'Manage Fields' tab, I could do it there. However, I can't figure out how to get my field to show up on that page. It shows up on the 'Manage Form' and 'Manage Display' tab, but not the 'Manage Fields' tab.

Does anyone know how to either get it to show up on that tab, or how to set the default text format on this field?

# Answer
Alright, after lots of research I've come up with three different solutions to the issue.

**Solution 1 (not so great):**

On the text formats and editors configuration page (/admin/config/content/formats), the top format in the list that the user has permission to will be set as the text format automatically when saving the field (entity). If you only have a text format or two, this will work, but it is easily breakable, so it's not a great solution.

Pros - easy.

Cons - easy to break if/when someone adds a text format or re-orders them. Hard to configure. Not stable at all.

**Solution 2:**

In your form defintion for the entity (or a \_form\_alter hook for the form), you can set the format as follows. Note that in this case, my field is keyed as 'message:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);

  foreach(\Drupal\Core\Render\Element::children($form['message']['widget']) as $element_index) {
    $form['message']['widget'][$element_index]['#format'] = TEXT_FORMAT;
  }

  return $form;
}

```

Note: Replace TEXT\_FORMAT with the key of the text format you want to use.

Pros - can be overridden as part of the form by other developers

Cons - can be overridden as part of the form by other developers (if you want to ensure that the text format is always the same and cannot be changed)

**Solution 3:**

In your entity definition, first add this function (again, my field is keyed as 'message'):

```
public function setMessageFormat($format) {
  $this->get('message')->format = $format;

  return $this;
}

```

Then you can add a preSave() method to the entity definition to set the format:

```
public function preSave(EntityStorageInterface $storage_controller) {
  parent::preSave($storage_controller);

  $this->setMessageFormat(TEXT_FORMAT);
}

```

Note: Replace TEXT\_FORMAT with the key of the text format you want to use.

Pros - Ensures your text format is always what you want it to be for that field on the entity

Cons - cannot be changed by anyone else if you want this to be configurable.
> 3 votes

# Answer
Yes, this is currently not possible, see https://www.drupal.org/node/2004672. A text field is considered empty if there is no text, and if it is empty, then the default value isn't saved.

For configurable fields, there is https://www.drupal.org/project/allowed\_formats and other similar modules.

You could try setting a default value in either postCreate() or preCreate() but it is possible that this would be filtered out in the same way at some point. Would have to try to be sure. The only option that's left then is to do it in your form.
> 1 votes

---
Tags: 8, nodes, input-formats
---


# Question
Title: How can I set a view not to use the path previously set and be able to save the view?
I have some views I am not currently using. I want to disable the path, or leave it as *No path is set*.

All I get is the following message.

> Display "VIEW" uses a path but the path is undefined.

How can I set a view not to use the path previously set and be able to save the view?

# Answer
You should disable the view by going to
Structure -\> views
Inside views on the right side there will be a tab and when u click on it you can disable the view so that you can enable it for future use.
> 0 votes

# Answer
Use the dropdown on the right to disable the view
> 0 votes

---
Tags: views
---


# Question
Title: How to add programmatically region's class when region had block in D8?
I have one row three column region. How can I add custom class on each region when one of region is not work?

**When three regiosn work, classes will be below**

```
|------------|-------------|--------------|
|            |             |              |
|  region 1  |   region 2  |    region 3  |
|            |             |              |
|------------|-------------|--------------|
  col-sm-4      col-sm-4       col-sm-4

```

---

**When two regions work, classes will be below**

```
|-------------------|---------------------|
|                   |                     |
|  region 1         |     region 2        |
|                   |                     |
|-------------------|---------------------|
      col-sm-6             col-sm6

```

---

**When only one region work, class will be below**

```
|-----------------------------------------|
|                                         |
|               region 1                  |
|                                         |
|-----------------------------------------|
               col-sm-12

```

I use in `page.html.twig` like below. It worked for me but not good code for more column.

```
{% if page.region_1 and page.region_2 %}
  <div class="row">
    <div class="region_1 col-sm-6"> {{ page.region_1 }} </div>
    <div class="region_2 col-sm-6"> {{ page.region_2 }} </div>
  </div>
{% endif %}

{% if not page.region_1 and page.region_2 %}
  <div class="region_2 col-sm-12"> {{ page.region_2 }} </div>
{% endif %}

{% if not page.region_2 and page.region_1 %}
  <div class="region_1 col-sm-12"> {{ page.region_1 }} </div>
{% endif %}

```

I'm try using `hook_preprocess_region()` like below. Can I check regions condition in `hook_preprocess_region`?

```
function MYTHEME_preprocess_region(&$variables) {

  // Add class in header region.
  $region = $variables['elements']['#region'];
  $region_header = array(
    'region_1',
    'region_2',
    'region_3'
  );

  if (in_array($region, $region_header)) {
    $variables['attributes']['class'][] = 'col-sm-12';
  }

}

```

# Answer
> 0 votes
Check Block Class module for this

Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent element of a block. Hooray for more powerful block theming!

---
Tags: theming
---


# Question
Title: Commerce Discount Module : Free Products : n+x
Is someone using commerce discount module and customized free products quantity field for buy x and get y functionality ? If i set buy 1 get 1(free product qty) its not multiplying while user updating quantity on cart.for ex-

I added 1 product = 1 qty.if user increase product qty with 2,its remaining same.like 2 = 1

# Answer
Buy X Get Y offers (or "Per quantity" offers) are supported out of the box in the Commerce Discount Extra module, which we'd like to merge into Commerce Discount eventually:

https://www.drupal.org/project/commerce\_discount\_extra
> 0 votes

---
Tags: 7, commerce, entities, hooks
---


# Question
Title: What does combined block caching option 'DRUPAL_CACHE_PER_ROLE|DRUPAL_CACHE_PER_PAGE' do?
I understand that certain block caching options can be combined. What does it mean if I set the caching option of a block defined in code to `DRUPAL_CACHE_PER_ROLE|DRUPAL_CACHE_PER_PAGE`?

I am confused by the OR bitwise operator. Does this mean that the block will not only be cached by page, but also by role? For example, if User role A visits the same page as User role B, they will each see different cached versions of the block despite being on the same page?

# Answer
According to the documentation:

> Page and user settings can be combined with a bitwise-binary or operator; for example, `DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE` means that the block can change depending on the user role or page it is on.

In other words: When the block is cached, information about the user role and page are stored with it. The cached version is served only in situations where both the current user role *and* the current page match those of the cached block.

A good example in Drupal 7 core is the Author Information block (see block info, block view). It must vary by page, because every page can have a different author, and it must vary by role, because not every role may have permissions to view the author information.
> 1 votes

---
Tags: 7, blocks, caching
---


# Question
Title: create an commerce order list view with payment method
I would like to create simple orders list with chosen payment method.

Problem: If customer goes through checkout process at once (without returning from checkout review and changing payment method) there would be only one payment method for an order, which is ok.

However, if customer returns from checkout page and changes payment method and then completes checkout - the order has 2 payment methods attached to it.

Now, inside view I can add relationship to Commerce Order: Payment Transaction, which causes duplicates. So I choose Commerce Order: Representative payment transaction, which gives me only one payment method (Now I can use payment method field). Inside relationship I can select representative sort criteria - in my case it would be transaction id (descending). However, sorting does not seem to work. The view always outputs the first payment method chosen when creating the order.

Is anything wrong with the view or is it better option to delete the unused payment transactions?

Question: what is the recommended way of keeping only one (last) payment method.

# Answer
As per the "***... which causes duplicates ...***" in your question: you may be able to prevent those by using the Views Distinct module. From its project page:

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

Consider an example like so (with the duplicates included):

```
order id1 with payment id1
order id2 with payment id2
order id2 with payment id3
order id3 with payment id4

```

For this example, to only show the last payment method, sort by `payment id` (but *descending*!), and on the `order_id` filter repeats. So that only the last row for every `order_id` will be shown.

The new Views results with these changes applied for the above example should now look like so (with no more the duplicates related to `payment id2`):

```
order id1 with payment id1
order id2 with payment id3
order id3 with payment id4

```
> 2 votes

# Answer
You need to use *Relationship: Commerce Order: Payment Transaction* in relationships section, and require that relationship.

Then add the filter **(Transaction) Commerce Payment Transaction: Status (\<\> Failure)** or its reverse logic is one of "SUCCESS". Don't forget to add relationship to transaction for the filter

Last, no need to add "distinct" in the query if you don't have other stuff causing duplicates. I have such views working great in production sites.

**Update**: I searched my setup a bit but there's no "custom rule". I believe it depends on payment methods. Which means that if yours don't implement "failure" status, you need to create a custom rule. Anyway the strange in your config is that a transaction that was not followed until checkout complete is attached to the order! This is not logical and doesn't work so on my config.
> 0 votes

---
Tags: 7, views, commerce
---


title: How to connect database in php file?

text:
# Question
Title: How to connect database in php file?
I have a custom module and in this module I've a `.php` file and inside this file I need to insert the data into database. I am using below code:

```
  define('DRUPAL_ROOT', getcwd());
  header('Access-Control-Allow-Origin: *');
  include_once DRUPAL_ROOT . '../includes/bootstrap.inc';

  include_once DRUPAL_ROOT . '../includes/database.inc';
  include_once DRUPAL_ROOT . '../includes/database.mysql.inc';
  conf_init();
  drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
  $userid = $_POST['user'];
  $module_name = $_POST['module'];
  $name = "_user_role_".$userid;
  $fe_id = db_insert('role')
    ->fields(array(
      'name' => $name,
    ))
    ->execute();

```

Its give below error:

# Answer
`getcwd` gets the current working directory, i.e. the one you're executing the script from.

If you need `DRUPAL_ROOT` to refer to the root of your Drupal installation, run the script from that directory, not the one that contains your module.

If you want to execute it from the module directory, fix the paths to the includes in your script.
> 1 votes

# Answer
Your code has issue in first line it-self:

```
define('DRUPAL_ROOT', getcwd());

```

`getcwd()` as per described on PHP.net

> Gets the current working directory

Because of `getcwd()` your Drupal Root directory is set to your module directory and PHP isn't able to find `bootstrap.inc` and `database.inc`.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Class 'Drupal\user\Entity\User' not found when running drush
I am trying to run a drush on functional Drupal 7 site, however, the attempt of run `drush` ends with an error saying: `Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php, line 571`.

Any idea what may be happening?

Full output:

```
vagrant@1843vm:/var/www/drupalvm/drupal/web$ drush
PHP Fatal error:  Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php on line 571
[error]  Drush command terminated abnormally due to an unrecoverable error.
Error: Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php, line 571
[error]  Drush was not able to start (bootstrap) Drupal.
Hint: This error can only occur once the database connection has already been successfully initiated, therefore this error generally points to a site configuration issue, and not a problem connecting to the database.

Drush was attempting to connect to:
 drupal-version         :  7.50
 drupal-settings-file   :  sites/default/settings.php
 uri                    :  http://default
 db-driver              :  mysql
 db-hostname            :  localhost
 db-username            :  root
 db-password            :  123
 db-name                :  il
 db-port                :
 install-profile        :  standard
 db-status              :  Connected
 theme                  :  intelligent_life
 admin-theme            :  seven
 php-bin                :  /usr/bin/php
 php-os                 :  Linux
 php-conf               :  /etc/php/5.6/cli/php.ini
 drush-script           :  /usr/local/share/drush/drush.php
 drush-version          :  9.0-dev-g1c91f8b
 drush-temp             :  /tmp
 drush-conf             :
 drush-alias-files      :  /home/vagrant/.drush/drupalvm.aliases.drushrc.php
 root                   :  /var/www/drupalvm/drupal/web
 site                   :  sites/default
 modules                :  sites/all/modules
 themes                 :  sites/all/themes
 files                  :  sites/default/files
 temp                   :  /tmp
 %paths                 :  /var/www/drupalvm/drupal/web
                       sites/default
                       sites/all/modules
                       sites/all/themes
                       sites/default/files
                       /tmp`

```

# Answer
> 2 votes
I had the same problem, it's related to the Drush version used by the DrupalVM. You can change the Drush version in the config.yml file.

More info: https://github.com/geerlingguy/drupal-vm/issues/1020

---
Tags: drush
---


# Question
Title: How to resolve the Ajax error when trying to add a VBO Action to a Rule?
We've a large site running Drupal 7 with OG, Flag, Rules, etc.

OG uses a subscription model where you have to confirm you want to join a group (or leave a group) so we've decided to move to a Flag system that then uses rules to add (or remove) that user from the group. We previously asked a question asking how to apply flags retrospectively for group subscriptions using Organic Groups - you can find this in "How to apply flags retrospectively for group subscriptions using Organic Groups?".

As per the existing answer in that question, we created a view that shows users sorted by newest first. Some more details about that view:

* Fields are `User: Name` and `Bulk operations: User`.
* Filter Criteria is `User: Active` and that they are a member of a specific group.

We then go to add the Rule. When we try to add the action '***Load a list of entity ids from a VBO View***' a little **`Please Wait`**-message displays and then, after 15 seconds or so, I get an Ajax error like so:

```
Http Result Code: 500
Debugging Information follows:
Path: /system/ajax
Statustext: Internal Server Error
ResponseText: (this is blank/empty)

```

Have we done something wrong setting up the View, or could it be something wrong with the install that could be giving the error?

Here is an export of our view:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Bulk operations: User */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'users';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Field: Groups (field_group_collaborative) */
$handler->display->display_options['filters']['field_group_collaborative_target_id']['id'] = 'field_group_collaborative_target_id';
$handler->display->display_options['filters']['field_group_collaborative_target_id']['table'] = 'og_membership';
$handler->display->display_options['filters']['field_group_collaborative_target_id']['field'] = 'field_group_collaborative_target_id';
$handler->display->display_options['filters']['field_group_collaborative_target_id']['value']['value'] = '761';

```

There is no export of the rule as trying to build a rule gives a timeout AJAX error.

We've bumped up all the server/mysql/php settings.

Server error log

```
[
{
"disp_time": "2016-11-28 14:40:52",
"http_status": 500,
"id": 10,
"log_type": "varnish-request",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": "### - -  \"POST http://###.com/system/ajax HTTP/1.1\" 500 26 \"https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action\" \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36\" 30.616768360 miss pass request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\" \"-\" forwarded_for=\"###\""
},
{
"disp_time": "2016-11-28 14:40:52",
"http_status": 500,
"id": 9,
"log_type": "apache-request",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": "### - -  \"POST /system/ajax HTTP/1.1\" 500 26 \"https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action\" \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36\" vhost=###.com host=###.com hosting_site=### pid=2531 request_time=30614611 forwarded_for=\"###\" request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
},
{
"disp_time": "2016-11-28 14:41:22",
"http_status": 500,
"id": 8,
"log_type": "bal-request",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": "127.0.0.1 - -  \"POST /system/ajax HTTP/1.1\" 500 719 \"https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action\" \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36\" http_host=###.com affinity=\"-\" upstream_addr=\"###\" hosting_site=### request_time=30.616 forwarded_for=\"###\" upstream_status=\"500\" request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\" ssl_protocol=\"-\" ssl_cipher=\"-\""
},
{
"disp_time": "2016-11-28 14:41:22",
"id": 7,
"log_type": "drupal-request",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": " ###.com POST /system/ajax http_code=500 query= uid=11656 php_pid=7959 php_time=30.232 queue_wait=0 request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
},
{
"id": 6,
"log_type": "php-error",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": " PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 72 bytes) in /mnt/www/html/###/docroot/includes/database/database.inc on line 2200 request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
},
{
"disp_time": "2016-11-28 14:41:17",
"id": 5,
"log_type": "drupal-watchdog",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": " ###: https://###.com|1480344077|php|###|https://###.com/system/ajax|https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action|11656||Notice: Undefined property: view::$exposed_input in views_plugin_display_attachment->attach_to() (line 230 of /mnt/www/html/###/docroot/sites/all/modules/contrib/views/plugins/views_plugin_display_attachment.inc). request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
},
{
"disp_time": "2016-11-28 14:41:14",
"id": 4,
"log_type": "drupal-watchdog",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": " ### ###: https://###.com|1480344074|form|###|https://###.com/system/ajax|https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action|11656||Illegal choice all in type element. request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
},
{
"disp_time": "2016-11-28 14:41:14",
"id": 3,
"log_type": "drupal-watchdog",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": " ### ###: https://###.com|1480344074|form|###|https://###.com/system/ajax|https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action|11656||Illegal choice all in type element. request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
},
{
"disp_time": "2016-11-28 14:41:13",
"id": 2,
"log_type": "drupal-watchdog",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": " ### ###: https://###.com|1480344073|form|###|https://###.com/system/ajax|https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action|11656||Illegal choice all in type element. request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
},
{
"disp_time": "2016-11-28 14:41:13",
"id": 1,
"log_type": "drupal-watchdog",
"request_id": "v-a93ea8f4-b578-11e6-988a-22000a62068c",
"server": "###",
"text": " ### ###: https://###.com|1480344073|form|###|https://###.com/system/ajax|https://###.com/admin/config/workflow/rules/reaction/manage/rules_sandy/add/1/action|11656||Illegal choice all in type element. request_id=\"v-a93ea8f4-b578-11e6-988a-22000a62068c\""
}
]

```

# Answer
Not sure if it's what's causing your issue, but it looks like your issue is similar to "AJAX error 500 reported when trying to add certain actions": the AJAX error you included in your question is idential to what is in the issue description!

**Attempt 1**: As per comment 4 and 5: if you have the Universally Unique IDentifier module enabled, try to (temporary) disable that module. It might help to eventually get around it

**Attempt 2**: Related to the error about "*PHP Fatal error: Allowed memory size of 268435456 bytes exhausted ...*" in your server error log: try to (temporary) increase the allowed memory, just to eliminate the possibility that it's because you don't have enough memory available.

If none of this helps, then:

1. please try to add your feedback to this issue I mentioned (which is still in status "Maintainer needs more info").
2. Have a look at this answer as a possible alternative, which uses another technique, and therefor possibly doesn't cause this very same AJAX error.
> 1 votes

---
Tags: 7, rules, ajax, views
---


# Question
Title: How to clear or rebuild a cached block for a specific user?
I have a block with the cache setting `DRUPAL_CACHE_PER_USER`.

I want to clear the cache when a user performs a specific action. I want to clear the cached block only for the acting user, keeping the block cache for all other users.

How can I do that in Drupal 7?

# Answer
This data is stored in the `block_cache` bin under the cid format:

`<MODULE_MACHINE_NAME>:<BLOCK_MACHINE_NAME>:<THEME_MACHINE_NAME>:u.<UID>`

Knowing that, you can build some wrapper function for `cache_clear_all()` that will delete any arbitrary UID's cached block:

```
function clear_user_block_cache($uid, $module = 'MYMODULE', $block = 'MYBLOCK', $theme = 'MYTHEME') {
  cache_clear_all("$module:$block:$theme:u.$uid");
}

```

You can invoke this function call whenever the user takes the relevant action.
> 5 votes

# Answer
If you get an exception on cache\_clear\_all(), make sure you add the table name as second parameter. E.g: cache\_clear\_all('yourcidstring', 'fromThisDbTable');
> 0 votes

---
Tags: 7, blocks, caching
---


# Question
Title: Running Drupal code inspections via PHP Storm returns incorrect results
When I run PHP Code Sniffer inspections in PHP Storm (latest version) for Drupal code using the latest Drupal coding standards (from the Coder module), I get incorrect results. Running the inspections manually on the command line seems to return the proper results. I don't know why.

Here's the output of running phpcs manually against this test file from the CAS module:

```
/Users/bosborne/.composer/vendor/bin/phpcs --standard=/Users/bosborne/.composer/vendor/drupal/coder/coder_sniffer/Drupal tests/src/Unit/Subscriber/CasSubscriberTest.php

FILE: ...ules/contrib/cas/tests/src/Unit/Subscriber/CasSubscriberTest.php
----------------------------------------------------------------------
FOUND 11 ERRORS AND 4 WARNINGS AFFECTING 15 LINES
----------------------------------------------------------------------
  16 | WARNING | [x] Unused use statement
  99 | ERROR   | [x] Expected "MockCondition" but found
     |         |     "MockCondition;" for @var tag in member variable
     |         |     comment
 131 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 132 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 133 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 134 | ERROR   | [x] Array indentation error, expected 6 spaces but
     |         |     found 8
 135 | WARNING | [x] A comma should follow the last multiline array
     |         |     item. Found: ]
 148 | ERROR   | [x] There should be no white space after an opening
     |         |     "["
 149 | WARNING | [x] A comma should follow the last multiline array
     |         |     item. Found: ]
 162 | ERROR   | [x] There should be no white space after an opening
     |         |     "["
 163 | WARNING | [x] A comma should follow the last multiline array
     |         |     item. Found: ]
 177 | ERROR   | [x] Object operator not indented correctly; expected
     |         |     6 spaces but found 35
 193 | ERROR   | [x] Object operator not indented correctly; expected
     |         |     6 spaces but found 28
 194 | ERROR   | [ ] If the line declaring an array spans longer than
     |         |     80 characters, each element should be broken
     |         |     into its own line
 564 | ERROR   | [x] Inline comments must start with a capital letter
----------------------------------------------------------------------
PHPCBF CAN FIX THE 14 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

```

Lots of errors and warnings!

But when I configure my PHP Storm (latest version) to run the inspections on the same file, I get just two weak warnings, and the filedoc one it complains about is wrong (file docs are not required on namespaced files).

So something is out of wack here, but for the life of me I cannot figure out why PHP Storm is returning the wrong output.

Environment info:

* Using version 8.x-2.9 of the Coder module
* Using version 2.7 of phpcs
* Code Sniffer is setup in PHP Storm using the same exact path that I use when running the command manually (see config image below)
* Inspections are setup in PHP Storm to use "Custom" inspections and I proide the path to the Drupal coding standards (the same path that I use when running it manually)

**EDIT:** I also filed an issue with PHP Storm directly: https://youtrack.jetbrains.com/issue/WI-34029

# Answer
OK - Embarrassingly enough, this was indeed "user error". The path to the coding standard that PHP Storm was using was indeed slightly different than the path I thought it was using. The paths were quite similar so I didn't catch it during my own reviews.

What helped is that you can configure PHP Storm to output the exact command it runs in the debug log by doing the following: Open Help \> Debug Log Settings and add there `com.jetbrains.php`. Then run the inspection and look at the debug log.
> 0 votes

---
Tags: 8
---


# Question
Title: Load AJAX form on every page via drupal_get_form
I'm trying to load this contact form on every page via drupal\_get\_form()

```
<?php
function MYMODULE_menu() {
    $items = array();
    $items['contact'] = array(
        'title' => t('Contact'),
        'description' => t('Contact'),
        'page callback' => 'contact_page',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK
    );
    return $items;
}

function contact_page () {
     $output = '<div id="ajax_contact_form">'.drupal_render(drupal_get_form('ajax_contact_form')).'</div>';
}

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

    $form['submit'] = array(
        '#type' => 'submit',
        '#ajax' => array(
            'callback' => 'ajax_contact_callback',
            'wrapper' => 'ajax_contact_form',
            'name' => 'submit1',
            'method' => 'html',
            'progress' => array(
                    'type' => 'throbber',
                    'message' => t('Message is sending...'),
                ),
        ),
    '#value' => t('Send'),
    );
    $form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="box">',
    '#suffix' => '</div>',
    );
  return $form;
}

function ajax_contact_callback($form, &$form_state){
    drupal_validate_form('ajax_contact_form', $form, $form_state);
    $name =  $form_state['values']['name'];
    if (form_get_errors()) {

        $form['box']['#markup']='<div class="ajax_message ajax_error" >'.t('Please check your fields!').'</div>';
        $form_state['rebuild'] = TRUE;
        return $form;
    }
    return $form;
}
?>

```

Basically everything is works on /contact page but when I try to load this form from page.tpl.php. It doesn't want to validate. What should I do?

```
<?php  print render(drupal_get_form('ajax_contact_form'));  ?>

```

Here

# Answer
I solved this issue, problem was in `'wrapper'` so this is how it works

```
<?php  print '<div id="ajax_contact_form">'.drupal_render(drupal_get_form('ajax_contact_form')).'</div>';  ?>

```
> 0 votes

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


# Question
Title: View of users flagged by a user, users flagging a user, and nodes from users flagged by a user
I have a user flag that is pretty much like a "*follow*" or "*subscribe*" function.

Basically I want to create 3 `views` for my website's `user profile` pages:

> 1. A list of users flagged by a user (e.g. a "people i'm following" block)
> 2. A list of users flagging a user (e.g. a "my fans" or "my followers" block)
> 3. A list of nodes from all the users that have been flagged by a user (i.e. a news feed function for a user to view all the new content from the users he/she flagged)

Would appreciate any help or comments!

# Answer
Better late than never, To get your followers of fans you can:

1. create a view of type users.
2. create a relationship Flags: User's flaggings.
3. now this is were most people go wrong you should remove "Include only users who have flagged content."
4. chose your flag.
5. Add Contextual filter "Flags: Content ID".
6. make sure to use the relationship.
7. WHEN THE FILTER VALUE IS NOT AVAILABLE provide default value of "user Id from logged in user".
> 4 votes

# Answer
The first scenerio can be attained by doing the following (in drupal 7)

1. Add the 'Flags: \[flag type\]' relationship, and set 'By' to 'Any user.'
2. Add the 'Flags: User' relationship; don't set any options for it.
3. Add the 'User: Uid' contextual filter, and set it to 'Provide default value' 'User ID from URL'.

if you are using panels, you have to make sure you pass the uid to the view.

still working on figuring out the other two scenarios, let me know if you hace any luck
> 1 votes

# Answer
I was struggling to get number 2, but thanks to this answer: How can I make a view that shows users all the who have flagged a single user?

1. Create a view of users
2. Add the relationship "User's flaggings" and uncheck the "Include only users who have flagged content" checkbox.
3. Add a contextual filter "Flags: entity ID", and choose the method to provide a default value - in my case, get User ID from URL.
> 1 votes

# Answer
A list of users flagging a user (i.e. a "my fans" or "my followers" block)

1. create a new view, based on users.
2. add relationship Flags: User's flagged content
    * ACTIVE : Include only users who have flagged content.
    * Choose your flag name

thats it.

Perhaps you want to add a filter to filter out your own name ..
> 0 votes

# Answer
I believe I figured out how to configure number 1 and 3.

1. Create a view of Users (rather than content).
2. Add the flag as a relationship (the flog following or whatever you call it) and add By "current user". This should get you a list of the users you are following.
3. Add "User: Content Authored" as another relationship this should give you a duplicate row for every piece of content that the user has authored.

Now you should be able to use fields to omit or ad whatever info you want.
> 0 votes

# Answer
Yes, that's the right answer, user379468!

Instead of the third point use:

1. Add the "User: Content Authored"
2. Add the "User:uid" contextual filter
3. Add the "(Author) flags: (name\_of\_your\_user\_flag)" relationship
> 0 votes

---
Tags: views, nodes, users, flags
---


# Question
Title: Migration tries to create existing entity
I have a D8 migration where I pull remote resources and for each one I create new entity object, apply the resource onto the entity via custom methods on that entity and return the data for this resource as $entity-\>toArray(). This is how my iterator is getting build. So basically it is an array of entity definitions.

On the target entity I have a field called 'name' which is a unique fields so no two entities with the same 'name' can exist. In the migration I have this field as id key. But for some reason when I run the migration it tries to create a new entity and so the UniqueField constraint will prevent the entity to be saved(I am doing validation in entity's preSave() method) and my migration will fail.

And I cannot figure out why it won't match the existing entity if the 'name' field has a value(I have checked this on multiple places in the code).

The only thing I can come up with it so try to load an existing entity in the prepareRow() myself but that seems as very strange approach and I could basically just completely scratch the migration and write a simple batch.

---

This is my iterator:

```
  /**
   * {@inheritdoc}
   */
  protected function initializeIterator() {
    $items = $this->getResourceEntity()->getResourcePlugin()->loadAll();
    $storage = $this->entityManager->getStorage($this->getDerivativeId());

    $items = array_map(function($resource) use ($storage) {
      $entity = $storage->create();
      $entity->resourceMap($resource);
      return $entity->toArray();
    }, $items);

    return new \ArrayIterator($items);
  }

```

---

After debugging `\Drupal\migrate\Plugin\migrate\id_map\Sql::sourceIdFields` and `\Drupal\migrate\Plugin\migrate\id_map\Sql::destinationIdFields` it looks like it tries to map `'name' => 'id'` fields for some reason instead of `'name' => 'name'`.

I guess that is because the destination plugin(content entity) returns the entity id field which in this case is `id` in `\Drupal\migrate\Plugin\migrate\destination\EntityContentBase::getIds`.

## I guess I am missing some crucial information here on how the migrations work.

So yeah, I had to use 'id' in getIds(), and in the iterator I had to try to figure out entity id of an existing entity.

# Answer
> 2 votes
It's rather premature to create an entity at the source plugin, when the destination plugin will create the entity for you... It's much simpler for the iterator to simply produce an array of fields representing the raw data, have the process pipeline map those source fields to the Drupal destination entity's field names, and have the destination plugin 'entity:my\_entity' create and save the entity to Drupal.

---
Tags: 8, migrations
---


title: Paragraph Component reporting via Views

text:
# Question
Title: Paragraph Component reporting via Views
I would like to create a View that allows me to see where Paragraph Components are being utilised.

It would just need to be a basic tabular View consisting of the following fields:

* Paragraph Component Type / Name
* Parent Node Title
* Parent Node URL

Using exposed filters on the View it would then be ideally possible to filter by Paragraph Type so that you can easily see what nodes / pages are using what Paragraph Component Type / Name.

Is this possible through the Views UI? I have tried setting relationships between the node / field / entity, but can't get it to join up.

# Answer
I think I got it.

1. Install the Entity Reference module
2. Go to view and add a relationship in the advanced section
3. Search for your paragraph embed field and set the identifier as anything as you want
4. Add your paragraph fields by searching for the fields in the paragraph bundle
5. Click save and done!
> 0 votes

---
Tags: 7, views
---


title: How to prevent scan by drupalxray

text:
# Question
Title: How to prevent scan by drupalxray
A website called Drupal X-Ray can detect a Drupal site's Drupal version and modules in use. So if I don't want others to find that information, what can I do?

# Answer
You can look at deploying a site and scrubbing it of files like CHANGELOG.txt/INSTALL.txt automatically. Other things, like removing the meta generator tag in the head also can hide that it is Drupal, but nothing is bulletproof. For example, typing 'Drupal' in the browser devtools window is another way to tell if a site is Drupal or not (in most cases). You could also try banning requests originating from that domain/service at the server level.
> 1 votes

---
Tags: database
---


# Question
Title: In Drupal 8, how to automatically create a term in a specific vocabulary from the field present in node/add page?
Steps to reproduce -

* Create two new vocabularies at - `SITE/admin/structure/taxonomy/add`
* Add them as fields to the article content type. Set number of values to be unlimited, set form display to `Autocomplete (tags style)`
* The new vocab fields do not work like the Tags field

Could you help me learn how to automatically create a term in a specific vocabulary from the field present in node/add page?

# Answer
> 4 votes
Thanks to a colleague, I found the setting I had to use.

1. Go to - `SITE/admin/structure/types/manage/article/fields/node.article.field_vocab_a_tag`
2. Check - `Create referenced entities if they don't already exist`

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


# Question
Title: Why Are Changes / Updates to User Account Fields Not Persisted (Lost on Page Refresh)
Drupal version 7.52.

Updating a user account page, e.g. changing their email or name, results in the page being reloaded with the changes persisted in the form, but when you refresh the page the changes are lost.

It's as if some validation errors are blocking the user update function but no feedback is being displayed.

Checked all logs and no errors reported.

# Answer
> 0 votes
Turns out it was down to Clientside Validation modules. I disabled the following and it now works as expected:

* `clientside_validation_fapi`
* `clientside_validation_field_validation`

The other clientside validation modules work fine, just these two seem to block updates to user accounts with no errors, warnings or notices.

---
Tags: 7, forms, users
---


# Question
Title: Why doesn't drush respond to commands after install
# Setup

I just followed the directions on the drush website for installing drush.

I performed the command `php -r "readfile('http://files.drush.org/drush.phar');" > drush`

Then attempted the next command `php drush core-status` which resulted in lots of text basically saying "Permission Denied".

So I went ahead and performed the next direction which makes the scripts executable. `chmod +x drush`

# The Problem

I then attempted `php drush core-status` again.

Now the console just sits there when I type the command. It displays nothing and never released back to prompt. I had to ctrl+c to free up the console.

# The Question

What am I doing wrong here? Are their dependencies on drush that are not listed in the install document? Is their some way to see errors that are not printed to the console?

I was using php 5.4 originally but updated to 5.5 and that did not solve the problem. CentOS 6.7.

# Answer
At the time of my comment the phar for drush wasn't working correctly. That very well may be fixed by now, however, I've still found installing drush via composer to be the easiest solution.
> 1 votes

# Answer
Verify that your server has the package php5-suhosin enabled. Disable it or add the following to suhosin.ini file (etc/php5/conf.d/suhosin.ini): `suhosin.executor.include.whitelist = phar`
> 0 votes

# Answer
You should be calling drush on its own, in the root of the Drupal install:

```
drush core-status

```
> -1 votes

---
Tags: drush
---


# Question
Title: How do I treat the phrase as individual words in Search?
I have a problem in our Search results. We are using Search API and Search API Solr modules running in drupal 8.

We have successfully indexed our content in Solr and is pretty working.

For example, I have a term called "Jakarta Law firm" and it will display the results like: Jakarta Law Firm in 2000, Jakarta Law Firm in 2001, etc.

However, if I searched "law firm Jakarta", it will return no results. Can you please tell me if there are any configurations in Solr or in the module so that it will search whatever the order of the search words? Or may I know what is the Solr term functionality that will handle that? Or any hooks that we can use?

I really appreciate your help about this!

# Answer
> 2 votes
When adding text fields to your search index, you need to indicate it's usage by specifying if you want it to be a Fulltext field or a String field.

You can add the field twice, once a String and once as a Fulltext field.

If you are using views, you'll want to make sure your full text search exposed filter includes the Fulltext version of this field, and is set to "Contains any of these words"

---
Tags: 8, search
---


title: Front-end on a different domain

text:
# Question
Title: Front-end on a different domain
I'm using drupal8 in headless mode. So I have a backend on Drupal8, and a frontend in JS. I'd like to have content URLs in drupal8 to point to the frontend domain and not the backend (which doesn't have any templates to display the content).

backend.example.com/mycontent for Drupal8 www.example.com/mycontent for the frontend

How can I do to update all the links in UIs to have the frontend domain in place of the backend domain ? (views or admin/content or breadcrumb on edit form).

# Answer
You can try using the Domain access module that does the work. Version 8.x works with not issues. Go ahead and use it with no fear.
> 0 votes

---
Tags: 8
---


# Question
Title: Printing fieldable panel pane custom field in template properly
I've created a fieldable panel pane that has two fields, a title and a body. My template file looks like this:

```
<div class="sidebar-pane">
    <h2 class="pane-title">
        <?php print render($content['field_pane_title']); ?>
    </h2>
    <div class="pane-content">
        <?php print render($content['field_body']); ?>
    </div>
</div>

```

This seems fairly basic. Now, when I actually add one of these panes to a page, this is the DOM that is spit out:

```
<div class="sidebar-pane">
    <h2 class="pane-title"></h2>
    <h3 class="field-label"></h3>
    Test Pane

    <div class="pane-content">
        <h3 class="field-label"></h3>

        <p>This is a test body.</p>
    </div>
</div>

```

Ignoring the fact that it's printing out empty field-label elements, why is the pane-title field being printed outside the pane-title h2 element? Is there a better way to be doing this? Thanks!

# Answer
Ignoring the empty field-labels was a problem! The issue was with those field labels, which were generated by the Fences module. They were somehow causing the h2 to close too early.

I ended up modifying the module myself, so that the template checks if a field label exists before adding it to the DOM.

I also ended up finding an issue on the module's issue page which has a patch to fix it directly, in case anyone is interested: https://www.drupal.org/node/2605808
> 0 votes

---
Tags: theming
---


# Question
Title: Deleting a cloned node erases all paragraphs
Suppose node A contains a paragraphs field with a paragraph entity X. Duplicating the node by means of Node clone will create a new node - let's call it node B - with an exact copy of paragraph X. It is even possible to change the contents of X in node A and B independently. But when A or B is deleted, X will be erased from *both* nodes. Obviously this is because there has never been created a new entity when replicating the paragraph, but only a new entity revision.

For Drupal 7, this behavior is documented in Paragraphs data loss with Node clone module and at least partly fixed by a patch. But none of this seems to be the case for the Drupal 8 dev version of Node clone. Has anyone found a solution or workaround for this issue?

Drupal 8.2.0

Paragraph 8.x-1.0+14-dev

Node clone 8.x-1.x-dev

# Answer
Paragraph in 8.x integrates with the replicate project only at the moment: https://www.drupal.org/project/replicate

If you use that, cloning a node will also create clones of the used paragraphs.
> 3 votes

---
Tags: 8, entities
---


title: Adding icons to field labels

text:
# Question
Title: Adding icons to field labels
How do I add icons next to field names, like adding a phone icon in front of the mobile phone field?

i tried the patches shown in https://www.drupal.org/node/2050257, but they do not seem to work.

I have seen this on some websites, so I guess it should be possible.

# Answer
You can change the label using the template\_preprocess\_field hook.

For instance, if your field was named "phone" and the content type was "business", you could add this to your template.php:

```
template_preprocess_field (&$variables) {
  $content_type = $variables['element']['#bundle'];
  $field_name = $variables['element']['#field_name'];

  if ($content_type == 'business' && $field_name == 'phone') {
    $variables['label'] = '<img src="http://www.carloancentre.ca/wp-content/uploads/2014/03/Contact-Methods-Phone-icon.png" height="16" width="16"/>' . $variables['label'];
  }
}

```
> 1 votes

# Answer
You can solve using css

```
#field-name {
  background-image: url('image/path/ico_phone.png');
  background-repeat: no-repeat;
  background-position: left center;
  padding-left: 16px;
}

```
> 1 votes

# Answer
you need to create field template file and apply css.

see this links : https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7
> 0 votes

# Answer
you need create #field\_prefix , add HTML image or element icon font into `#field_prefix` ! Read Document about form API Drupal
> 0 votes

# Answer
I will advice to fix this issue by using the CSS injector module to add the necessary CSS styles to show an icon before the field label.

> Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme. The CSS is added using Drupal's standard `drupal_add_css()` function and respects page caching, etc. The 2.x brach leverages CTools so CSS can be included with Feature changes (ie. CSS that improves the look of a View can be packaged with the View).
> -1 votes

---
Tags: 7, entities
---


# Question
Title: Drupal Commerce Hook - Extra validation before adding to cart
I was looking for a hook that will fire after a user hits the add to cart button. The commerce api isn't very clear about this.

What I'm trying to is: Add an extra validation for a customized product (date field). So basically I want to interrupt the adding to the cart process and proceed if validation is ok, and lead the user back if not.

Thanks!

# Answer
> 1 votes
Seems like hook\_commerce\_cart\_product\_add is what you're after. I couldn't find any examples for preventing the line item being added to the cart but at the very least you should be able to use drupal\_goto to interupt the process. You might also want to look at the Rules events\actions provided by Commerce.

# Answer
> 0 votes
You will want to run a `hook_form_alter` to add your own validation callback. An example may look like the following.

```
/**
 * Implements hook_form_alter().
 */
function commerce_stock_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, "commerce_cart_add_to_cart_form") === 0) {
    $form['#validate'][] = 'mymodule_add_to_cart_validate';
  }
}

```

Your call back can then check `$form_state['values']['quantity']` or `$form_state['values']['product_id']`, for example, to check quantity and the product added.

A great example of hooking into the add to cart form is in the Commerce Stock module, for advanced usages: http://cgit.drupalcode.org/commerce\_stock/tree/commerce\_stock.module#n64

# Answer
> -3 votes
Maybe this post can help you. https://www.drupal.org/node/1292742

---
Tags: hooks, commerce
---


# Question
Title: How to create notifications like Facebook about pending workflow approvals?
Is it possible in Drupal 8 to setup notification bar as in Facebook?

**Update**:

I have different roles and I am using workbench for applying workflow. I have three transition attached with role like draft, approved, published. When user like reporter who have only draft transition going to save content at that time a user like editor who have right for transition like approve will get notify on screen when login.

# Answer
Have a look at one of the answers to "Notification + Subscription: Can this combination recipe be used to create notification system similar to Facebook's?", which explains how the Menu Badges module can be used for this. The result of using it looks as in this example:

The current status of this module for D8 is like so:

> The 8.x-1.x-dev release includes all the functionality of the Drupal 7 version. However, it is not yet completely working with the new caching that Drupal 8 does. Badges are getting cached and don't change when they should. Once that is fixed, a stable release will be created.

To implement it for supporting what you decribed in your *update*, you only have to create an appropriate view (using views) with as results the updated content that the editor should be notified about.
> 0 votes

---
Tags: 8, notifications, workbench
---


# Question
Title: Can't find "Site Configuration > Image Caption" configuration settings
Can't find "Site Configuration \> Image Caption" configuration after image\_caption has been installed.

I installed latest version of image\_caption from https://www.drupal.org/project/image\_caption.

The module is enabled but no configuration settings.

Under Configuration, there is no input filter.

In text format, can't find any image caption settings.

# Answer
The D7 version of module doesn't provide configuration under "Admin =\> Site Configuration =\> Image Caption". "**Site Configuration**" was available in D6 version, in D7 it is called as "**Configuration**".

I've just tried the D7 version of module, there are 2 modules and it is as below:

1. **Image caption** (main module) : This module doesn't define any configuration, it by default check if `<img>` tag in page body has `caption` class or not. If yes, then it takes the `title` attribute value and add caption.
2. **Image caption filter** (sub-module) : This module defines configuration under ***Admin =\> Configuration =\> Text Formats*** settings (see screenshot below). To process the images uploaded in Text Area.
> 1 votes

---
Tags: 7, media
---


# Question
Title: What entity type should I choose for a comment type?
When I add a comment type (for example, *Blog comments*), I can select an entity type as target for the comment.

What should I choose and why?

Is it *Custom block* or *Comment*? My intuition says to pick *Comment*, but I don't know on what basis I should decide what to pick.

The other option seems in any case less likely for my case. I just need a global article comment type.

>

# Answer
That depends to which entity you want to attach those comments. If the new comment type is for content types (node bundles), select the according type. (I assume it's one of the the last three list entries given in your screenshot.)
> 3 votes

---
Tags: 8, comments
---


# Question
Title: Programmatically customise fields in node views
I'm developing a module that exposes a node type (by the usual `hook_node_info()` and `hook_install()`) and a set of custom fields.

I would like to programmatically define what/how those fields have to be shown in the node views (at least "full"). For example: the field XYZ should be hidden in the "full" mode, and the field ABC should have the lable inline (I'm able to do this by UI, but I would like to define it programmatically).

In any case my need is to **exactly modify the view mode** (not to always hide a field), in order to allow users to modify the default visualisation way after installation, if necessary.

I can't figure what hook I have to implement, or what code I have to write in the `hook_install`.

Thank you for your help

# Answer
I want to share the solution I found, in order to help future readers.

In Drupal 7 the concept of "formatter" helpt to control the output of a field. For example this tutorial allow you to programmatically define a custom formatter for a given field.

Then by UI site admins (by `admin/structure/types/manage/<nodetype-name>/display`) are able to chose that formatter (or others) for any specific field.

If you want to declare a default formatter for a field, the best way seems to be while the install phase of the module. In that moment (At least in my case and in all tutorial I found on the Internet) you use a `field_create_instance` method to add a specific instance of a given field. According to the official documentation, you can also add the `display` options that exactly allow you to define the formatter to be used for a specific display (or the formatters if want to declare for more than one display).
> 0 votes

---
Tags: 7, entities
---