# Question
Title: How do I use the global class \Drupal static methods to access services?
Is there a difference between calling `\Drupal::service('config.factory')` and `\Drupal::configFactory()`?

Is it better to use the second one?

Can `\Drupal` be used to do something else than calling services?

The documentation says:

> Accessing services in global functions
>
> The global Drupal class provides static methods to access several of the most common services. For example, Drupal::moduleHandler() will return the module handler service or Drupal::translation() will return the string translation service. If there is no dedicated method for the service you want to use, you can use the Drupal::service() method to retrieve any defined service.

In which cases isn't there any dedicated method? How do I easily list all the retrievable services?

# Answer
> 2 votes
`\Drupal::configFactory()` is just shorter than `\Drupal::service('config.factory')`. The fact that with `\Drupal::configFactory()` you aren't hard-coding the service name in your module is not probably a reason to choose it, since you would still hard-code most of the service names (the dedicated methods don't even cover a quarter of all the available services), and the chances that a service name is changed are probably low now that Drupal 8 has a stable release.
When there is a dedicated method for a service I am using in my module, I much prefer using that dedicated method, and I prefer using dependency injection over using the static methods `\Drupal` has.

The purpose of the \Drupal class is giving access to the services provided from Drupal or third-party modules; even `\Drupal::request()` is calling a service's method. So, no, you don't use \Drupal for things that aren't services; even in this case, you should not depend from that class, if it is possible to use dependency injection.

For a list of the services implemented by modules, you need to look at the .services.yml files provided with the modules, including the core modules. Those files give you a list of services implemented by modules; it's impossible to give an exhaustive list since every module can implement all the services it needs.

# Answer
> 6 votes
`\Drupal::service('config.factory')` and `\Drupal::configFactory()` are equivalent; the second is just shorter.

There are many, many services provided by core, and only a few of them have a dedicated method. You can get a list of core services on the core.services.yml page. Note that this is not all services that core offers, for example, there are more services in user.services.yml.

Also note that when working with classes, it's better to use dependency injection rather than calling static methods. Static methods should be called in procedural code (in D8, this basically means hooks, or API functions).

This is a slideshow I used when doing a presentation on dependency injection at Drupal Camp Tokyo this month.

---
Tags: 8, services, dependency-injection
---


# Question
Title: Why is my file upload always NULL in $form_state?
I've build a form where the user can upload an image as avatar for his profile. But I have an issue as the selected image is not being recognized at all.

I used the image example from drupal.org, this is my minimal code not working at all:

```
function my_edit_form($form, $form_state, $entity) {

  $form['picture']['picture_upload'] = array(
    '#type' => 'file',
    '#title' => t("Upload picture"),
    '#description' => t("Your virtual face or picture. Pictures larger than 150x150 pixels will be scaled down."),
    '#upload_location' => 'public://pictures/',
    '#size' => 48,
  );

  return $form;
}

```

Now, I'm trying to use the `file()` functions as described in the documentation but it seems my `$form_state['values']['picture']` is always `NULL`.

```
function my_edit_form_submit($form, &$form_state) {
  dpm($form_state);
}

```

I have no idea how that's possible and I'm a bit lost here. Any idea what else I could try?

# Answer
> 6 votes
Okay, this is tricky how Drupal handles the file uploads and took me some time to figure out.

`$form_state` indeed shows NULL or empty strings or empty arrays for my file upload **unless I add a proper upload function**. The file exists but is not uploaded yet.

It's worth taking a look at `user_validate_picture()`:

```
function user_validate_picture(&$form, &$form_state) {
  // If required, validate the uploaded picture.
  $validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  );

  // Save the file as a temporary file.
  $file = file_save_upload('picture_upload', $validators);
  if ($file === FALSE) {
    form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
  }
  elseif ($file !== NULL) {
    $form_state['values']['picture_upload'] = $file;
  }
}

```

Calling this function from inside my own validation function will upload the file to `temporary://What-is-Sustainability_0.png` and it's now visible in `$form_state['values']`:

This is what I was looking for, now I can simply save the file where I need it and have the `fid` available to link it to entities.

# Answer
> 4 votes
For Drupal 8:

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

    parent::validateForm($form, $form_state);

    $validators = array(
        'file_validate_extensions' => array("pdf"),
        'file_validate_size' => array(file_upload_max_size()),
    );

    // Save the file as a temporary file.
    $file = file_save_upload('field_upload', $validators, FALSE, 0, FILE_EXISTS_REPLACE);
    if ($file === FALSE) {
        $form_state->setError($form["field_upload"], "Failed to upload the file");
    }
    elseif ($file !== NULL) {

        $form_state->setValue("field_upload", $file->toArray());
    }

}

```

---
Tags: forms, media, users, files
---


# Question
Title: Create views have field image with multil image style?
I want create view like this

You can see this view have two image style (name are 700x700 and 263x132). I want use two image style because it's faster when the page loading.

So how can do that with views?

# Answer
> 4 votes
You can use Views "Attachment", so you can create main View to display only first two items, then you can create "Attachment" with different markup (remeber to apply this only for current format) and skip first two elements and then attach it to the main view (after it). Sorry for my english ;)

---
Tags: views, 8, media
---


title: Drush path settings

text:
# Question
Title: Drush path settings
I'm fairly new to terminal and very new to Drush - I've installed Drush on my VPS using Composer and when I ssh as root all works fine. However I realise I shouldn't be using root so am trying to set up using another user but keep getting:

```
env: drush: No such file or directory

```

I realise this is something to do with the path to drush but cannot work out what I've got wrong. Here are my .bashrc and .bashprofile contents:

ROOT .bashrc:

```
# .bashrc

# To fix 'stdin is not a tty' error with Drush alias connections
export PATH=$PATH:~/.composer/vendor/drush/drush
[ -z "$PS1" ] && return

# User specific aliases and functions

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

```

ROOT .bash\_profile:

```
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin
PATH="$HOME/.composer/vendor/bin:$PATH"
export PATH

```

USER .bashrc:

```
# .bashrc

# To fix 'stdin is not a tty' error with Drush alias connections
export PATH=$PATH:~/.composer/vendor/drush/drush
[ -z "$PS1" ] && return

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# User specific aliases and functions
alias drush='~/.composer/vendor/drush/drush'

```

USER .bash\_profile

```
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin
PATH="$HOME/.composer/vendor/bin:$PATH"
export PATH

```

I've googled lots of solutions and tried various things so may by now have a bit of a mash up of things in these files!

# Answer
> 2 votes
You installed Drush in ~/.composer/vendor/drush/drush. You could instead use this alternative method.

> If you need Drush installed for all users on a system using Composer, install Composer globally then follow the steps below.
>
> Important: Run these shell commands as a privileged user with write access to /opt and /usr/local/bin or prefix with `sudo`.
>
> ```
> # Create and/or navigate to a path for the single Composer Drush install.
> mkdir --parents /opt/drush-8.x
> cd /opt/drush-8.x
> # Initialise a new Composer project that requires Drush.
> composer init --require=drush/drush:8.* -n
> # Configure the path Composer should use for the Drush vendor binaries.
> composer config bin-dir /usr/local/bin
> # Install Drush.
> composer install
>
> ```

For Drush 8, the alternative method is described on Install (alternatives) / Install a global Drush via Composer.

> Follow the instructions below:

1. Install Composer globally.
2. Install the cgr tool following the instructions in that project.
3. Add Composer's bin directory to the system path by placing `export PATH="$HOME/.composer/vendor/bin:$PATH"` into your ~/.bash\_profile (Mac OS users) or into your ~/.bashrc (Linux users).
4. Install latest stable Drush: `cgr drush/drush`.

For latest Drush releases, it's recommended to add it as Composer dependency, but not globally.

# Answer
> 2 votes
`env: drush: No such file or directory` is most likely coming from the line in your `.bashrc` file pointing to a non-existant file/directory called drush.

Since you say you're new to terminal and drush, here's a little background of what I think is happening: The squiggly line ~ ('Tilde' iirc?) is a shortcut in terminal. It means *my home directory*. So if your *root* user's `.bashrc` contains a directory path starting with tilde, for example `~/.composer/vendor/drush/drush`, this is basically pointing to `/home/root/.composer/vendor/drush/drush`. When the `.bashrc` file in *your user's* directory has the exact same line, it points to a different directory, because of the tilde. Yours will be pointing to `/home/iain-g/.composer/vendor/drush/drush` (hypothetically, if your linux login is `iain-g`).

You can't simply point to `/home/root` from your own `.bashrc` either, since you won't have permission to access the root user's home directory.

So what you need to do is:

* Uninstall the drush you have installed for root user (otherwise you may get issues later on with 2 drushes). This may not be necessary but it's nice to clean up after yourself.
* Install Composer globally. You're most likely safe to go with `/usr/local/bin/` as the directory to put the `composer` file in. But if you're unsure you can type `echo $PATH` in terminal and you'll see all the directories in your PATH environment variable, you can put composer in almost any of these directories.
* Install Drush For ALL USERS via Composer (see 2nd heading). It's only about 5 commands. And they're written for you. Just copy and paste and execute them line by line.

---
Tags: drush
---


# Question
Title: How to prevent performance issues when checking a large list of nodes using Rules?
Please, advice me on such a question about the Rules module.

**Background:** I have two types of users and 2 types on content. Each user can create one type of content. User of type2 can create a content of content\_type\_2 which has an entity reference field to a node of content\_type\_1. But this user should have a limit - such user may reference a node of content\_type\_1 only once.

**How I implemented it:**

* rule is triggered when user\_type2 is visiting content\_type\_2 node-add form. A NID of reference to content\_type\_1 is present as URL parameter.
* rule fetches nodes by property (where author is current user)
* for each item of the list of fetched entities is triggered another one rules component
* component checks is current list item is of "content\_type\_2"
* component checks current list item's entity reference field (nid of the referenced node) is equal to the nid value from URL parameter.
* if both conditions are true - prevent node saving and display and error message.

It works fine and does it's job. But I worry about the following: what will happened if a user of user\_type2 already has let say 10000+ of nodes of content\_type\_2? Does it mean that "fetch entity by property" will query for all that number of nodes at once? Can it highly slow down my site performance?

If it is true, maybe there is a better way of organizing this checking process? Will be thankful for any comment and advice!

**UPD 1 (to make the question more clear):**

* User type "Client" can create nodes of type "Request" .
* User type "Provider" can create nodes of type "Proposal".
* "Proposal" type has entity reference field to "Request" node (only 1 value allowed, it is required).
* Provider can create multiple number of "Proposal" nodes.
* But he has to be restricted to create only 1 "Proposal" per a certain "Request" node. So he should not be allowed to reference a "Request" node if he has already referenced it in any of his previous Proposals.
* Reference field is filled automatically ("Provider" can't do it by hands). "Provider" also can't edit any of published Proposals, but can delete any of them.

**UPD 2 (Rules export)**

Reaction Rule which is triggered at "node/add/proposal"

```
{ "rules_check_unique" : {
    "LABEL" : "Check Proposal is unique per Request",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "business_custom" ],
    "REQUIRES" : [ "rules", "rules_url_argument" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node\/add\/proposal" } },
      { "rules_url_argument_argument_exists" : { "argument" : "field_request_reference" } }
    ],
    "DO" : [
      { "rules_url_argument_rules_action_get_argument_from_url" : {
          "USING" : { "type" : "integer", "argument_name" : "field_request_reference" },
          "PROVIDE" : { "argument_from_url" : { "argument_from_url" : "Argument from URL" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "author",
            "value" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_if_proposal_is_already_posted_for_a_request" : { "cnid" : [ "argument-from-url" ], "proposal" : [ "list-item" ] } }
          ]
        }
      }
    ]
  }
}

```

Component Rules which check if Proposal for the referenced Request already exists

```
{ "rules_if_proposal_is_already_posted_for_a_request" : {
    "LABEL" : "If proposal is already posted for a request",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "cnid" : { "label" : "Current NID", "type" : "integer" },
      "proposal" : { "label" : "Proposal", "type" : "node" }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "proposal" ],
          "type" : { "value" : { "proposal" : "proposal" } }
        }
      },
      { "data_is" : { "data" : [ "proposal:field-request-reference:nid" ], "value" : [ "cnid" ] } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "You have already made a proposal for this request.",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "node\/[cnid:value]" } }
    ]
  }
}

```

# Answer
> 2 votes
### Preface

Even though I didn't test it, I trust your rule (+ Rules Component) works. But, you really made it complicated. Moreover, it seems that your rule is using Rules Event "***Drupal is initializing***". You're right, you must use this event if you want to have Rules intercept something like "a node is ***going to be*** added". Because if you'd use something like "before saving content of type ABC", you wouldn't be able to STOP such saving (you would be too late).

But using that Rules Event also implies that this rule gets triggered for *every* (repeat *every*) page load on your site, and each time at least the Rules Condition to check for that `node/add/proposal` path has to be performed. So only because of using that Rules Event, I think you should try to go for an alternative implementation to achieve the same goal. That goal is, if I correctly interpreted your question, like so: **A Provider can only reference a "Request" node in a single "Proposal"**.

Read on for a blueprint with some more details about how I would implement this ... (BTW: in D7).

### Step 1: Flag a Request after a Proposal was submitted

Use the Flag module to create a (non-global) flag to be used for flagging a node of type "Request", so that whenever a Provider submits a proposal, the referenced Request gets flagged by that Provider. So the flag is to indicated that such provider did submit a Proposal to the specific Request.

To actually do so, simply use the Rules module to do so (this is a kind of getting started with Rules, not further explained in this answer).

### Step 2: Create a view with an Entity Reference display

Create a view (with the Views module) to create a list of all the Requests that are allowed to be selected by a specific user. Some more details (specs) about the view to be created:

* The display type of such view must be an *Entity Reference* display.
* It should list all nodes of content type "Request".
* It should have a filter like "Not flagged (with the flag from Step 1) by the current user".

### Step 3: Adapt your Entity Reference field

Your entity reference field (to select from a filtered list of Requests) should be field that looks like so:

* Field Name = Anything you want, eg `field_requests_list`.
* Field Type = Entity Reference, using these additional settings for it:

+ *Target type* = `node`.
    + *Number of values* = `1`.
    + "Mode" (within "entity selection") = `Views: Filter by an entity reference view`. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an *Entity Reference* display, or add such a display to an existing view. In your case, you should select the view created in "Step 2".
    + Pick any of the other options to define this field as you see fit.

### Step 4: Disable your custom rule

After you completed the previous steps, there is no more need for your custom rule "Check Proposal is unique per Request", so at least disable that rule (and optionally just delete it). If this was the only Rule using your Rules Component, you might also want to delete that Rules Component (not needed anymore either).

### Step 5: Reduce the risk to run in a new (Views) performance issue

You have a valid point in the extra comment you posted below this answer, ie:

> If I have over 10000 nodes of type "Request" on the website which are not flagged by the current Provider, the view will query for all that number of stuff as I understand. Doesn't it influence the performance as well?

I don't expect such performance issue for as long as you have only like a few hundreds of nodes of type "Request". But for 10.000 nodes I'm not sure. However, if you also want to take away that risk, you could improve the above solution a bit further like so:

* Introduce an additional (non-global) flag, which a "Provider" must use to indicated something like "*I am interested in preparing a proposal for this request*".
* Improve the view in Step 2, by adding this additional flag as an additional filter of that view.

Obviously, the downside of introducing this extra flag is that the Provider must first "flag" relevant Requests. But the benefit of doing (enforcing?) so is that the number of results in your view will probably be limited to only a few (or a few dozens at max).

### Bottomline

After you completed the previous steps, you will:

* No longer use that Rule (+ related component) for which you wondered about its performance.
* You will have relevant business logic in place so that **a Provider can only reference a "Request" node in a single "Proposal"** (which IMO is what you're trying to implement).

### Homework

The above is just a blueprint, you may want to further refine it. E.g. what if some *smart* Provider tries to "unflag" a Request that the Provider (automatically) flagged before (via Step 1)? If that happens, such Provider could submit another proposal to the same Request (which is not what you'd want). *Hint*: intercept that event also, and don't allow that to happen ... also using ... euh ... Rules!

# Answer
> 1 votes
> let say 10000+ of nodes of content\_type\_2? Does it mean that "fetch enitity by property" will query for all that number of nodes at once? Can it highly slow down my site perfomance?

I think you answered your own question,

> * rule fetches nodes by property (where author is current user)
> * for each item of the list of fetched entities is triggered another one rules component

Haha yea, not a good approach. A better approach:

Use the flag module and create flag for the Request nodes.

Use Rules Conditional

Then in rules, when Proposal is created \>\> component of request node (loaded using the Reference NID), if flagged is unflaged, flag. Else prevent node from saving and show error message.

When Proposal node is deleted \>\> component of request node (loaded using the Reference NID), unflag if it's flagged.

---
Tags: nodes, rules
---


# Question
Title: How to use the Rules module to lock English nodes from editing?
I need to lock all English nodes from editing because translators sometimes change English nodes by mistake instead of creating translations for them.

Can it be done with Rules?

I guess it might work with the Rules Condition that uses a data comparison `node:language equals English`.

What Rules Action can be used here?

# Answer
For the event, "a node is updated", use the action "set data value".. Unchanged node's body \> Changed node's body and set a site message explaining that the translation wasn't saved.

I'd also make the rule only apply to the translator role.
> 1 votes

# Answer
* Add **event** "when node is updated"
* Add **condition** "if it has field language" AND "data compression value = English "
* Add **action** "Add redirection of node page or you can show message on site "
> 0 votes

# Answer
Yes this is perfectly possible via the Rules module. Some more details about how to actually do so:

* Rules Event: Drupal is initializing
* Rules Condition (both must be true):
    + current path matches the pattern of editing a node.
    + check if the language of the node is English.
* Rules Action:
    + perform an appropriate redirect (to whatever path that fits your needs).
    + set a Drupal message (to indicate such edits are not allowed).

For an example of a rule (in Rules export format) that you could use as a starting point, have a look at the answer to "Is there a way to restrict some pages like node/add, /user/login and more?".

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

---
Tags: rules, i18n-l10n, users
---


# Question
Title: PDOException: SQLSTATE[42S02] on cache_block after module install
I am getting the following error on my (localhost) test system after installing some modules:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'bitnami\_drupal7.cache\_block' doesn't exist

After receiving the error, I uninstalled and removed the modules I was attempting to install thinking that a fresh module install might fix the problem. However, it's apparent to me that the install corrupted the database. Before I even attempted a new install of those modules, I get the above error while performing some other work. So, I used PHPMyAdmin to peek into the database. When I try to access `cache_block`, I get an error stating that it does not exist. Unfortunately, I do not have a recent back up since this is a test system. However, I do have a live production system.

**Question**: can I use the live production system to export the `cache_block` table structure and then import it into my localhost? If not, is there an alternative solution to resolve this error? I'd like to avoid having to reinstall Drupal.

# Answer
> 1 votes
> can I use the live production system to export the cache\_block table structure and then import it into my localhost?

Yes, that's exactly what you should do. Core cache tables have a common structure so you could even just duplicate cache\_bootstrap or another from your local and rename it.

Don't bother importing the data as you'll want to clear caches after recreating the table anyway.

Personally I'd be tempted to also go and find out what caused it in the first place to make sure it can't happen again (and so the site can stay up to date).

---
Tags: 7, database
---


# Question
Title: How to perform a comparison in a rule to check all values of a multi-select list?
I'm stuck with a simple problem, maybe someone can point me in the right direction...

I have a **ContentType** with a field, let's say it's a list of hobbies. It's a **Checkboxlist, multi-select**.

**Users** have an additional **account field** to select their favourite hobby (**a single-select selectbox**)...

Now, when a new content of that type is generated I wan't to send an email to all users who have a selected hobby from the list, selected as favourite in their profile.

--

I used "Fetch entity by property" to get the users with one of the selected hobbies.

I configured it that way:

* Entity type - Value: User
* Property - Value: Hobby (this is a single value, cause a user can only select one hobby)
* Value - Data selector: `node:hobbies:0` (and there is the problem: I can only compare it with the first value of the multi-select *hobbies* list)

Result: It triggers only correctly for the first selected hobby.

--

How can I configure it to take every selected value?

# Answer
There is a `switch to direct input mode` button in the `Value - Data selector` section, after clicking it you'll see a select box with all the values of that field which now you can select.
> 1 votes

# Answer
Your Rules Events and Conditions (if any) are pretty sure OK, but you're missing a crucial Rules Action: a Rules **Loop**. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should add a loop related to that list of hobbies entered when a content type is added. After you do, you should iterate over each item in that list (= each hobby in the content type added). And for each iteration you should then perform the Rules Actions you seem to have in place already (ie "Fetch entity by Property", etc). If you rework your rule like this, in the end you should replace that `node:hobbies:0` by the "list item being processed" (ie the hobby, selected in the node, being processed in the current iteration step).

***Easy, no?***

PS: I doubt the prior answer is going to help achieve your goal ...
> 0 votes

---
Tags: entities, rules
---


# Question
Title: How to add menu links to a node created within a test?
I want to create a test where a few nodes are created, and on those nodes are menu links.

The most I have found so far is:

```
    $options = array(
      'menu_name' => 'menu_test',
      'bundle' => 'menu_link_content',
      'link' => [['uri' => 'internal:/']],
    );
    $link = MenuLinkContent::create($options);
    $link->save();

```

How do I tie it and the node together? Just provide the node uri in the 'link' property? Would that just be `internal:node/(nid)`?

# Answer
Yes, you have just to provide an uri that identifies the node, for example `entity:node/1`

Use

```
'link' => ['uri' => 'entity:node/' . $nid],

```
> 2 votes

---
Tags: 8, testing
---


# Question
Title: How to fetch a list of nodes by content type in a Rules Action set?
I am trying to create a Rules Component that fetches a list of nodes based on their content type. But when I try creating it, I get a little stuck. Here's my process:

1. I create a rules component using "action component"
2. Then add an action to the component "fetch entity by property"
3. Select the entity type I would like to fetch "node"

I am then presented with the following:

In the value box I don't have node types nor a way to pass a text string that represents one, I have tried several ways by including introducing a text variable set to the entity type but if I try and use that as the value I get an error which says something about the variable being the wrong type.

# Answer
> 2 votes
Introduce a variable of type **Text Token** with the content type as the value.

```
Parameter: Type: Text token, Value: content_type

```

And then use this new variable as the value for comparison with the property.

# Answer
> 1 votes
Have a look at this Rules Component (an Action Set), in Rules export format:

```
{ "rules_fetch_all_nodes_of_a_selected_content_type" : {
    "LABEL" : "Fetch all nodes of a selected content type",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "fetched_content_type" : { "label" : "Fetched content type", "type" : "token" } },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "type",
            "value" : [ "fetched-content-type" ]
          },
          "PROVIDE" : { "entity_fetched" : { "node_fetched" : "Fetched node" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node-fetched" ] },
          "ITEM" : { "current_node" : "Current node" },
          "DO" : [
            { "drupal_message" : { "message" : "Title of current node  (with nid = [current-node:nid]) is [current-node:title]" } }
          ]
        }
      }
    ]
  }
}

```

After you import it in your own site, use the "execute" link (to the right of it) to experiment with it in your own site.

As a sample, enter a value like `article` for its input parameter (=`fetched_content_type`, which is the machine name of the content type to be processed). After you do, it'll show a Drupal message for each of your nodes with a content type that matches the value of your parameter. Here is a sample of such messages:

```
Title of current node (with nid = 19) is How to do X?
Title of current node (with nid = 53) is Hello World ...
Title of current node (with nid = 57) is Bonjour!

```

---
Tags: rules
---


# Question
Title: How can I add an unescaped script tag and contents to a page?
I would like to add to my pages the structured data in JSON-LD (https://developers.google.com/search/docs/guides/intro-structured-data)

Basically, what I need to do is to add somewhere in the HTML for, let's say a basic page, a snippet like the following:

```
<script type="application/ld+json">
{  "@context":"http://schema.org",
   "@type":"WebSite",
   "name":"Site name",
   "alternateName":"Site alternatime name",
   "description":"Site description",
   "keywords":"list of keyword",
   "inLanguage":"en",
   "url":"http://www.example.eu/en",
   "potentialAction":{
   "@type":"SearchAction",
   "target":"http://www.example.com/en/find/{search_term_string}",
   "query-input":"required name=search_term_string"
   }
}
</script>

```

I've tried to use the full HTML input but the snippet gets (kind of) escaped with the CDATA and google cannot parse it.

So, how can I provide that snippet without any escaping?

# Answer
> 4 votes
Here's a simple way to do this with no additional modules required. For the sake of this example, I'm going to add this field to the `Basic page` content type that comes with the `Standard` installation profile.

First, let's create a new Text format. Go to `admin/config/content/formats` and click `Add text format`. I name the Text format **JSON-LD** and make it only available for Administrators. Be sure to leave all options blank and set `Text editor` to `None`, like so:

Then, let's add a new field to the `Basic page` content type. Go to `admin/structure/types/manage/page/fields/add-field` and select `Text (formatted, long)`. I name the field **JSON-LD** with an automatic machine name of `field_json_ld`.

Then let's make sure we hide the field's label. Go to `admin/structure/types/manage/page/display` and make sure to set the Label to our new **JSON-LD** field to `- Hidden -`, like so:

Now it's time to add the script to a new page. Go to `node/add/page` and fill in the Title and Body as you like. Here's the important bit: for the **JSON-LD** textarea, be sure to set the `Text format` to **JSON-LD**, like so:

Now click `Save and publish`. Your node will look like this:

Nothing special, right? Now let's take a look at our source code:

Bingo!

# Answer
> 1 votes
The default Full HTML format uses CKEditor, which performs it's own text filtering and is likely what is causing your problems. You can disable CKEditor's Advanced Content Filter, but what I would recommend is creating a new text format with no filtering and no text editor. Then create a new long text field for your page's content type, and set the new text format as default.

You should be able to paste whatever scripts you need in the new field.

# Answer
> -2 votes
If you want to add the script to the editor, use the PHP code filter instead of full HTML, then add your snippet. It will work fine.

>

>

---
Tags: 8
---


# Question
Title: How do I alter the HTML outputted by an exposed filter?
I have a view that pulls in content of many different types. I gave the user two exposed filters, using the Better Exposed Filters module. However, the two filters look different. I would like them to look the same.

Specifically, I would like to get rid of the "Start date", "End date", and "E.g., 2017-02-01" labels on the filter on the right hand side.

How do I do this? Is it possible to do it within the view settings? If not, I don't mind writing a custom solution. I imagine there's a relevant hook somewhere, but I do not know which one to use.

# Answer
> 2 votes
Turns out these settings can't be changed in the View (that I was able to find, and I looked pretty extensively). But, with Drupal's module/hook system, it's a pretty quick fix.

Source: How to remove format description in date\_popup form field?

First, get rid of **Start date** and replace **End date** with **And** to match the filter on the left:

```
function edit_date_form_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] === "views-exposed-form-editable-content-page") {
    $form["field_editor_review_date_value_1"]["min"]["#title"] = "";
    $form["field_editor_review_date_value_1"]["max"]["#title"] = "And";
  }
}

```

Then, get rid of the **E.g., 2017-02-01**:

```
function edit_date_form_date_popup_process_alter(&$element, &$form_state, $context) {
  $element['date']['#description'] = "";
  $element['time']['#description'] = "";
}

```

Plop those into a module, enable it, and your output is:

---
Tags: 7, hooks, views
---


# Question
Title: Using 2 code repos, one Acquia and one private gitlab server for Drupal code base tracking
I run a few drupal 7 sites on acquia and I also have a separate gitlab server for sites that are not on Acquia. Is it possible to push to both repositories on Acquia and Gitlab?

# Answer
> 2 votes
Definitely possible and it's what I do. Acquia provides some documentation on this. As Kevin mentioned you can do this by setting up two remotes for your local repository clone, one at GitHub/GitLab/Bitbucket, and one at Acquia Cloud.

# Answer
> 0 votes
Yes, it is possible, but tedious (in my opinion).

One way to do it is to setup two remotes, and simply do `git push remote-1`, `git push remote-2`. Although depending on your setup, and if you have a team, you are going to want to designate which remote is authoritative and which one is the mirror - if I understand the ask right.

I think you might be looking for is this answer on git itself which is more in depth:

https://stackoverflow.com/a/14290145/295112

Otherwise, if you want to track modules individually, then the entire codebase itself cannot be version controlled unless the code you are tracking are git submodules, or all individually tracked (where the entire drupal root *is not* tracked).

So if there are sites running on Acquia that have dependent modules where the code lives on GitLab, perhaps bringing them into your Acquia project as submodules is your best shot. I am doing that on a project right now, except in my case I am tracking a Pattern Lab project whos repo is on another server. I pulled it into my Drupal project as a git submodule so I could get upstream changes into my workflow - and once I have done some theming work, I push to Acquia.

---
Tags: version-control, deployment, acquia-cloud
---


# Question
Title: Remove row from system table with hook_update_N
I've run into some trouble writing a hook\_update\_N function that will remove a row from the `system` table. Can anyone point me in the right direction? Finding little documentation..

# Answer
I think your code should look something like this:

```
<?php

/**
 * Delete row from system table.
 */
function MODULENAME_update_7001() {
  db_query('DELETE FROM {system} WHERE name = :name', array(':name' => 'FOO'));
}

```

This should go in the MODULENAME.install file of your module. Of course you'll need to replace MODULENAME with the name of your module and FOO with the name of the row you want to delete.

Relevant documentation can be found at Updating tables: hook\_update\_N() functions, hook\_update\_N and Database abstraction layer.
> 3 votes

---
Tags: 7, database, updating
---


# Question
Title: Can't get current user context in page panager
I'm using page manger with panel, and Rng module.

I want a custom page for the registration page (the page to see the registrant information, provided by the Rng module) depending of the current user's role.

So i added a registration page with page manager with this path:

/registration/%

It work, but when i want to set the role has a selection criteria, it's not in the drop down, because there is no current user in the context.

How can i had the current user (not a specific user) in the context?

# Answer
And i'm answering myself, again:

it seem to be a bug in the alpha24.

I updated with the current dev version (2017-Jan-18), and now i've got the current user in the context, and in the criteria !
> 0 votes

---
Tags: chaos-tool-suite, rng
---


# Question
Title: get path of uploaded picture for custom parallax effect
i created a custom block where i can upload an image. i overwrite the custom block with a template:

```
   <div{{ attributes }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
   <div{{ content_attributes.addClass( 'content') }}>

      <div class="row">
        <div class="col-md-12">

          {{content.field_parallax_bilder }}  <----- (1)

          <div class="parallax-window" data-parallax="scroll" data-image-src="(2)">  <----- (2)

          </div>
        </div>
      </div>
      </div>

  {% endblock %}
</div>

```

i want to get the path of the image (1) and include it in my data-image-src parameter (2). is there an easier way then write a block\_preprocess?

# Answer
> 1 votes
You'll have to set a $src var from the corresponding preprocess hook.

```
function myModuleOrTheme_preprocess_block(&$variables){

if(isset($variables['elements']['content']['field_parralaxBgImage']))
//or any other way to test if you are in the right block

   //Get the Image id :
   $imgListItems = $variables['elements']['content']['field_testimages']['#items'];
   $imgId = $imgListItems->getValue()[0]['target_id'];
   //load the entity :
   $image = \Drupal\file\Entity\File::load($imageId);

  // now you can simply return the original image's url :
  $variables['parralaxBgSrc'] = image->url();

  //or return a styled image's url (croped or resized) with a image style configured in the BO
  $imageStyle = \Drupal\image\Entity\ImageStyle::load('imageStyle_id');
  $variables['parralaxBgSrc'] = $imageStyle->buildUrl($image->getFileUri());

}

```

After that, you'll be able to use it in your twig tpl :

```
 <div class="parallax-window" data-parallax="scroll" data-image-src="{{$parralaxBgSrc}}">

```

(Dont forgot to flush your cache after adding the hook)

Et voila! :)

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


title: About View format its css setting.

text:
# Question
Title: About View format its css setting.
I am not good at CSS. Here I want to divid every grid evenly. The is my page. My view I use grid instead of table or unformatted list, which are only text on each row not suit my want.

https://www.jeffhost.idv.tw/services

The other question is on this. I found the picture too small, while making the window smaller. How to adjust a proper setting on View?

https://www.jeffhost.idv.tw/online-buying

Thanks.

# Answer
Okay, the answers to your questions are both rather simple.

1. Your columns are uneven because you did not apply a width to the columns. To solve this I simply applied a percentage width to the td element as follows:

`.view-view-services .view-content td{
 width: 33.33%;
}`

2. When you make your browser's viewport smaller, your images become smaller. This is due to the `auto` properties applied to the `img` tag's height and width. To solve the issue I overrode the `max-width` property as follows:

`.view-uc-products .views-field-uc-product-img img{
 max-width: none;
{`

Let me know if you have any questions!
> 1 votes

---
Tags: views
---


title: How do I add a custom block to a view?

text:
# Question
Title: How do I add a custom block to a view?
In preset views like the *Taxonomy Term* one (/taxonomy/term/%), it can be done by adding a custom block to the footer, but it is not controllable as block layout on /admin/structure/block.

Is it possible to add a region to a custom view template?

# Answer
> 4 votes
Simply go to `/admin/structure/block` and add the block to a region.

In configure block, under Visibility, click on pages tab and type path with wildcard `/taxonomy/term/*`.

Therefore, this block will only be visible in your taxonomy page view.

# Answer
> 2 votes
I very rarely output views as pages because of their initial limitations. If you output the view as a block, you can simply plug it in, using the `/admin/structure/block` interface. You could also try out the Panels module instead of using the blocks interface. It has an intuitive interface, which makes arranging layouts easy. If you're unfamiliar with Panels, here's a basic tutorial on how to get started.

If you're comfortable editing templates, you can plug in a block using the instructions given in this top answer. Here's a little more information on customizing Views templates.

---
Tags: 8, blocks
---


# Question
Title: How to move the comment form to the top?
Per default in Drupal 8 the comment form is rendered below the comments. In Drupal 7 you could move the comment form from the bottom to the top by modifying the comment-wrapper.tpl.php.

Is there also a way in Drupal 8 to get this functionality?

# Answer
> 6 votes
You can in **field--comment.html.twig**

```
{#
/**
 * @file
 * Default theme override for comment fields.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional title output populated by modules, intended to
 *   be displayed after the main title tag that appears in the template.
 * - comments: List of comments rendered through comment.html.twig.
 * - content_attributes: HTML attributes for the form title.
 * - comment_form: The 'Add new comment' form.
 * - comment_display_mode: Is the comments are threaded.
 * - comment_type: The comment type bundle ID for the comment field.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 * @see comment_preprocess_field()
 */
#}
<section{{ attributes }}>
  {% if comments and not label_hidden %}
    {{ title_prefix }}
    <h2{{ title_attributes }}>{{ label }}</h2>
    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}
    <h2{{ content_attributes }}>{{ 'Add new comment'|t }}</h2>
    {{ comment_form }}
  {% endif %}

</section>

```

So copy the above code and go to `/themes/YOURTHEME/templates` folder and create field--comment.html.twig and now paste code.

Now, all you gotta do is just move

```
 {% if comment_form %}
    <h2{{ content_attributes }}>{{ 'Add new comment'|t }}</h2>
    {{ comment_form }}
  {% endif %}

```

and place it above the `{{ comments }}` line

Flush/Clear the cache to see changes.

# Answer
> 1 votes
For change the placement of comment form in drupal 8, you can work on the field--comment.html.twig file. Put this file to your theme.

---
Tags: theming, 8, comments
---


# Question
Title: Creating "Welcome <username>" special menu items
I want to create special menu items with title "Welcome ". I want to make it as special menu item (without link to any node), that shows sub-menu on hover. For that I have used Special Menu Items module and is working fine.

But I am not able to figure out how to create dynamic menu title in form "Welcome Username". I have tried using Menu Token module as well, but it didn't work. It just displays token as it is.

Any suggestion how can I achieve this using module or programatically.

-- Many thanks for your time.

# Answer
I used this on www.grupposportivo.be in a bootstrap nav bar

```
<!-- de inlog button en user print -->
            <li><?php global $user; if ($user->uid != 0)
                { print '<li class="first">' .t('').
                    '<a href="' .url('user/'.$user->uid). '">' .$user->name. '</a>
                    </li>'; print '<li>
                    <a href="' .url('user/logout'). '">' .t('Logout'). '</a>
                    </li>'; } else { print '<li class="first">
                    <a href="' .url('user'). '">' .t('Login'). '</a>
                    </li>'; print '<li>
                    <a href="' .url('user/register'). '">' .t(''). '</a>
                    </li>'; } ?></li>

```
> 1 votes

# Answer
Copy the existing special\_menu\_items module. e.g. welcome\_menu\_items and put it in your custom modules directory. It is only 200 lines, so maintenance particularly if your requirements don't change should not be large.

Change this code adding '. check\_plain($user-\>name);'.

```
  case '<nolink>':
    $tag = variable_get('special_menu_items_nolink_tag', '<span>');
    $title = $variables['options']['html'] ? $variables['text'] : check_plain($variables['text']) . check_plain($user->name);
    $variables['options']['attributes']['class'][] = 'nolink';
    break;

```

This will only give you the username, not the full name. You need to edit the profile to provide a full name. You might also want to check that $variables\['text'\] contains the work 'Welcome' before altering it.

You could debug $variables\['text'\] and submit a patch if there is a problem with this as noted by Clive.
> 0 votes

# Answer
Hope this code snippet will help you.

```
function YOURTHEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
 if($element['#original_link']['mlid']=='YOUR MENU ID'){
    global $user;
    $element['#title'] = $element['#title']. ' '.$user->name;
  }
    $output = l($element['#title'], $element['#href'], $element['#localized_options'], array('attributes' => array('data-title' => $element['#title'])));
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";

}

```

Add this inside your **sites** \> **all** \> **themes** \> default-theme \> **template.php**
> 0 votes

# Answer
I think the cleanest method is to use Menu token module and add menu item with this settings:

* Title: `Welcome [current-user:name]`
* Path: `[current-user:edit-url]`
* Use tokens in title and in path: `checked`
> 0 votes

# Answer
Here's how we accomplished the same thing you are looking to do. We used a custom module and hook\_block\_view. I've left the part relevant to you. header\_user\_nav is our custom nav block at the top of the site. We display the login/register link if the user is not logged in. Once logged in \[if($user-\>uid !== 0)\], the block content changes. The first li is the Welcome message plus the user's name.

```
function custom_module_name_block_view($delta = '') {
  $block = array();
  if($delta == 'header_user_nav'){
    $block['content'] = '<ul><li class="login">' . l('Login or Register', 'user/login', array('query' => drupal_get_destination())) . '</li></ul>';
    $block['subject'] = '';
    global $user;
    if($user->uid !== 0){
      $output = '<ul><li class="username">';
      $output .= t('Welcome ') . $user->name;
      $output .= '</li>';**
      $output .= '<li class="profile">';
      $output .= l('My Profile', 'user');
      $output .= '</li>';
      $output .= '<li class="logout">';
      $output .= l('Logout', 'user/logout');
      $output .= '</li></ul>';

      $block['content'] = $output;
    }
  }

  return $block;
}

```
> 0 votes

# Answer
Use the site current user token for menu tokens. See the screenshots it helps you.
> 0 votes

---
Tags: 7, routes
---


title: Using ImageWidget as form element

text:
# Question
Title: Using ImageWidget as form element
I would like to have a multi image upload in my form with an option to sort images and provide optional title/alt. This functoonality is present in the image widget field widget plugin and so instead of writing a lot of new code I am wondering if there is a simple way to use it as form element somehow?

# Answer
> 0 votes
I agree with @mradcliffe, that there is probably no simple way to reuse field widgets for normal form fields. The code of field widgets heavily depend on an underlying entity field.

I think the best solution is to create a mock custom entity. As you obviously don't need to store the result, otherwise you would already use an entity, you can set

```
"storage" = "Drupal\Core\Entity\ContentEntityNullStorage",

```

in the entity. Example for this is the core Contact Form, which needs very little code to implement fully customizable forms by reusing the form API for entity forms.

# Answer
> -1 votes
Simply configure your field to unlimited value with image type, and you'll get exactly what you said: upload multiple images, provide there title and alt attributes, and sort them.

You can change this in the field parameter (number of authorized values).

---
Tags: 8, forms
---


# Question
Title: How do I access a custom variable in block.tpl.php?
I created a custom module that defines a block. In `hook_block_view()`, I have the following code.

```
$block['content'] = theme('item_list', array( 'count' => $count));

```

How can I get the value of `$count` in block.tpl.php?

# Answer
> 1 votes
You have defined your block with hook\_block\_info(). Now you need to use hook\_block\_view() to add your variables to the content array which can be called in your template file.

# Answer
> 0 votes
The block.tpl.php template file receives in `$content` what you put in `$block['content']` in `hook_block_view()`.

Since you are putting the output of a theme function in `$block['content']`, you would need to filter out the HTML tags from `$content`, to get the value of `$count`.

Alternatively, you can use the following code in `hook_block_view()`.

```
$block['content'] = $count;

```

In that way, if other modules don't alter the content of your block, you get the value of `$count` straight in `$content`, inside block.tpl.php.

---
Tags: blocks
---


# Question
Title: How to create nodes automatically using title, fields, etc from some other nodes?
I want to generate nodes for a content type using fields of some other content types. For example I have three content types A,B,C. All three content types have some common fields as well like Title, Category and Date. I want to create another content type D to hold only those common fields.

Now here I want to generate content automatically for content Type D. I'm looking for a technique in which I can define that, "fetch data" from these common fields of A,B C content types to fill fields of content type D and generate nodes automatically for content type D.

Any suggestions about how to get this to work?

# Answer
Similar to the previous answer, I would also recommend to use the Rules module to implement what you're looking for. However, your major challenge is going to be "What is actually the trigger to create such node of content type D" (and your question says nothing about that).

A solution that would work for sure is to (also) get the Views Rules module involved in the puzzle you're trying to solve. Some details about this module (from its project page):

> Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

1. Create a view (using Views) so that you have 1 Views result (row) for each node of content type "D" to be created, whereas that view has fields (columns) for each of the fields, title, etc from your nodes of content type A, B, C that you want to use to create your node of content type D. Important: use a Views display type of "Rules".
2. Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop".
3. For each iteration step in your Rules loop, perform a Rules Action to create an entity, of type Node (and content type D). At that point you'll have all data from each column of your Views results available as so called Rules Parameters. So at that point it's a piece of cake to populate the various fields of your node of content type D.
4. The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

***Easy, no?***

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

# Answer
The Rules module is your friend here.

You may use it to create an entity (here a node) after saving a new content of type A B or C (or any other event). Then you can add actions (set a data value) to fetch field values from A, B and C for your new content of type D. The first action would be of course Create an entity, then set data values.

You may find a great set of tutorials about Rules at Learning the Rules framework series.

Here is a short example : after saving a new Drupal Article, create a new Drupal Basic Page with the Body extracted from the Article and an automatic node-title.

```
{ "rules_automatic_node_creation_based_on_another_node" : {
    "LABEL" : "Automatic node creation based on another node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Basic page from Article [node:title]",
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "entity-created:body" ], "value" : [ "node:body" ] } }
    ]
  }
}

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Fatal error: Call to undefined function _ds_inception_get_overrides()
I am trying to run the cron job in a drupal website that my client gave me then I tried to update the cron job for search and after the cron jobs finished then my drupal installation turn into this error.

> Fatal error: Call to undefined function `_ds_inception_get_overrides()` in C:\Apache24\htdocs\sites\uqsport.com.au\modules\ds\_inception\includes\ds\_inception.pages.inc on line 37

I have searched everywhere in google but it seems other people don't have this kind of problem before so it kind of make me perplexed as to how this error came upon me? I just need to know how the above error happened? and what is the solution. any help would be greatly appreciated. thanks though.

**update**.

this is what ds\_inception.info contains.

```
 name = Display Suite Inception
description = Create flexible layout pages (Drupal within Drupal) on top of Display Suite.
package = "Display Suite"
core = 7.x
files[] = ds_inception.class.inc
files[] = ds_inception.module
dependencies[] = "ds_inception_fields"
dependencies[] = "ds"
dependencies[] = "ds_extras"
dependencies[] = "views"
dependencies[] = "ctools"
dependencies[] = "entity"
dependencies[] = "list"
configure = admin/config/user-interface/inception

; Information added by cms-build component-build on October 24 2016
version = "7.x-1.0"
core = "7.x"
project = "ds_inception"
datestamp = "201610241316"

```

# Answer
> 1 votes
When Drupal runs its cron tasks, it runs also every implementation of `hook_cron()` made from every module, including the core ones. Those implementation can then invoke other hooks, even the ones implemented by modules not implementing `hook_cron()`.

The error you are showing is caused from the module whose machine name is ds\_inception. Whenever it is implementing `hook_cron()` or one of the hooks invoked from `hook_cron()`, you need to disable that module.

I cannot tell you the name of the module you read in the page listing all the enabled modules, since I didn't find any third-party module with that machine name hosted on drupal.org. I thought it was a sub-module of the Display Suite module, but the 7.x-1.x branch doesn't contain such module, nor does the 7.x-2.x branch. It could also be a custom module developer for that site.
You can still find the readable name of the module in the ds\_inception.info file, if you find one. It's the one following *name =* in that file.

---
Tags: 7
---


title: How do I format a field in views?

text:
# Question
Title: How do I format a field in views?
I have an FAQ page, where in the title it has some html tags, I would like to show the title in the views. When the view is displayed, it is showing html tags as well. How can I get the html processed value.

Is it possible?

# Answer
> 0 votes
Have you checked title field's settings section in views. There is a option for "Style settings" you can check the option for restrict or add new html tags.

# Answer
> 0 votes
If you're putting `<h1>` tags in your node title, do not do that. Simply when you add the title field, go to style settings and add the H1 here. There are other options like `strong` and `p` in this drop down box.

**OR**

Alternatively, you could simply re-write the results and write your HTML around the `{{ title }}`

---
Tags: views, 8
---


title: How do I use PHP code in a block?

text:
# Question
Title: How do I use PHP code in a block?
I am new to Drupal 8. I am building a website with Drupal 8, and it has many blocks contain images. They have an absolute path for the src attribute right now. I would like to make them dynamic base on the base URL, but there is no text format support PHP code anymore for security reason. Is there a safe way to achieve this?

# Answer
> 1 votes
You could and should do your PHP logic with template\_preprocess\_block. As creating a programmatic block just so you can use PHP is more work than necessary, overkill, for this use case.

Also, without any more specific info regarding `make them dynamic based on base URL`, this is as far as I can go.

---
Tags: 8, blocks
---


# Question
Title: Countdown timer on discount products pages
I have created discounts on products, with an end date.

How do I display a countdown timer on my product pages (as in the screenshot) ?

Thank you

# Answer
You can use the Field Timer module

> This module provides field which can be displayed as a timer/**countdown**. A start/target date can be any date or an entity property which represent a date (for example, created date of a node). Module provides 4 field formatters: simple text and 3 formatters based on jQuery plugins County and jQuery Countdown. If you are looking for a configurable countdown/timer, this module is for you. It allows to configure backgrounds, effects, formats, language of timer.

OR

Countdown Timer Field

> Countdown timer field module allows you to create countdown timer field to count the days, hours, minutes, and seconds until a specified event. The module uses jQuery Countdown Timer to display the countdown timer in a nice graphical way.
> 2 votes

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


# Question
Title: Do non-enabled modules affect performance?
Does having Drupal modules present, but not enabled have any effect on the performance of a Drupal site?

To put it another way, would removing disabled modules on a Drupal site have a positive affect on performance?

# Answer
> 99 votes
Generally no it will not affect performance - except for when you are viewing your Modules selection page (admin/build/modules or admin/modules). Disabled modules are not loaded into memory and never executed.

# Answer
> 63 votes
Yes. It can.

Despite what the others say, there are several situations in which performance will go down.

1. Disabled, and not properly uninstalled modules can have severe effects on performance: variables for a module are not removed and will be loaded at every pagerequest. Locales for a module (in case you use a translated site) are not removed and cause overhead on an already cumbersome database-table.
2. Drupal uses the system table as caching to avoid lookups in the filesystem for modules. The more entries there are in that table, the slower it will be. This effect is rather small, because the system table is quite well indexed. However, cache-clears and visiting the admin pages cause this table to be rebuilt. Rebuilding the table with 200+ unused modules is about 25 times slower than with no unused modules. The amount of rebuilding of this table can be quite high in some weird situations, during development and so.

Unused modules do not use more memory other then during rebuild of the system table. Unused modules do not cause more or slower lookups on your filesystem, other then during rebuilding the system table. If you go above the X-thousands of modules, then the filesystem itself can cause trouble.

# Answer
> 9 votes
With *installed* I suppose you mean inside your drupal modules ("sites/all/modules" or "sites/yoursite.com/modules") folder, right?

If so, disabled modules won't affect performance at all, just when you visit your "admin/build/modules" page. Drupal rebuilds the cache of some module elements (as hook\_menu).

# Answer
> 7 votes
From my experience, the performance decrease from disabled modules is negligible (and relative, 4000 disabled modules might make things a little slower than 30 disabled modules, etc.)

Personally, I'm just more concerned about unused (and probably outdated) code sitting in my repo and web dirs, but I'm anally retentive like that.

# Answer
> 4 votes
Technically no and yes. Normally disabled moduels don't load in memory, so they won't affect the performance of the site as such. But if the disabled modules has lot of data in variables, then it is advisable to uninstall them so that the memory gets freed up.

# Answer
> 3 votes
Removing the code of the disabled modules might not have an effect on the site.

Then again, if you installed a module at some point, it will have populated the database with a few tables. So the more modules you install, the greater the chance of affecting database performance.

Uninstalling the module will remove those unnecessary tables.

Again, performance depends on the number of modules you have installed.

# Answer
> 3 votes
The disabled modules that are not uninstalled but physically deleted from folder system would adversely impact the site performance. I had 5 such modules and due to that, there were additional 10,000 calls to is\_dir() function. I used missing\_modules module (missing\_module) to identify the missing modules and fixed the issue in the database.

# Answer
> 1 votes
Disabled modules do not affect the performance of drupal site.

But it is recommended not to download the modules which would be of no use to your site.

# Answer
> 1 votes
Uninstalled and disabled will not effect on performance.

But if the module is disabled only then it may have some tables associated so those are extra burden on the drupal database.

And as said earlier there will be some significant performance issue on drupal's module page. Many times this page is not loaded and takes a lot of time because of all the module those are installed/ uninstalled are displayed there.

So for overcoming this situation we should remove physically the unused modules from /sites/all/modules/ drive.

---
Tags: 7, performance
---


# Question
Title: Accessing a Entity Refererenced field of the current node
I have to render a field of a node that is inside a content type in Drupal 8.

I have a content type called `summary` that has a field, called `field_content` that is an Entity reference field for unlimited items of a specific content type (article)

I'm able to get the current node and handle the `field_content`, but I cant access each of referenced items inside of this type.

Also I have tried to debug the `field_content` with kint but the browser crashes (I suppose that it happens becasue the data dump is very big) and I can't access the inner properties (I have to get a field called `field_desc_text` inside each article).

I need the node or the nid to load it of each of this inner items.

This is what i've tried:

```
       $currentNode = \Drupal::routeMatch()->getParameter('node');
    foreach ($currentNode->get('field_content') as $nodeRef)
    {
      kint($nodeRef); //*This debugs the entire referenced node, but there is no sight of my desired fields
      die;
     // kint($nodeRef[0]); *Cannot use object of type Drupal\\Core\\Field\\Plugin\\Field\\FieldType\\EntityReferenceItem as array
     // kint($nodeRef->get('title')); *Uncaught PHP Exception InvalidArgumentException: "Property title is unknown."

     die;

    }

```

And this is the output of the kint($currentNode):

https://mega.nz/#!Fogx0LpC!CYvc6YSRs1ZcgOAc4RCfDo5iVqjBLYckvuFEUgqRGx8

Thanks in advance!

# Answer
You can access the entities referenced by an entity reference field using the following code.

```
$currentNode = \Drupal::routeMatch()->getParameter('node');
$entities = $currentNode->get('field_content')->referencedEntities();

```

The value returned from `referencedEntities()` is an array of objects that implement `EntityInterface`.
See the documentation and the code used by `EntityReferenceFieldItemList::referencedEntities()` for more details.
> 3 votes

---
Tags: 8, nodes
---


title: Bartik Home link to be uppercase

text:
# Question
Title: Bartik Home link to be uppercase
How can I make "home" link on bartik menu uppercase and instead name it "front page"? I tried by going to edit it at structure-menus-main navigation and i cannot because it says "This link is provided by the Standard module. The title and path cannot be edited." I created a subtheme of bartik. What should i write there in order to change it? Thank you.I am using Drupal8.

# Answer
> 5 votes
This is related to the Q Remove default “Home” link?. You can not alter that menu item. The only way to fix this is to disable the existing "Home" link, and create a new one instead according to your specifications.

To do this, follow these steps:

1. Go to `admin/structure/menu/manage/main` and disable the `Home` menu item
2. Add a new menu item at `admin/structure/menu/manage/main/add` and fill in the options like this:

3. Click `Save` and you're done

---
Tags: 8, navigation
---


# Question
Title: Which Rules Event should I use to change the value of a Select List field?
Use Case:

I've got two select lists

1. Due Date
2. Status

The **Due Date** is a **Date field**, the **Status** is a **select list** with options: **Current, Past Due**.

By default, Current is pre-selected.

I want to run a Rule that *when the current date is greater than the Due Date, the value of the select list will change to Past Due*.

I was trying to experiment with the Rules module, not sure about the event. Would it be ***Drupal is initializing***?

What's the best approach?

# Answer
1. Add event entity has a value or data comparison
2. Add condition according to your select list
3. Add action set data value against changed value
> 0 votes

# Answer
I'm not sure if by using Rules Event "***Drupal is initializing***" you could get it to work. But I recommend you to try to use an alternative Rules Event, since a Rule that uses Rules Event *Drupal is initializing* gets triggered on *every* (repeat *every*) page load on your site. There are plenty of situations where this is (probably) the only Rules Event you can use (if you want to implement some logic with Rules), but I always try to use that Rules Event only *if anything else fails*.

In your case, there is a much better suited Rules Event you could use, i.e. Rules Event ***Before saving content***. Have a look at this rule (in Rules Export format):

```
{ "rules_force_a_value_for_past_due_dates" : {
    "LABEL" : "Force a value for past due dates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_expiration_date" } },
      { "data_is" : {
          "data" : [ "node:field-expiration-date" ],
          "op" : "\u003C",
          "value" : [ "site:current-date" ]
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules Event is "Before saving new content" (if appropriate, you could limit it to some content type, like "Article", only, if the Rule should only be triggered for such content type).
* In my case I have a selection list field with machine name `field_optionlist`.
* This field actually has 3 possible values, like so:
    + A (=Advanced).
    + B (=Basic).
    + C (=Custom).
* These are its Rules Conditions (validations), in the order specified:
    + a validation to ensure that this rule only applies for nodes that have a field with machine name `field_expiration_date` (which also makes that field available as a token for processing in subsequent Rules Conditions/Actions).
    + a validation about attempts to save a node where "The selected value" of `field_expiration_date` is in the past.
    + a validation to ensure that this rule only applies for nodes that have a field with machine name `field_optionlist`.
* If all these Rules Conditions are satisfied, then the Rules Action will force the value of `field_optionlist` to be `A` (feel free to change to whatever you want).

If you want, you can use the Rules UI to import the above rule in your own site. But before doing so, make sure you have defined 2 similar fields (with machine names `field_optionlist` and `field_expiration_date`). As a variation, adapt the machine names to similar fields you already have (attention about `field-optionlist` versus `field_optionlist` though, same for the 2nd field, important!).

***Easy, no?***

PS 1: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

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

---
Tags: entities, rules
---


# Question
Title: Activate bootstrap theme in BrowserTestBase phpunit test
In a Drupal 8 testclass I am trying to install the bootstrap theme (v 8.x-3.1). It is saved in the /theme directory. No problem when using the UI. Unfortunately I get an error in the test when I try to install it with this code:

```
/*
 * Anytest
 * @group proreos
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 *
 */
class CalculatorControllerTest extends BrowserTestBase {

  public function setUp() {
    parent::setUp();
    \Drupal::service('theme_handler')->install(array('bootstrap'));
  }

```

The test exits with the following error:

```
PHPunit Test failed to complete; Error: PHPUnit 4.8.27 by Sebastian
Bergmann and contributors.
There was 1 error:

1)
Drupal\Tests\preosasde\Functional\CalculatorControllerTest::testCalculatorController
Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for
bootstrap.settings with the following errors: bootstrap.settings:schemas
missing schema

/var/www/vhosts/proreos/core/lib/Drupal/Core/Config/Testing/ConfigSchemaChecker.php:93

```

Any advice on this? Anyone tried to install bootstrap in an PHPUnit test sucessfully?

Thanks!

# Answer
Thanks to Berdir for the hint. The solution is to disable the schema validation here. It's done with this code in my testclass:

```
protected function getConfigSchemaExclusions() {
  return array_merge(parent::getConfigSchemaExclusions(), ['bootstrap.settings']);
}

```
> 1 votes

---
Tags: theming, 8, testing
---


# Question
Title: How to edit default Commerce Order status?
I am trying to edit the label of a **default** Commerce Order status (Pending:pending).

I have tried through `commerce_order.api.php` like it is explained in this post: Change order status string from "Completed" to "Shipped" and on this page but unfortunately it did not work for me. More, in this PHP file, the Completed status should display Finished and it doesn't work either??

The Commerce custom Order Status works fine with new statuses but I did not find any way to edit default ones.

Thanks for any tip.

# Answer
Ryan's solution in Change order status string from "Completed" to "Shipped" works finally, my code was wrong.

So, for anyone having the same need, create a mini-custom module using the function hook\_commerce\_order\_status\_info\_alter (dependencies commerce\_order) and paste your new label like it is done for Completed status.

You may find the exact status machine names (e.g. "pending") in commerce\_order.module.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can we apply group_concat using views?
Is there any way we can apply group\_concat clause using views and without applying any customization to views ?

# Answer
> 0 votes
After some R & D on the above issue. I found that Views Aggregator Plus has that feature which I require. However, there are some minor configuration to be made but this module is quite helpful the result which I was expecting.

---
Tags: views
---


# Question
Title: Setting custom permissions in a view on a per-display basis
## Context

* D7
* Views (latest version as of this writing 2017-02)

## Scenario

* SingerRegarn has a D7 view with five displays, where the access control on each display is set to:
    + `Access:Permission | View published content`
* SingerRegarn creates another display, but she wants access control to be set to:
    + `Access:Permission | Administer users`
* SingerRegarn configures the permissions for the newly created display, using the setting:
    + `For: This page (override)`
* SingerRegarn then saves the newly created display.

## Problem

* After saving the newly created display, the permissions for the newly created display do not differ from the other displays, as desired.

## Question

* Is there a bug-fix or workaround to prevent this unexpected behavior?

## See also

# Answer
Okay, so I put this to the test, using you example. I did not experience any unexpected results. I created 3 displays and set 2 of the displays to `Access:Permission | View published content`. For the 3rd display, I set it to `Access:Role | administrator`. When I'm logged in as an Administrator, I can view all three display pages. However, when I try to view the 3rd display page as an unauthenticated user, it returns an access denied error. Displays 1-2 remain visible to an unauthenticated user.

My configuration of display 1-2:

What my view page looks like for display 1-2 (viewed as unauthenticated user):

My configuration of display 3:

View page for display 3 (viewed as unauthenticated user):

I'd double check your configuration to make sure it's correct! If you're still having issues, you could output your displays as blocks. Then you could apply permissions on those blocks using the `admin/structure/block` interface. You can also plug in view blocks into something like a Panel page, and apply permissions to your Panel pages.
> 1 votes

# Answer
## Overview

* Thanks to feedback from Kellen Lester, and a review of some of my old notes, the steps and workaround are more clearly enumerated. There may or may not be a fix for this, but here is a workaround.

## Workaround

* Activate the Master display for the view.
* On the Master display, set the access control to:
    + `Access:None`
* Now, whenever a new display is created it will default to `Access: None`
* Now, for every display where a custom permission is desired, the following should produce the expected results:
    + Click `None` to change the access control
    + Choose `For: This page (override)`
    + Choose either permissions-based or role-based access control as desired
    + Save the display
* Result: the custom per-display permissions settings should remain as expected, without modifying the permissions for any of the other displays
> 1 votes

---
Tags: 7, views, users
---


# Question
Title: How to expose a select field to a Rules Condition?
In Drupal 7, I have defined a new content type which has a checkbox field . The idea is that when a user chooses option A and submits the content, the system does something after the creation of the node, say, send an email to the webmaster and if the user choose option B or C while creating the content, the system do nothing.

I've had difficulty to expose the select field result to a Rules Condition and I'm even not sure whether it is possible, so appreciate your help.

# Answer
> 4 votes
Well, I found my answer:

I need to create a 'Entity has field' condition and equate it to the machine name of the field in question.

Then the field becomes exposed in 'Data Comparison' to be evaluated.

# Answer
> 0 votes
Your own answer is correct, but a bit cryptic IMO.

By adding a Rules Condition `Entity has field` (related to your field) it becomes available to use it in subsequent Rules Conditions, and *also* subsequent Rules Actions. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

### Example

Have a look at this Rules example in Rules Export format (refer to "Which Rules Event should I use to change the value of a Select List field?" for more details what this example is about):

```
{ "rules_force_a_value_for_past_due_dates" : {
    "LABEL" : "Force a value for past due dates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_expiration_date" } },
      { "data_is" : {
          "data" : [ "node:field-expiration-date" ],
          "op" : "\u003C",
          "value" : [ "site:current-date" ]
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ]
  }
}

```

Without the *first* `entity_has_field`-condition (about `field_expiration_date`), it would be impossible to select that field as a token in the 2nd Rules Condition (it simply wouldn't be shown in the select list to select a token).

Without the *second* `entity_has_field`-condition (about `field_optionlist`), it would be impossible to select that field as a token in the Rules Action (again, it simply wouldn't be shown in the select list to select a token).

---
Tags: 7, entities, rules
---


# Question
Title: How to check in a Rules Condition if a specific value of a multi-value field is selected?
I have a "checkboxes" field that allows the user to select unlimited options. How do I check if at least a specific value has been selected?

I am using the Rules module, and when it checks if the 'field has value' it combines all the options. Right now, if both the values "`b`" AND "`c`" are selected, then the action (which checks for the value "`b`") won't be executed.

# Answer
I ended up creating a "Check a Truth Value" condition with the Rules module. The code below is the one I used.

```
if ($node->field_area_51[0]['value']) {
  foreach ($node->field_area_51 as $key => $value) {
    if ($value[value] == 'b') {
      return TRUE;
    }
  }
}

```
> 4 votes

# Answer
I would build a hook\_nodeapi validate (D6) or a hook\_node\_validate (D7) to check if "b" is selected, use dsm to inspect the values of $node. I supposed you're working with the content type page: `$node->type == 'page'` and you field is named `field_options`.
The values are defined like this:

```
a|A option
b|B option
c|C option

```

Code for D7:

```
function mymodule_node_validate($node, $form) {
  dsm($node);
  $b_selected = FALSE;
  if ($node->type == 'page') {
    foreach($node->field_options[$node->language] as $option) {
      if ($option['value'] == 'b') {
        $b_selected = TRUE;
      }
    }
    if (!$b_selected) {
      form_set_error('field_options', t('Please select at least option B'));
    }
  }
}

```

PS: I'm not sure about the form\_set\_error for fields
> 1 votes

# Answer
Sorry to say, but your custom rule works as implemented: only if value "`b`" is selected, the list of selected values is equal to ... "`b`", while if value "`b`" AND "`c`" are selected, then the list of selected values is NOT equal to ... euh ... "`b`".

To get your rule to work like you want it to work, then you should use these Rules Conditions (in the specified order):

* ***Entity has field***, for your "checkboxes" field.
* ***List contains item***, whereas:
    + the list is also about that same "checkboxes" field (since your field allows multiple values, it is also considered as a list).
    + the item you want to check for (if it is contained in the list) is "`b`".

With those 2 Rules Conditions, your Rules Actions should be perform (1) if only value "`b`" was selected, but (2) also if value "`b`" and value "`c`" were ***both*** selected.

For an example Rule (in rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.

PS: even though CCK is rather D6-ish, the same kind of mistake can happen in D7 (which is what my answer is about).
> 0 votes

---
Tags: entities, rules
---


# Question
Title: How to replace node_form() with my custom form callback?
In my module, I want to override the call to `node_form()` for a specific node type called `superpage`, because I want this specific node form to allow for a confirmation step before saving.

In `drupal_retrieve_form()`, every node form is built by the function `node_form()`, which adds everything you'd expect from a node form.

I want to add an extra step to my form: First, the node form should be rendered normally; then, when the user clicks *Save*, I am using a *custom submit handler* to set `$form_state['rebuild']`, and to set a custom flag, signaling the need for confirmation. Now I want to rebuild the form not through `node_form()`; instead I want to display a `confirm_form()`.

This means that the process starts over in `drupal_retrieve_form()`, which simply calls `node_form()` again, because the `node` module implements `hook_forms()` and defines that callback for all node forms.

I would like to replace the form callback for my custom content type, so that it returns a normal node form if confirmation is not needed, or a confirmation form if needed.

Implementing `hook_forms()` in my module didn't help.

```
/**
 * Implements hook_forms().
 */
function superpages_forms($form_id, $args) {
  $forms = array();
  if ($form_id == 'superpage_node_form') {
    // Adding this callback crashes drupal_retrieve_form().
    $forms[$form_id]['callback'] = 'superpages_wrapped_node_form';
  }
  return $forms;
}

function superpages_wrapped_node_form($form, &$form_state, $node) {
  // Build for special case: a confirmation form.
  if (!empty($form_state['values']['confirm_is_needed'])) {
    $confirm = t('You should be careful with this. Are you sure?');
    $confirm_form = confirm_form(array(), $confirm, 'node/' . $node->nid);
    return $confirm_form;
  } else {
  // Build a normal node form.
    return node_form($form, $form_state, $node);
  }
}

```

# Answer
> 1 votes
Variant 1. You can use hook\_menu\_alter and you can set your callback

```
/**
 * Implements hook_menu_alter.
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/superpage']['page callback'] = 'MYMODULE_superpage_form';
}

```

Variant 2. You can use hook\_form\_FORM\_ID\_alter and override/edit the form

```
/**
 * Implements hook_form_FORM_ID_alter()
 */
function MYMODULE_form_superpage_node_form_alter(&$form, &$form_state, $form_id){
  // your code
}

```

---
Tags: 7, forms
---


# Question
Title: How to restrict tagged content based on user?
I'm using drupal 7.39, but I don't know how to restrict users to access some specific content.

I have created a content type called **person**. Then I have created 5 nodes, like so:

* 2 nodes tagged with **manager** term.
* 2 nodes tagged with **lead** term.
* 1 node tagged with **worker** term.

This is where I struggle:

* the **worker** user must see node tagged with **worker**.
* the **lead** user must see node tagged with **lead** and **worker**.
* the **manager** user should see all nodes.

Is there any solution to get this to work (without writing custom code)? Because a configurable job is always easier.

# Answer
Seems like using the Taxonomy Access Control module is the most straight forward solution to answer your question. Some details about this module (from its project page):

> Access control for user roles based on taxonomy categories (vocabulary, terms).
>
> * Automatically controls access to nodes (based on their taxonomy terms).
> * Configuration page for each user role.
> * Three node access permission types: View, Update, Delete.
> * Two term access types: View tag, Add tag.

Together with using this module, you should also define 3 roles, i.e.:

* ***Lead***, granted to any user considered as "Lead".
* ***Worker***, granted to any user considered as "Worker".
* ***Manager***, granted to any user considered as "Manager".

With those roles and permissions in place, you have everything to configure your access rules as provided by the Taxonomy Access Control module.

PS: note that this has nothing to do with content type "Person" (as in your question). Not sure why you need/use that content type, but to get the above to work you don't need that.
> 0 votes

---
Tags: users, taxonomy-terms
---


title: Supported recurring payments

text:
# Question
Title: Supported recurring payments
I would like to activate Recurring Payments in Drupal. Is there a list of supported payment methods?

# Answer
Try Commerce Recurring Framework module

> Overview
>
> Provides a rules, field and entity based approach to recurring billing for Drupal commerce.
>
> Features
>
> Auto-generate new orders based on recurring configuration decoupling payment from recurring process and leveraging the payment responsibility directly to the payment method.

Also For more details about how you can use this Read Recurring payments in Drupal
> 0 votes

---
Tags: 7, payment-gateways
---


# Question
Title: How to know when a node is going to be deleted when using Rules Event "Before saving content"?
I'm using a rule with Rules Event "Before saving content", but this rule is also executed when I delete the node.

I'm recalculating some fields, I don't need to do this when the node is going to be deleted.

How can I know when the node is going to be deleted? I'm coding the rule with `hook_rules_action_info`.

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

```
{ "rules_before_saving_content_but_not_when_deleting" : {
    "LABEL" : "Before saving content but not when deleting",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "The path of the content being saved = [site:current-page:path]" } }
    ]
  }
}

```

If you request an edit a node (say with `nid=71`) your path will be `node/71/edit`. If you then save the node by hitting the `Save` button, the above rule will show a Drupal message like so:

```
The path of the content being saved = node/71/edit

```

If you request an edit a node (say with `nid=72`), your path will be `node/72/edit`. But if you then decide to delete (instead of save) the node by hitting the `Delete` button, then no Drupal message (similar to the previous scenario above) will be shown.

This (rather basic) Rules debugging scenario, leads me to believe that, out-of-the-Rules-box, Rules Event ***Before saving content*** does NOT get triggered when a node is deleted. So whatever problem you are experiencing (when a node is deleted), it must be because of something else happening in your site, in your custom rule, or your custom code of your rule. If I was to further investigate your issue, I'd start "Rules debugging", as explained in the answer to "How can I display the value of a variable inside a condition?".

PS: a quick-and-dirty workaround for whatever issue you're experiencing, might be to check the results you get by adding an extra Rules Condition to check if the (saved) node will still have status "published" (assuming a deleted node is no longer marked as "published").

---
Tags: 7, nodes, rules
---


# Question
Title: Pull in all child libraries of a library/module/theme with dependencies in yml
I have one contrib module and a custom module. The contrib module defines a lot of sub libraries and I want to depend all of it. Example:

Contrib module module\_contrib.libraries.yml

```
module_contrib_lib: [...]
module_contrib_lib.sub1: [...]
module_contrib_lib.sub2: [...]
module_contrib_lib.sub3: [...]
module_contrib_lib.sub4: [...]
module_contrib_lib.sub5: [...]
module_contrib_lib.sub6: [...]
[...]

```

And in my custom.libraries.yml

```
custom:
  [...]
  dependencies:
    - module_contrib/module_contrib_lib

```

But this doesn't pull in the subs, I tried with `- module_contrib/module_contrib_lib.*`, but it doesn't do anything. If I put `- module_contrib/module_contrib_lib.sub1` ect it works. There's no any wildchar to pull in all of the sub libs?

# Answer
> 2 votes
Well, I suppose if you want to pull them all in, you can nest them under 1 library definition.

Or, add another library definition that contains all of the resources, so you can still use multiple or the whole shebang if you want to.

---
Tags: 8
---


# Question
Title: What is the proper way to set up the front page?
I currently have my front page set to a node/basic page through *Configuration \> Site information \> Default front page*. Will this cause Google to index both the home page and the default front page? I just don't want to get hit for duplicate content.

I’m worried because both were showing on the XML sitemap before I removed the default front page (droneswithcameras.com/search-best-drones-cameras). You can look at my site to see what I’m talking about. The default homepage is set to /search-best-drones-cameras.

Are the front page and home page essentially the same thing? It’s just strange to me that there are multiple URLs for the same page.

# Answer
> 1 votes
In Drupal 8 you can disable the /node route by disabling the view called "Frontpage", effectively eliminating the frontpage concept.

---
Tags: 7
---


# Question
Title: How do i get parent ID of a taxonomy term?
When i try to get data using the JSON API module, the field parent is always empty even if a term hierarchy exists.

For example, for a request to http://mysite.local/jsonapi/taxonomy\_term/my\_vocabulary/1a2a1fc1-b6d8-40be-a482-766ccab4aed1?\_format=api\_json&include=vid,parent, part of the response is the following one.

```
"parent":{
        "data":[

        ]
     },

```

How can I fix it?

# Answer
See this core issue: https://www.drupal.org/node/2543726

This will address this. Right now, parent is a special pseudo-field that only supports saving parent relationships but not actually loading them. That's why serialization doesn't work.

You would have to write your own serializer that uses the getParents methods of the taxonomy\_term storage to load the data
> 2 votes

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


# Question
Title: Apply a ranged contextual filter to a date in Views
I have an entity with a timestamp field that I would like to filter based on date. I can add a standard filter "between two date", type in two dates, and everything works great. However, contextual ranges do not work. I've read online that Drupal 7 allowed 2016-01-10--2017-01-01 or 20160101--20170101 as input and would display all results in 2016. These do not seem to work in Drupal 8. Is there a way to do range contextual filters in D8?

I've tried using a datetime field instead of a timestamp, and I am unable to filter this either.

# Answer
> 1 votes
Views Contextual Range Filter might do the trick for you. Install the latest beta and then see if you need to apply this patch. It's got just the functionality you're looking for.

---
Tags: views, 8
---


title: File system... How does it work?

text:
# Question
Title: File system... How does it work?
I am new in Drupal. Now I am trying to understand basic philosophy of Home-\> Administration -\> Configuration -\> Media -\> File system. `Public file system path` here is:

```
sites/default/files

```

is set as public path by default and `Public file base URL`is therefore:

```
http://example.com/sites/default/files

```

Couple days ago not knowing about `File system` I created folder, where I put some pdf files.

`http://example.com/custom_files/pdf`

In the **article** I set hyperlinks to these files and everybody may download these pdfs happily. And now I do not know at all, why should I bother with `File system` **public path**??? What is it good for, when I may use any folder I want?

Thanks for answers

# Answer
## TL;DR

Public file path is used for file uploads that happen in Drupal. Usually you want to use Drupal to manage content, that means article, users and files. This requires you to upload files inside Drupal application and this is where the public file setting comes into play.

## Longer version

When you create a Drupal site, you can decide where all file uploads (which are public) should be located. The only rule is, that it have to be inside the webroot, so that they are accessible for download.

By default this is `sites/default/files`, but it could be `/uploads` or whatever you like.

This is used for when you actually use Drupal as a CMS and upload files on content like on articles, user profile pictures etc. When you upload files through Drupal and they are public, Drupal will save info about the file, know it's location and can do things with it.

Having the public path configurable is pretty smart, it means to change move or rename the upload folder and you only need you change one setting for it to work.

If you have FTP access you can upload any file to the webserver, it will be accessible to users etc. You should note that uploading files this way, means that Drupal wont know that they exist and can't actually use them in any way. It might be a good solution for your use case, but you are effectively bypassing Drupal as a CMS and if you plan on manually uploading all files through FTP, you will loose a lot of the file management features and the public file setting wont matter one bit.

Hope this clear things up for you a bit.
> 3 votes

---
Tags: files
---


# Question
Title: Make sure content of every view is published
I'd like to set a query alter function that checks if the `node.status` condition is already set in the view's query, and if it's not I'd like to set it to only get published content. The following code doesn't seem to running on my app. Do you have any suggestions to make this work?

```
function hook_views_query_alter(&$view, &$query) {

    $found = false;

    foreach($query->condition as $condition) {
        if($condition = 'node.status') {
            $found = true;
        }
    }

    if(!$found) {
        $this->query->add_where(
            $this->options['group'],
            db_or()->condition('node.status', 1, '=')
        );
    }

```

I have \> 100 views to implement this change on.

# Answer
Why not just set a filter in the View configuration and set Status as `Published`?
> 0 votes

---
Tags: 7, hooks
---