# Question
Title: How to send an email notification reminder based on a user's date of entry field?
The authenticated users on my Drupal website have "Entry date" in their profile (= date when they registered). I want to send out notifications to me (the admin) when a user has been registered on my website since more than 5, 10 or 15 years. So each time a user surpasses for example 5 years of registration time, I get an email notification 1 month in advance.

How can I achieve this?

# Answer
Use the Rules module together with `Rules Scheduler` (a sub-module of it), as explained in the steps below. These steps are based on a date field which is added to the user profile, so that for each user you can indicate an appropriate date.

### Step 1: Create a field to store the reminder date

Similar to that "Entry date" field you already have, add another field to the "user" entity with machine name (say) `field_next_reminder`. Allow only 1 date (to store the date of the "next" reminder), I don't see any reason why you'd want to make it required (it doesn't matter in the context of this answer). And set its initial value to "5 years after the entry date", using the same procedure you have in place already for that "Entry date".

### Step 2: Create a Rules "Component"

Here is the Rules **Component** to be created (in Rules export format, just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at `admin/config/workflow/rules`):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_be_reminded" : { "label" : "User to be reminded", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : "[site:mail]" ,
          "subject" : "Time flies ...",
          "message" : "This is a reminder about another 5th anniversary for user with eMail id [user-to-be-reminded:mail] on [user-to-be-reminded:field_next_reminder] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***To*** eMail ID.

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at `admin/config/workflow/rules`):

```
{ "rules_on_new_user_registration" : {
    "LABEL" : "On new user registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [], "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_reminder" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[account:name]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-reminder",
            "date_offset" : { "value" : 2592000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_be_reminded" : [ "account" ]
        }
      }
    ]
  }
}

```

Note that the above rule refers to the *Rules Component* from the previous step.

Also note the machine name of `field_next_reminder` in this rule, which is the field's machine name created in Step 1 (if in step 1 you used another machine name, then also replace the machine name `field_next_reminder` in this rule with the machine name of the field created in Step 1 (if you don't have such field yet, or the field names don't match, then the import of this rule might not work).

The `schedule_delete` part of this rule ensures that previously "scheduled" reminders are removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

### Step 4: Add 5 more years to the reminder date

With what's above you should receive such reminder eMails after 5 years. But you also want that to happen after 5 (or 10) years later on (for 10 years or 15 years).

Probably the easiest way to do so, is to have some mechanism in place so that around the time you actually perform some action (to process your reminder), you also add 5 more years to the `field_next_reminder`. In doing so, the above magic will get triggered again (via that very same rule).

You can apply such update manually (don't forget it though). Or (my preference) you could use the Flag module to implement a designated (global) flag to flag users. And combine this with an extra custom rule with these specs:

* Rules Event: User gets flagged (with the designated flag).
* Rules Actions:

+ Do whatever you want to happen to actually send congratulations (or anything like that?) to that user. E.g sending an appropriate eMail, grant user points, grant a special user badge (*yearling*?).
    + Update the `field_next_reminder` (using "set a data value") to add 5 more years for your next reminder.

True, this would be a minor extra effort to get it implemented (it may take up to 5 minutes, say 15 at most ...). But the ROI of doing so would be that authorized users would only have to flag those yearling-type of users (somewhere after they receive the reminder eMail ... in which you could even include a relevant hyperlink to make the magic happen). Even better: you could use this flagging facility to start nagging **yourself** to not forget to flag that user ... (logic: reminder date is below 30 days, and user is not yet flagged).

### Step 5: Further tuning and enhancements

* The ***date\_offset*** (=2592000) in the above rule corresponds to "30 days in advance", which may need review / tuning (it's about 1 month, right?).
* You might want to also use the Field Permissions module to set field-level permissions to edit, view and create fields on any entity. In your case maybe you only want admins to edit that reminder field.
* 5 years is a long time ... remaining homework: what if the user account has been deleted.
* Instead of just sending an eMail (as in the Rules Component), you could replace that by a more advanced option using the Message module (which has great integrations with the Rules module also). Here is an quote about that module (from its project page):

> ... enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

### Step 6: User boarding

With the above solution in place, you have a solution for (a) all future new user accounts that will be created and (b) all existing accounts for which a date is entered (manually?) in that `field_next_reminder` field. However you could take advantage of that existing "Entry date" you mentioned, to also get a similar process in place for your existing user accounts, by performing an (one time only) appropriate mass update (bulk) operation. If you wonder how to also get that to work, then use this link.

**Note**: Using Rules to send an email X days after a user registers also contains quite some details that may help you.
> 4 votes

# Answer
You can achieve your goal using both Rules and Scheduler module.

Check Using rules to send an email x days after a user registers.

If you are looking for custom coding, you can implement `hook_cron`, as explained in the answer to the question about "How to create a task which run at cron time and send emails to users?".

Some other links which may help you:
> 3 votes

---
Tags: 7, users, emails, notifications
---


# Question
Title: find all users of a certain role and return that list
I am trying to turn this query to drupal EntityCondition query

```
select u.name, ',', u.mail, ',', r.name , ','
from users as u, users_roles as ur, role as r
where u.uid = ur.uid
and ur.rid = r.rid

```

This should return a list of all users with their email username and user role

I have this

```
  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'user')
    ->addTag('role_filter');
  $results = $query2->execute();

```

So getting all users within a specific role id

```
function mymodule_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->leftJoin('users_roles', 'r', 'users.uid = r.uid');
  $and = db_and()
            ->condition('r.rid', array(3,4,5), 'IN');
  $query
    ->condition($and);
}

```

I am not sure how to get the role value based on what I have is it another entity condition?

The above entityFiledQuery does return the following

```
{"1":{"uid":"1","name":"admin","pass":"HASHPASSWORD!","mail":"admin@example.com" "roles":{"2":"authenticated user","3":"administrator"},

```

but a) I would rather have roles as the value administrator and not this funky array with the "rid" key b) the hashed password is there, can data be sanitized ?

# Answer
> 3 votes
The name of the role is in the `role` table so just join that in as well:

```
function mymodule_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->innerJoin('users_roles', 'ur', 'users.uid = ur.uid');
  $query->innerJoin('role', 'r', 'r.rid = ur.rid');
  $query->condition('r.name', 'administrator');
}

```

Note that you want inner joins here, not left, otherwise you'll just get whether they have the admin role or not. You don't need an `and` as you only have one condition.

The hashed password is added by `user_load`, not your query, so you'd have to address that separately. I'm not sure there's an easy way to exclude a property from an entity load, it would make for a good follow-up question.

---
Tags: users, entities, database
---


title: User Import with inactive status

text:
# Question
Title: User Import with inactive status
I have a site where we need to bulk import users into the system, however the client wants to be able to import the users into the system but have them inactive until a later date,

The idea is that we operate online training courses, so we will receive user data from an organisation as part of our onboarding - however we do not want to give the users access to the system until it is time for them to start their course.

My idea was to use the User Import module to bulk import - however I can not see a way to set the 'status' of users when importing - as a result all users have instant access to the system. Is there any way to do this with the User Import module?

If it was possible, we would then use a VBO operation to change the status of the users to active at the appropriate date - this would also mean that users would receive the site configured activation email with the appropriate log-in information,

Any help or alternative implementation suggestions would be greatly appreciated,

Thanks,

# Answer
The **Feeds module** \- https://www.drupal.org/project/feeds \- provided me with the solution to this issue.

Feeds allow you set both the Status of the whole import, and a per user status by adding a Status column to your CSV,

For users who have the same problem, this how you do either:

---

### 1. General Status for User Import

Once you have installed the Feeds module go Structure/Feeds Importer/User Import - admin/structure/feeds/user - and go to the **Settings** option in the **Processor** section, here you will find an option to set the Status of all imported users:

---

### 2. Status column in Import CSV

If you want to add a status column to your CSV file, allowing some users records to be imported as active and others as blocked, then you need to edit the **Mapping** in the Processor section - again at admin/structure/feeds/user. Add a new field to the mapping selecting 'Account Status' as the target field.

Inside your CSV **use the values 0 or 1 for the status** \- where 0 is 'blocked' and 1 is 'active'.

Note: this will override any default status defined by the steps outline in Option 1 above.

---

---

I can also confirm that VBO operation to unblock users will also result in the correct Activation emails being sent out to the users (provided you have an activation email configured in Account settings)
> 0 votes

---
Tags: users, importing-exporting
---


# Question
Title: Can I use hook_css_alter inside of hook_form_alter
Can I use hook\_css\_alter inside of hook\_form\_alter. I need to unset a css file only on certain forms and only to non-admins. This is what I have but it doesn't work.

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\UserSession;

function mymodule_form_alter(array &$form, FormStateInterface $form_state,  $form_id) {
  $user = \Drupal::currentUser()->getRoles();
    if(in_array("administrator", $user)) {

    function mymodule_css_alter(&$css) {
      unset($css['core/themes/stable/css/system/components/tabledrag.module.css']);
    }
  }
}

```

# Answer
You can't use a hook function inside of a hook function. If you are in the css alter hook you have to get the information you need from where you are in code. For example you could check for the route name of the form because the current route match is available in a service. So this could work (not tested):

```
function mymodule_css_alter(&$css) {
  $user = \Drupal::currentUser()->getRoles();
  $route = \Drupal::service('current_route_match')->getRouteName();
  if (in_array('administrator', $user) && $route == 'entity.node.edit_form') {
    ...

```
> 4 votes

# Answer
Yo unset CSS files on certain pages for certain users, you could do something like this:

```
function hook_css_alter(&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
   if (\Drupal::routeMatch()->getRouteName() == 'form.route') {
    $roles = \Drupal::currentUser()->getRoles();
    if(!in_array("administrator", $roles)){
       unset($css['file.css']);
    }
  }
}

```

Hope this helps
> 2 votes

---
Tags: 8, forms
---


title: Confirm drush is reading policy file

text:
# Question
Title: Confirm drush is reading policy file
Drush newbie question: I've copied the policy.drush.inc file from drush examples and saved into my local drush folder, then cleared drush's cache - how do I confirm Drush is using that file (other than attempting to overwrite a production database with a local one!!)

# Answer
> 2 votes
The file `examples/policy.drush`.inc contains a `drush_policy_pm_update_validate` hook. If `drush pm-update`, gives you the message "This codebase is assembled with Composer instead of Drush. \[...\]" you know that Drush uses the file.

---
Tags: drush
---


# Question
Title: All special characters get outputted as question marks
I have a Drupal 8 (8.2.5) setup on a Debian Jessie Server `PHP 7.0.15-1~dotdeb+8.1` and MySQL `5.5.54`. All of a sudden Drupal converted all special characters like `ü,ä,ö,ß,–...` into question marks like `Das mu?? doch nicht sein`.

At first I thought, this must be a problem with a false encoding in the HTML header, but the encoding of the page is: UTF-8. Then I realized, that in the database all those characters are really 'converted' to question marks. As I have on the same server many Drupal instances (v. 6, 7 and 8) running, the which never had shown such behavior, I don't think, it is an issue with the server setup. The MySQL logs did not show anything referring to this issue neither.

After restoring the Data base, the same issue occurred again after some days.

I have absolutely no clue, what is going on. Has anybody an idea what could be the cause of this problem?

UPDATE: This problem is getting more wired: It turned out, as soon as I clear the cache, all special characters are gone. A look into the database (with PHPMyAdmin) shows, they really are. When I then restore a former database version, all special characters are shown on the site correctly again, but in the database they are still shown as questions marks. My first guess was: They are already »converted« in the database dumb I was using, but only correct in the cache table. But, when restore the database and directly edit an affected node, all special characters are correctly shown in the form field. After saving it, they are correct even in the database. So I could restore all special characters by bulk republish them from the `/admin/content` interface. Also it turns out that not only special character in node fields are gone, but also in path alias and taxonomy terms. For example: Where »ä« should be converted to »ae« within a path alias, it was turned to a »?«.

Let me demonstrate this with some screen shots. The special character in this case was an en dash (–): This is how it looks like on the site, when the issue occurs, a question mark is shown where originally an en dash was:

PHPMyAdmin shows us in the next picture, that this en dash was really converted to an question mark:

Looking into the backups of my data base with a text editor show, that in there the special characters are not corrupted.

Uploading the database file with Mackup and Migrate or with `drush sql-cli < path/to/my/file/database.sql` a look into the database shows, it gets corrupted immediately:

But on the site as long as I don't clear the cache all looks good. That means **the cache table aren't corrupted**. But surprisingly even if I edit an node, it is shown as if it weren't corrupted:

For a commoner like my that leads to the conclusion:

* **Some how, if I edit a node, it's content is loaded from cache tables!**

So my questions are:

1. Which Drupal module or function could be responsible for touching all most every database entry, but not the cache tables?
2. If I re-save a node or entity (without making any change), how is it possible, that the database entry of the affected fields change?

# Answer
It turned out that the described problem was caused by the Backup and Migrate module. In fact it is a known bug. **So, don't use this module for Drupal 8. It will destroy your entire site.**
> 5 votes

---
Tags: 8
---


# Question
Title: How do I organize content based on date field in a Y > m > d hierarchy?
In essence, I want to organize content based on a date field; first by year, and once a user clicks a particular year, it goes to months, and so on... possible?

For instance,
-2017
-2016
-2015

I click on 2016 views generated date link, I should see the following on the next page.

December,
November, etc...

and finally, if I click on November, I will get to the actual listing of content for November.

Edit:
I have already tried grouping by year, and then months. But it is not creating the hierarchy I am expecting. Should I create a display that groups content by years first? and then months?

# Answer
> 0 votes
So for Drupal 7: Take look at this description: http://chrisshattuck.com/blog/how-create-monthly-archive-block-drupal-blog-views

This is basically an explanation of the "Archive" view (disabled by default) shipped with views. Take a closer look at it and copy it to apply a few minor changes.

It gives you a monthly grouping of your content if there is no argument passed. That is actually the trick. Instead of the "created" date of your content just use the date field you have as argument.

---
Tags: datetime
---


title: How can I remove an action link?

text:
# Question
Title: How can I remove an action link?
I have a form that I'm creating and I'd like to get rid of the 'Add contract' button that is being put there automatically. Is there something different I can do here:

```
function my_module_theme($existing, $type, $theme, $path) {
  module_load_include('inc', 'my_module', 'includes/admin/my_module.admin.forms');

  return array(
    'my_module_setup_form_contract' => array(
      'render element' => 'form',
    ),
  );
}

```

Or is there some other hook I can use? I've been looking in the `theme_my_module_setup_form_contract` and `my_module_setup_form_contract`, but it looks like it's too late there.

This is for 7, btw.

# Answer
> 1 votes
You can remove local actions within hook\_menu\_alter().

If this is a generic action it will be removed on all of those forms. E.g. local actions for nodes - changes would be seen on all content types.

---
Tags: 7, theming, forms
---


# Question
Title: Button with different value and label / text
in Drupal 8, I want my form display such a (submit) button:

```
<button name="name" type="submit" value="value">Not the value</button>

```

So basically, the button value (that will be submitted) shall be different than the button text / label (following that solution).

Is that possible with the Form API? If yes, how?

# Answer
I think this might be a duplicate of a question I posted a few weeks ago for Drupal 8.

Original question: https://drupal.stackexchange.com/a/226494/57

Some more write up: http://kevinquillen.com/drupal/2017/01/28/adding-twig-template-suggestions-for-form-elements

Basically I wanted to target just one submit, hence that technique. Simply changing the `#type` to `button` is not enough in the Form API to get that result you're asking for.
> 1 votes

# Answer
Could solve it myself. Since I'm using Bootstrap, I could hook into its button template `input__button`:

```
function MYMODULE_preprocess_input__button(&$variables) {

  if (!empty($variables['element']['#label'])) {
    $variables['label'] = $variables['element']['#label'];
  }
}

```

With that, I can now define a label using the Form API:

```
$form['submit'] = [
  '#type' => 'submit',
  '#name' => 'some_name',
  '#value' => 'some_value_to_send',
  '#label' => $this->t('Label to show'),
  '#button_type' => 'primary',
];

```

(If Bootstrap applies my patch then the hook will get obsolete.)
> 1 votes

---
Tags: 8, forms
---


# Question
Title: I am trying to modify a form element using hook form alter but I can't find the correct field name
I am learning Drupal 7. I have a custom module, trying to modify a date form element in my page. I have the form id identified, and Devel module list me all the fields in this page, I think I am typing the correct field name but it doesn't work, It creates a new form element instead of modify the form element. Maybe the element is inside a fieldset, but I don't know how to write the correct line to modify. It is a datepicker and I am trying to modify the minDate property for the date element.

Here is my code:

```
function davidcustom_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);  // print form ID to messages

  // Check when the right form is passed
  if ($form_id == 'commerce_cart_add_to_cart_form_24296') {

    $form['field_line_item_fecha_reserva'] = array(
      '#title' => t('Pick the desired date'),
      '#type' => 'date_popup',
      '#datepicker_options' => array(
        'minDate' => 10,
      ),
    );

  }

}

```

# Answer
> 1 votes
When you can't find an array key, the best thing to do is to dump the entire form array and search for it. If you use the Devel module, you can use the following:

```
dpm($devel);

```

This will give you a nice collapsible output through which you can search. Or you can use the old-school method that I use, and dump it directly using:

```
die('<pre>' . print_r($form, TRUE) . '</pre>');

```

---
Tags: 7, forms
---


# Question
Title: how to tell which book node is the root node programatically
If I have some nodes that are of type book, how can I go through them in a php script and tell which is the root? thanks

# Answer
You can try to build the menu tree for your book. Book nodes do not have direct parents. The relationship is defined by the menu structure.

This will give you the structure of the book menu.

```
$book = $node->book;
$tree = menu_tree_all_data(book_menu_name($book['bid']));

```
> 2 votes

---
Tags: 7, nodes, external-scripts
---


# Question
Title: How to prevent recursion when setting a data value for a user in rules?
I have a rule that is triggered on the event **After updating an existing user account**. The rule performs an action, **Set a data value**, that changes one of the values of the user account fields.

However, doing this causes the user account to be saved again, which triggers **After updating an existing user account** a second time. This causes some of my other rules that are triggered after updating a user account (such as those for sending notification e-mails) to be triggered twice.

I know this **Set a data value** rule is the issue because when I disable it, the account is only sent once, and the other rules that send notifications only send a single notification.

Is there a way to avoid this (single) recursion when setting a data value with a rule?

# Answer
This is not an ideal solution, but I just manually coded the necessary **Set a data value** behaviors in PHP in a custom module; this prevents the other rules from being triggered twice.
> 0 votes

# Answer
Your question seems like a variation of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

> some other module code is calling a `user_save` on `hook_user_update` triggering the rules event a second time.

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):
> 2 votes

# Answer
As per my understanding you need Rules Conditional module. We can run loops in rules action as well as we can put OR, AND conditions.

So at one time you can run loop for multiple actions which can solve your problem but you will have to workaround.

**Edited texts --**

You can set a field in profile with display hidden status. Name as per your like e.g. - WORKFLOW.

Use a taxonomy vocab for this field value where you add action names which you perform. If you have multiple action which need to be performed only once then set this field to have multiple value.

When you perform some action which need to perform only once, add one more action relevant to this action & for which a term is available in vocab such as "mailsent","sms-sent" etc..

Now go to the condition and add one more condition where you have to check whether that particular field WORKFLOW doesn't have this value.

So when once your mail action is performed, it will add a value "mailsent" & next time your condition will deny proceeding this rules s it will get "mailsent" in the field value..

I hope it helps..
> 0 votes

# Answer
You shouldn't worry about the fact that the Rule is triggered twice. If you activate debugging at `Workflow > Rules > Settings`, a grey box ("Rules evaluation log") appears when a Rule is run. In your case, you'll see that the same Rule is triggered two times. However, the second time the following message appears:

> Not evaluating reaction rule YOUR RULE to prevent recursion.

This proves that Rules is quite a smart module. :)
> 0 votes

---
Tags: rules
---


title: Custom action defined by config entity

text:
# Question
Title: Custom action defined by config entity
I am currently creating a module that allows generating PDFs based on arbitrary entities (or at least nodes). Multiple templates can be defined as config entities. This part already works. I have the config entity set up with create, edit and delete forms and the list.

Now I want to provide a link for each entity of any entity type (i.e. node) like example.com/node/\[nid\]/pdf/\[template\_id\] that loads the defined template with ID \[template\_id\], generates the PDF and downloads it directly.

What is the correct way? Should I just provide a link through the routing file or is it better to implement a plugin or a custom operation handler or .. I am new to D8 and so I am not aware of all possibilities.

Thanks, j

# Answer
That's what controllers are for, getting parameters from a route and generating output. So yes, to get started you need a routing file, where you define the parameters and the controller class and method that should be called.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: Adding a query string to menu items determined by the current node?
I'm pretty new to Drupal 8. I'm trying to figure out how to programmatically add a query string to a menu item link, the specific query string is determined by the node/page the user is currently on.

For example, I've got a link on my primary menu that goes to http://www.example.com

If I'm on the 'about me' page I want the link to add a query string of '?origin=about'. (http://www.example.com?origin=about)

If I'm on the 'contact me' page I want the link to add '?origin=contact', etc.

Are there any modules where this can be done, or how might I go about doing this myself?

# Answer
The menu is cached. You could disable caching and add the query string to the options of the url in hook\_link\_alter, but this is not good for performance. So this would be better solved in javascript. You can prepare the link in php by setting an attribute, so that you can easily find the link later in the client and attach the query string.
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: Datepicker widget. How can I add some variable javascript code from my module to configure the date popup calendar?
I need to personalize some settings in the date popup calendar in a date field. This is the documentation for the popup calendar used in the Drupal date field: http://api.jqueryui.com/datepicker/

I would to configure for example, the minDate property, to set a minimum selectable Date, according the documentation this is the code:

```
$( ".selector" ).datepicker({
  minDate: new Date(2007, 1 - 1, 1)
});

```

But... How and where do I type it in a custom module? It looks javascript, but I don't know how to make this code work for my date form element.

# Answer
You can add it with `#datepicker_options`, e.g.:

```
$form['date'] = [
  '#type' => 'date_popup',
  // ...
  '#datepicker_options' => [
    'minDate' => 0,
  ],
];

```
> 1 votes

---
Tags: 7, javascript, datetime
---


# Question
Title: Is there a Drupal way to loop over Webform fields in form alter function?
Since `$form['submitted']` array has also other keys than just field names e.g. #tree, what is the correct way to loop over this array?

I need to add a #prefix and #suffix for each field and for now I've just created condition `!is_numeric(strpos($fName,"#"))` This tells if it just a field name or if it holds render array properties or whatever they are called.

# Answer
For D7 use `element_children`:

> Identifies the children of an element array, optionally sorted by weight.
>
> The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal\_render() for details.

E.g.

```
foreach (element_children($form['submitted']) as $key) {
    $form['submitted'][$key]['#prefix'] = 'foo';
}

```

For D8, use the equivalent `Element::children` in the same manner.
> 5 votes

---
Tags: forms
---


# Question
Title: Rule to check if a date value is a specific day of the week
I want to set a rule which checks a date of format "2014-09-24 08:43:39" is a Monday using the data comparison rule. I have tried to manipulate the data selector for the date using the ":custom:N" format however data comparison wont accept it. I'm trying to do it from within the rules module as my PHP is a bit limited. Any ideas? Thanks Adrian

# Answer
I had myself many troubles with Rules and dates too. There are several open issues in Rules about dates. So the solution that I offer is very cumbersome and to be honest I don't like it too, but it seems to be the only thing to work. Improvements are of course welcome. Maybe there is also some module which I miss.

Note that this is about Rules ver. 7.x-2.7. The solution involves both some PHP code and components.

So the first issue at hand is that it seems Rules cannot change the format of a date variable in a data comparison, or to properly convert the data type.

Therefore I am using a rule to get the weekday from the variable, then pass it to a component as a variable (integer). In that component I can easily do a data comparison for the interger and procedd with any actions.

In order to get the weekday, I create an action "Add a variable". In there, I use some PHP code in order to directly get the week day. Here is the second issue: Rules do not seem to properly expose the variables in PHP. Therefore I specify the type of the variable as text, and then I specify the value using one of the replacement patterns in the direct input mode (otherwise a date will not be available in the data selection mode). Now we have the date as a string in a variable. Let name the variable `variable_added`.

The second action is to "Set a data value". In there, you specify:

```
<?php
$datetime = new DateTime(DateTime::createFromFormat('D, d/m/Y - H:i', $variable_added));
return $datetime->format('w');
?>

```

We create a DateTime object from a hard-coded format. This has to be the Drupal long date format which Rules seem to use for their date formatting. There got to be an API function that returns the current format which atm I miss, and so we have it hard coded to get us going. Replace this with your installation's custom format from `/admin/config/regional/date-time`, also consult this. Then we use `DateTime::format` to get the day number.

So now we have the day number as a string. The third action would be to convert the above variable to an integer, and then in a fourth action you would call the rules component passing on the converted variable along with any other variables you would need.

Appendix: My test case rule export.

```
{ "rules_test_date" : {
    "LABEL" : "Test date",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php" ],
    "ON" : { "cron" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[site:current-date]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "data_set" : {
          "data" : [ "variable-added" ],
          "value" : "\u003C?php\r\n$datetime = new DateTime(DateTime::createFromFormat(\u0027D, d\/m\/Y - H:i\u0027, $variable_added));\r\nreturn $datetime-\u003Eformat(\u0027w\u0027);\r\n?\u003E"
        }
      },
      { "drupal_message" : { "message" : [ "variable-added" ] } },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "variable-added" ] },
          "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
        }
      }
    ]
  }
}

```
> 1 votes

# Answer
Don't know if this works for your specific case, but for me this little module is quite useful in a similar context as it provides for a "check what day it is" Rules condition (and Event):

https://www.drupal.org/project/rules\_onceperday

> The module also provides a "Day of the week is a" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.
> 1 votes

---
Tags: rules, datetime
---


title: Add custom field to taxonomy term

text:
# Question
Title: Add custom field to taxonomy term
I added a custom field to a taxonomy term via 'Manage Fields' (see screenshot here: https://cl.ly/022v2B2H2c1m). How can I display this new field in the Frontend? In my template.php I have this:

```
$cats = taxonomy_get_tree(7);
$categories = array();
if (!empty($cats)) {
  foreach ($cats as $cat) {
    $parent = $cat->parents[0];
    $item = array(
      'tid' => $cat->tid,
      'name' => $cat->name,
      'description' => $cat->description,
      'image' => $cat->field_images,
      'children' => array(),
    );

  }
}

```

When I do a var\_dump($item), the image field shows 'NULL', although I added an image.

Anybody with a solution?

Best wishes

# Answer
You can use this -

```
$term = taxonomy_term_load($tid);
$field_image = field_get_items('taxonomy_term', $term, 'field_image');
if ($field_image) {
  $headerimg = field_view_value('taxonomy_term', $term, 'field_image', $field_image[0], array('type' => 'image'));
}
print render($headerimg);

```

In your file `template.php` use the `theme_preprocess_page` function like this :

```
function mytheme_preprocess_page(&$vars) {
  $term = menu_get_object('taxonomy_term', 2);
  if ($term) {
    $field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
    if ($field_header_image) {
      $vars['headerimg'] = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
    }
  }
}

```

Then in you `page.tpl.php` you can print `render($headerimg);`
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How can I print a field value in node.html.twig?
I want to print a field value in node.html.twig. When I use `{{ content.field_test }}`, it prints the full HTML markup of the field.

How can I just print the field value?

# Answer
> 8 votes
While you can print the first value of the field without the surrounding div container with `{{ content.field_test[0] }}`, this is not a recommend way to do it.

The markup you want to change is in the field template. If you don't want for example any div's around the field `field-test`, then place a field template in the template folder of the theme:

*field--field-test.html.twig*:

```
<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

```

The benefit you get is that this outputs multi-value fields and that you keep the attributes of the field, which is important if you want the theme to work with core and third-party modules for client side functionality like, for example, quickedit.

# Answer
> 6 votes
This will help:

Twig Field Value : It gives them more control over the output without drilling deep into the render array or using preprocess functions.

---
Tags: 8, entities
---


title: How to add default text to CKEditor?

text:
# Question
Title: How to add default text to CKEditor?
I am using CKEditor and I want ,when creating a new node, in the textarea of CKEditor to add some default text every time a user tries to create a new node. How can I do that? thanks

# Answer
> 1 votes
When you setup a node field, there's a default value in the form.

Simply write down the default value there, and each time a new content is created, this field will be loaded with that default value.

---
Tags: wysiwyg
---


# Question
Title: How To organize Taxonomy Vocabulary with overlapping terms - Content Display pages and future proofing
I am trying to get a handle on Taxonomy Vocabularies and when to have a separate vocabulary vs when to have multiple fields feed into one vocabulary. How this relates to term pages and Views pages and diplaying content in general.

I have 4 fields:

1. Artist Name
2. Song Writing Credit
3. Song Performance Credit
4. Song Composer Credit

Most of the time the 'Artist Name' is the same as the 'Song Performance Credit' and most of the time there's a different composer and writing credit.

I have 2 options when creating Vocabularies:

1. have all fields feed to one Vocabulary called "Artist Name"
2. have a different Vocabulary for each field

**The reason for option 1** is being able to display all content the artist is related to in a View. example: Artist Joe Blow performed on song 6 of an album. It's not his album but if a customer loves him they should be able to go to his artist page and see that album displayed. Therefore any time his taxonomy term is used on a performance credit or written by credit or composer credit it will be associated with that same taxonomy term and therefore be connected to that artist.

**The reason for option 2** is if I want to display a list of all composers on the site, or all song writers or all performers. If i bundle everything into one vocabulary, then a taxonomy page for "Artists" will show all taxonomies in that vocabulary including the composers, performers and writers. So keeping each field associated with a unique Vocabulary will allow for this separation. However then Joe Blow might be in various vocabularies and not necessarily linked to his artist page.

On an artist display page I would like to show a list of all Albums he/she is associated with including their own album but also albums they are featured on. This leads me to believe I should have only one taxonomy term of their name in the system therefore only one Vocabulary where all artist names live.

**Questions**

1. what's the best practice with taxonomy and at what point is it good to have different Vocabularies for each field vs one Vocabulary that multiple fields feed into
2. How are they suppose to be entered and organized for future relational connections?

# Answer
I'd not use a taxonomy at all for implementing what you're asking for. Instead I'd use the Entity Reference module and add an entity reference field like so (in the order specified):

* create an extra content type (say) "Artist".
* create a node for each Artist you ever want to be able to reference in any of those 4 fields.
* make each of your 4 fields an entity reference field.

That's all you'd need.

If I may say, this would still be a solution that could work if some day you have hundreds (thousands?) of Artists. If however you'd use your option 1, or option 2 (using vocabularies), do you think that would still be "usable" (practical)?

However, you may then also want to enable the Inline Entity Form module which, as mentioned on its project page, "*provides a widget for inline management (creation, modification, removal) of referenced entities*".

### More info

Have a look at the answers to these questions for some related topics:

PS: this could work for either D7 or D8.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Why theme scripts.js is not working, how to attach it
I started learning Drupal 8 and encountered problem when I wanted to use scripts.js file globally. I am just testing out code to change background color and write something to console, but script file is not working. **source/scripts.js** is minified to **build/scripts.js** which is included in **libraries.yml** and **global** is included in **info.yml**. What am I doing wrong? Maybe I don't understand new Drupal 8 Javascript API?

**libraries.yml**

```
  global:
  version: VERSION
  css:
    base:
      css/base/base.css: {}
    layout:
      css/layout/layout.css: {}
    component:
      css/components/components.css: {}
    theme:
      css/theme/theme.css: {}
      css/theme/print.css: { media: print }
  js:
    js/modernizr.js: {}
    js/build/scripts.js: {}
  dependencies:
    - core/drupal
    - core/jquery

```

**info.yml**

```
libraries:
  - core/normalize
  - offer42/global

```

**source/scripts.js**

```
(function (Drupal, $, window) {

  // To understand behaviors, see https://www.drupal.org/node/2269515
  Drupal.behaviors.offer42 = {
    attach: function (context, settings) {

      $(context).find('.block-offer42-branding')(function () {
          $(this).css('background-color', '#000');
          console.log("workinh");
      });

      // Execute code once the DOM is ready. $(document).ready() not required within Drupal.behaviors.

      $(window).load(function () {
        // Execute code once the window is fully loaded
      });

      $(window).resize(function () {
        // Execute code when the window is resized.
      });

      $(window).scroll(function () {
        // Execute code when the window scrolls.
      });

    }
  };

} (Drupal, jQuery, this));

```

# Answer
What you're trying to do is not valid jQuery code. You missed the `.each` part.

So use `$(context).find('.block-offer42-branding').each(function () {`
> 1 votes

---
Tags: theming, javascript
---


title: Views filter: show nodes last year

text:
# Question
Title: Views filter: show nodes last year
Following this tutorial https://www.drupal.org/node/2481343 i made a filter where the user can select the nodes, createad from a date till now.

Is there an easy way to make a button with 'show nodes from last year'? I was thinking about a button, switchting between 'last year' and 'all' (in fact a reset of the filter).

# Answer
Not very beautiful and dynamic but as a quick fix you could for instance add a Global: Text area to your views. (See screenshot also)

```
<a href=http://project.local/articles?created%5Bmin%5D=01%2F01%2F2016&created%5Bmax%5D=12%2F31%2F2016>Show nodes from last year</a>
<a href=http://project.local/articles>Show all nodes</a>

```

To make this more dynamic you could enable the php module (not recommended! https://drupal.stackexchange.com/a/2512/8606) and use `date("Y",strtotime("-1 year"));` to retrieve the previous year dynamically
> 0 votes

---
Tags: 7, views
---


# Question
Title: Conditional Field on Multiple Selects Module
I have 1 Multiple Select field and 2 Select List fields:

I need to show those 2 Select field only when Multiple Select has a value of 1 (the first value of the list is selected). I made the dependency and the 2 Select lists are hidden, but when I select the first value of the Multiple Select field, the 2 fields are not appearing, nothing happens.

Is there something that I'm doing wrong? Any opinions why is this not working?

# Answer
> 0 votes
It work when I use these settings. See screenshots.

---
Tags: forms
---


# Question
Title: Feeds tamper fetch data from external API
I am using drupal\_http\_request and drupal\_json\_decode to retrive and parse json from an external API in the feeds tamper by using the execute php code plugin. My code is as follows:

```
$json = "https://api.coursera.org/api/onDemandSpecializations.v1?ids=".$field;
$response = drupal_http_request($json);
$data = drupal_json_decode($response->data);
return ($data['elements'][0]['name']);

```

**This returns a null value.**

The json is as follows:

# Answer
If I'm not mistaken `{}` indicates that it is an object and `[]` means that the variable is an array, therefor, I would expect `$data->elements[0]->name` would be the way to get the value in your return statement.

To improve your code, I would advise to use the empty() (or isset()) functions to check whether the elements in $data exists
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: How to access fields from node template without render
within node template, i am trying to print a content type field value. usually I see the render function used to print the field value in the template e.g. `render($content['field_name']).` how do i just print the field value?

`$content['field_name'][$lang][0]['value']` doesnt work

# Answer
You can do it like this:

```
$lang = field_language('node', $node, 'field_name'); // gets field language

print $node->field_name[$lang][0]['value']; // prints field

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Change CSS rule for small screen with jQuery
I am making **bacon menu** for small screens. I need to initialize menu without showing menu links, so I hide them with **jQuery**. The problem is that on big screen menu links are still hidden and I don't want that to happen.

I use this code to avoid menu link removal on big screens, but it's not working:

**scripts.js** (function (Drupal, $, window) {

```
  // To understand behaviors, see https://www.drupal.org/node/2269515
  Drupal.behaviors.offer42 = {
    attach: function (context, settings) {

      // Execute code once the DOM is ready. $(document).ready() not required within Drupal.behaviors.
      // Burger menu for small screen
      $(window).resize(function(){
        if ($(window).width() > 720 ){
          $('ul.menu').css('display', 'none');
        }
      });

      $('#menuButton').click(function(){
        $(this).toggleClass('is-active');
        if ($(this).hasClass('is-active')) {
          $('ul.menu').css('display', 'block');
        }
        else {
          $('ul.menu').css('display', 'none');
        }
        });

} (Drupal, jQuery, this));

```

**SASS:**

```
.menu
  li
   display: block;
   text-align: center;
   background-color: #fff;
   @include media($medium-screen-up)
     list-style-type: none
     display: inline-block
     float: right;
     margin: 0 10px 0 10px
     @include position(relative, -50px null null null)
     background-color: initial;

```

# Answer
> 0 votes
Resolved.

```
if ($(this).hasClass('is-active')) {

```

doesn't allow to show menu links when no class is attached:

```
else {
          $('ul.menu').css('display', 'none');
        }

```

So, I modified checking for small screen:

```
 $(window).resize(function(){
        if ($(window).width() > 720 ){
          $('ul.menu').css('display', 'none');
        } else {
          $(this).toggleClass('is-active');
        }
      });

```

---
Tags: javascript, navigation, theming
---


# Question
Title: How to Programmatically add javascript dynamically from a custom module to modify a popup calendar property
I need to add a JavaScript code to my custom module, to modify the property in a date popup calendar and make it dynamic.

According to the documentation of the date popup calendar, the syntax for modifying the MaxDate is:

```
$( ".selector" ).datepicker({
  maxDate: "+1m"
});

```

I have to write "+1m" dynamically because it may be "+2m", "+3m", etc, it is variable.

How can I write a JavaScript code in my custom module and effect the popup calendar? I am wondering if I use script tag and put the JavaScript code inside it. In case, how can I do it by js?

# Answer
You can attach a script to a form using the form's #attached attribute. You can do this in hook\_form\_alter as follows:

```
function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'targeted_form')
  {
    $form['#attached']['js'][] = array
    (
      'type' => 'file',
      'data' => drupal_get_path('module', 'my_module') . '/scripts.js',
    );
  }
}

```

If you need to pass values from PHP to the form, you can attach values using Drupal.settings:

```
function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'targeted_form')
  {
    $form['#attached']['js'][] = array
    (
      'type' => 'setting',
      'data' => array('myModule' => array('someSetting' => 'some value')),
    );
  }
}

```

Now the value will be available in your form at:

```
Drupal.settings.myModule.someSetting

```

Combine these two techniques to attach a form and pass it some settings.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How can I import non-unicode text file by Feeds module?
My drupal version is : 7.5x

I want to import an csv or txt file that have non-unicode (iransystem) encoding.

After import this file to Drupal (persian character with iransystem encoding) my characters show correctly in my site. So these texts are imported successfully. But when I want to filter results of those fields by Views (exposed filter), I can not see any result by filtering views fields (search in fields by views exposed filter).

I want to import non-utf8 or unicode persian text files into Drupal and filter those fields by Views exposed filter (search on non-unicode characters).

For example I imported `A Persian or arabian word` into a field of Drupal. This passage shows correctly to me, but when I search type this passage in exposed `A Persian or arabian word text` in Drupal page and paste on search field of Drupal Views, I can see results correctly.

# Answer
I can only provide high-level guidance here, but you need to use the Feeds Tamper module, which allows you to alter data between when it is read from the source, and then passed to Feeds.

However, I don't think there is an existing tamper plugin that can handle your situation; you will have to create your own.

There are two patches in the issue queue that may provide guidance:

You can take one of those two patches, and update them to use your character set instead of the ones in the patch.

For example, in this patch, you would need to update

```
+function feeds_tamper_utf8_encode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
+  $field = drupal_convert_to_utf8($field, 'ISO-8859-1');
+}

```

to use your encoding name instead of `'ISO-8859-1'`.
> 1 votes

# Answer
My File is Unicode file.because it shows in microsoft excel and other programs correctly.But I think my file and my export is the Basic Problem.

So I delete those files and stop importing those to drupal.

thank you
> 0 votes

---
Tags: 7, views, feeds, importing-exporting, theming
---


title: How can I use $_SESSION?

text:
# Question
Title: How can I use $_SESSION?
I want to use this code in Drupal 8.

```
if (isset($_SESSION['loop'])) {
     $loop = $_SESSION['loop'];
} else {
     $loop = 0;
}
for ($count = 0; $count <= $loop; $count++) {
     $_SESSION['code'][$loop] = $code;
     $_SESSION['price'][$loop] = $price;
     $_SESSION['loop'] = $loop + 1;
}

```

This code worked correctly, but in Drupal 8 we should use this code.

```
// Setting a value.
$tempstore = Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

```

```
// Getting a value.
$tempstore = Drupal::service('user.private_tempstore')->get('mymodule_name');
$some_data = $tempstore->get('my_variable_name');

```

I don't know how to change my code to use this service's API. How do I convert my code to use the *user.private\_tempstore* service?

# Answer
You listed all the elements you need. You just need to swap out the set and get you were originally using with the ones you provided.

This:

```
$loop = $_SESSION['loop'];

```

Will become this:

```
$loop = Drupal::service('user.private_tempstore')->get('mymodule_name')->get('loop');

```

And this:

```
$_SESSION['loop'] = $loop + 1;

```

Will become this:

```
\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('loop', $loop + 1);

```

For your other elements, you can do the following.

This:

```
$_SESSION['code'][$loop] = $code;

```

Becomes this:

```
\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('code', [$loop => $code]);

```

And this:

```
$_SESSION['price'][$loop] = $price;

```

Becomes this:

```
\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('price', [$loop => $price]);

```
> 0 votes

---
Tags: 8
---


# Question
Title: Memcache "non-existent service "cache.backend.memcache" error
I have a successfully running and memcache.so and memcached.so and both are shown in phpinfo, I have set them in correct php.ini file and restarted all services.

```
sudo service memcached status

* memcached.service - memcached daemon
   Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2017-02-11 22:16:41 UTC; 7min ago
 Main PID: 12367 (memcached)
    Tasks: 6
   Memory: 548.0K
      CPU: 27ms
   CGroup: /system.slice/memcached.service
           `-12367 /usr/bin/memcached -m 128 -p 11211 -u memcache -l 127.0.0.1

```

`settings.php`:

```
$settings['memcache']['servers'] = ['127.0.0.1:11211' => 'default'];
$settings['memcache']['bins'] = ['default' => 'default'];
$settings['memcache']['key_prefix'] = '';
$settings['cache']['default'] = 'cache.backend.memcache';

```

`drush en memcache`:

```
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "cache.backend.memcache". Did you mean one of these: "cache.backend.database", "cache.backend.apcu", "cache.backend.php", "cache.backend.memory"? in /var/www/d8.com/htdocs/core/lib/Drupal/Component/DependencyInjection/Container.php on line 157 #0 /var/www/d8.com/htdocs/core/lib/Drupal/Core/Cache/ChainedFastBackendFactory.php(79): Drupal\Component\DependencyInjection\Container->get('cache.backend.m...')
#1 /var/www/d8.com/htdocs/core/lib/Drupal/Core/Cache/CacheFactory.php(83): Drupal\Core\Cache\ChainedFastBackendFactory->get('bootstrap')
#2 [internal function]: Drupal\Core\Cache\CacheFactory->get('bootstrap')
#3 /var/www/d8.com/htdocs/core/lib/Drupal/Component/DependencyInjection/Container.php(254): call_user_func_array(Array, Array)
#4 /var/www/d8.com/htdocs/core/lib/Drupal/Component/DependencyInjection/Container.php(177): Drupal\Component\DependencyInjection\Container->createService(Array, 'cache.bootstrap')
#5 /var/www/d8.com/htdocs/core/lib/Drupal/Component/DependencyInjection/Container.php(494): Drupal\Component\DependencyInjection\Container->get('cache.bootstrap', 1)
#6 /var/www/d8.com/htdocs/core/lib/Drupal/Component/DependencyInjection/Container.php(236): Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)
#7 /var/www/d8.com/htdocs/core/lib/Drupal/Component/DependencyInjection/Container.php(177): Drupal\Component\DependencyInjection\Container->createService(Array, 'module_handler')
#8 /var/www/d8.com/htdocs/core/lib/Drupal/Core/DrupalKernel.php(544): Drupal\Component\DependencyInjection\Container->get('module_handler')
#9 /var/www/d8.com/htdocs/core/lib/Drupal/Core/DrupalKernel.php(702): Drupal\Core\DrupalKernel->preHandle(Object(Symfony\Component\HttpFoundation\Request))
#10 phar:///usr/local/bin/drush/lib/Drush/Boot/DrupalBoot8.php(150): Drupal\Core\DrupalKernel->prepareLegacyRequest(Object(Symfony\Component\HttpFoundation\Request))
#11 phar:///usr/local/bin/drush/includes/bootstrap.inc(354): Drush\Boot\DrupalBoot8->bootstrap_drupal_full()
#12 phar:///usr/local/bin/drush/includes/bootstrap.inc(473): drush_bootstrap(5, 6)
#13 phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php(59): drush_bootstrap_to_phase(6)
#14 phar:///usr/local/bin/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#15 phar:///usr/local/bin/drush/includes/startup.inc(458): drush_main()
#16 phar:///usr/local/bin/drush/includes/startup.inc(365): drush_run_main(false, '/', 'Phar detected. ...')
#17 phar:///usr/local/bin/drush/drush(114): drush_startup(Array)
#18 /usr/local/bin/drush(10): require('phar:///usr/loc...')
#19 {main}
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "cache.backend.memcache". Did you mean one of these: "cache.backend.database", "cache.backend.apcu", "cache.backend.php", "cache.backend.memory"? in Drupal\Component\DependencyInjection\Container->get() (line 157 of /var/www/d8.com/htdocs/core/lib/Drupal/Component/DependencyInjection/Container.php).

```

So as you can see I cannot manage to enable the memcache module.

nginx php7.0-fpm

# Answer
You need to enable the memcache module *before* configuring it. The services only exist when a module is enabled.

At least with the redis module, it is also possible to manually register it to the classloader and explicitly add the services.yml file, but I don't know if that's true for memcache as well. See https://docs.platform.sh/frameworks/drupal8/redis.html
> 5 votes

---
Tags: 8, configuration, caching
---


# Question
Title: Should I use all these template files or will theme hooks do the job?
Since templates are slower than theme hooks, I'm wondering if I might be able to use them for my application. Here's what I'm trying to do:

Right now I have about 10 content types on my site and I've created a separate template file for each because I want each to have a `<div>` with a specific 'id' so I can target those pages with CSS. I also give each a separate template file so I can determine on a case by if they should have a secondary sidebar or not.

Those are the only reasons I'm using all these template files.

**Two Part Question:**

Can what I'm trying to do be reasonably accomplished with theme hooks, and if so, how?

# Answer
The module that defines a template defines if it is a template or a theme functions, that's not something you have any influence over.

And yes, theme functions are faster, but they're also deprecated and will be removed completely in Drupal 9 (Because twig is far easier to write than PHP). With render caching and so on, the performance difference is no longer as relevant as it used to be.

The performance difference is between having a template or not. There's anyway a template, just not a custom one, and the only performance difference then is the additioal complexity that your template adds and what you are doing sounds trivial.

There might be reason to do what you're doing differently, you could use preprocess, but you'd need to at least share your templates/code (you should always do this when asking questiosn) so you can get a specific code example. But not because of performance, a more valid reason would be code/template management, it will be more work to make further changes if you have 10 different templates or just one.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: How can I use $_SESSION in form handler drupal 8?
I create a module that has form . I want send data from other form to this form and show them . How can I save previous data in my form and show new data ?

For example I send number 1 to my form and form show 1 , then send number 2 and form show 1 and 2 , and then send number 3 and my form show 1 and 2 and 3 .

Then I want send this data ( 1 and 2 and 3 and ... ) to other page with my form . how can I do this ?

My sender form :

```
<form action="/form" method="post">
   <input type="text" name="number" />
   <input type="submit" value="GO" />
</form>

```

# Answer
> 2 votes
The suberglobal `$_SESSION` still works in D8 and is used by core several times.

For a correct Drupal 8 way see this change record. It shows how you access the session variable through the request object. But it doesn't show how to get the request object.

So this is an example for accessing the session in a form handler:

```
use Symfony\Component\HttpFoundation\Request;

  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {

    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);
    $form['counter'] = ['#markup' => '<p>#' . $value . '</p>'];

```

In a controller or form you can pull the request from the route parameter stack by putting a typed parameter `Request $request` in the build method.

If you are in a procedural form function get the request from `\Drupal`:

```
$request = \Drupal::request();

```

---
Tags: 8
---


# Question
Title: Where is the Drupal Syslog module log file in Cpanel?
I disable dblog module and want to enable syslog module instead of it. After enabling that ,I can't see any drupal Log in error\_log file in cpanel .

what is reason? where is Drupal log file for cpanel shared hostings?

My drupal version : 7

thank you

# Answer
> 3 votes
As mentioned on the documentation page for the syslog module, syslog is generally not suitable for shared hosting.

This is because it requires access to server level functionality and configuration that you aren't allowed to access on shared hosting.

# Answer
> 0 votes
IMO the Message module could be a perfect alternative, for situations where "syslog" cannot be used. Using this module, you can create your own custom "*Events logging*" (to register things that happened in a site). Specific to this question here, I'd create a so called "Message type" that contains the actual data to be logged.

You could even track things like updates to nodes, i.e. how data looked like before and after they got updated, a kind of "light" revisioning (only for those node attributes you want to know about).

About *Message types*: think of them as equivalent to Content types, whereas you create messages (instead of nodes) of a specific Message type (instead of Content type).

### Rules integration

A really interesting facility of the Message module is its perfect integration with the Rules module. Have a look at the answer to "How to implement a follow author (or user) function?" for way more details on that.

As an example, here is a (rather basic) custom rule:

* a Rules Event like "Before saving a new node", of "After updating an existing node" (or variations of these events).
* a Rules Action to "Create a message" (of a selected Message type).

That's really it ...

### Example included in Commerce Kickstart

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create such "*Events logging*". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

### Replicate/replace the Activity module

Should you want to do so, it seems perfectly possible to build a view (report) that contains the data similar to what you can do with the Activity module as shown in this screenprint (from this module's project page).

### More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules.

Though there is ***not a lot of documentation about it*** (which is what makes it a hidden D7 gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

**Tutorials:**

---
Tags: 7, database
---


# Question
Title: How to resolve error with drupal commerce 2 installation via composer
I am following the instructions at http://docs.drupalcommerce.org/v2/getting-started/install.html

After providing the console command for a new installation, console starts to download the various requirements, but before completion, returns the following error.

> Failed to execute git checkout '879356bbf75608f86d8fb89d76a21dc1e99a39ae' -- && git reset --hard '879356bbf75608f86d8fb89d76a21dc1e99a39ae' --
> fatal: Not a git repository (or any of the parent directories): .git

I have read elsewhere that I need to initialise a git repo first? Not sure if I am missing something or whether the documentation is incomplete. I assumed it was a one line command.

What am I doing wrong and how do I resolve this?

I am not a very advanced user and intend to use Acquia Dev Desktop as working environment.

Further to the above, I went on to try creating the MYSITE directory first and then ran git init from within this folder. I then ran the composer commands for a full install, and then received another error as below.

> \[InvalidArgumentException\]
> Project directory commerce8/ is not empty.

# Answer
> 0 votes
This turned out to be a problem of running composer through Acquia Dev Desktop's terminal launcher.

When using native terminal the installation completes without issue.

---
Tags: commerce, composer
---


title: Custom Validation after Custom submit

text:
# Question
Title: Custom Validation after Custom submit
How to pass the custom validation after custom submission?

I have problem in getting a variable from a custom submit handler. Actually, the custom validation must happen in the last step in order to validate correctly.

Workflow is:

1.custom submit.

2.get a value from the API.

3.pass it to custom validation.

Since the custom validation step comes first, I am unable to validate it properly.

# Answer
> 1 votes
You can use form\_set\_value() in your validation handler. Let's say you are retrieving a user ID from a remote API, by sending the user's name. In your form definition, you can have:

```
$form['user'] = array (
  '#type' => 'textfield',
  '#title' => t('User to fetch'),
);

```

In your validation handler, you can retrieve the value. If a value exists you save it using form\_set\_value, and if it doesn't, you set an error:

```
$remote_user_id = retrieve_uid_from_api($form_state['values']['user']);
if($remote_user_id) {
  form_set_value($form['user'], $remote_user_id);
}
else {
  form_set_error('user', t('%user does not exist in the remote API', array('%user' => $form_state['values']['user']));
}

```

So in your submit function, \`$form\_state\['values'\]\['user'\] will now contain the User ID from the remote API:

```
$remote_user_id = $form_state['values']['user'];

```

---
Tags: 7, forms
---


# Question
Title: Commerce 2: Is it 'really' necessary to setup product attributes before adding a simple product?
Following along with the documentation at http://docs.drupalcommerce.org/v2/product/index.html#

Slightly puzzled by the following

> "Setup product attributes - Before creating products, you need to create some attributes... "

Is it really necessary to setup some product attributes? What about a simple product for which a the body field is all that is needed to describe the item?

Be interested to know whether there may be some other reason for why product attributes should be created or whether the documentation ought to be clarified?

# Answer
> 2 votes
If the products you are adding do not require different variations, there is no need to add attributes. Product attributes are meant to define unique properties of a variation of the same product.

An example would be a t-shirt where the color and the size are two different attributes. The shirt has the same print and model (eg. long sleeves), but any given combination of size and color can exist, each having a different price, photo, etc. and its own SKU.

The documentation lists the creation of attributes before the creation of products, so you can choose these attributes once you start adding products.

---
Tags: commerce
---


# Question
Title: In Drupal Commerce how do you auto login an anonymous user that has completed checkout?
I have Drupal 7 Commerce core installed and configured manually. Not kickstart.

Currently after completing a Commerce checkout (Paypal Express) with an anonymous user, I get redirected back to the "Checkout Complete" page. The page gives a link to **Review My Order**, but it asks for login details which I do not have since it was an anonymous checkout.

Is there a way to auto login the user after the Successful Checkout?

# Answer
In short summary to the link Clive posted in case if it ever gets deleted on the interwebs:

http://s1l.org/automatic-user-login-anonymous-checkout

Step 1 - Make sure Anonymous checkout is checked on. (**Permissions \> Access Checkout**)

Step 2 - Make sure Commerce Immediate Login module is enabled: http://drupal.org/sandbox/simongeorges/1676742

Step 3 - Add a User Login Action to the default Commerce "Create new account for anonymous order" Rule (**Configuration -\> Workflow -\>Rules**)

--- ***rules/reaction/manage/Create a new account for an anonymous order***

Step 4 - Click Add action \> Login User (under system) \> type "account-created" \> **SAVE**

Step 5 - TEST!
> 5 votes

# Answer
Simplest may be to edit the checkout completion text in Store \> Configuration \> Checkout and remove the relevant link.

A user account is created for the anonymous order after checkout by Commerce.

The user gets emailed a login link and they can check their order details directly by clicking a link in the email there.

This way, you can verify their email address prior to login.
> 0 votes

# Answer
These days, a module with an official release is available as an alternative to sandbox project in your own answer. I.e the Commerce Checkout Complete Registration module. Some more details about it (from its project page):

> About:
>
> It's about having a way to choose or not, for the Guest customer, if (s)he wants to register.
>
> * Create new pane for the "Complete" checkout page.
> * This pane has 3 settings (for now) : password required (boolean), account creation email notification (boolean) and the text to be displayed for this pane form.
> * The pane will contain a button form + extra elements as the settings say.
> * On this pane form submission:
>
> + an user account will be created and set as the current user;
>     + the order will be assigned to the new user;
>     + a Rule event will be invoked (with order and user objects);
>     + the user will be redirected to its order history page.
>
> Extra:
>
> This module could be used togheter with Anonymous checkout option of the Commerce Checkout Redirect module.
> 0 votes

---
Tags: 7, users, commerce
---


# Question
Title: hook for db insert function on custom table
Is there any hook on `db_insert` function on a custom table?

```
db_insert('projects')
  ->fields(array(
    'title' => $title,
    'p_key' => $projectkey,
  ))->execute();

```

# Answer
No, there's no hook invoked for `db_insert`.

If you have a custom table, though, you're probably controlling the insert code yourself, in which case you can invoke your own:

```
db_insert()->(...);
module_invoke_all('mymodule_foo_insert', $some_contextual_data);

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: addClass in Twig with if statement in item-list.html.twig
I try conditionally add a CSS class to a `<li>` element in `item-list.html.twig`.

```
{%- for item in items -%}

    {# check if is facet li #}
    {% if item.attributes.hasClass('facet-item') %}
    <li{{ item.attributes.addClass('list-group-item') }}>{{ item.value }}</li>
    {% endif %}

{%- endfor -%

```

When I add the if statement like above, I don't get any output at all. If I remove the if statement I get correct output like:

```
<div class="item-list">
    <ul data-drupal-facet-id="contactvoorkeur" class="js-facets-checkbox-links list-group">
        <li class="facet-item broodjeaap list-group-item">
            <input type="checkbox" class="facets-checkbox" id="contactvoorkeur-email" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Aemail">
            <label for="contactvoorkeur-email">E-mail <span class="facet-count">(2)</span></label>
            <a href="/search-person/cards?f[0]=contactvoorkeur%3Aemail" rel="nofollow" data-drupal-facet-item-id="contactvoorkeur-email" style="display: none;">E-mail <span class="facet-count">(2)</span>
            </a>
        </li>
    <li class="facet-item broodjeaap list-group-item">
        <input type="checkbox" class="facets-checkbox" id="contactvoorkeur-post" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Apost">
        <label for="contactvoorkeur-post">Post <span class="facet-count">(1)</span></label>
        <a href="/search-person/cards?f[0]=contactvoorkeur%3Apost" rel="nofollow" data-drupal-facet-item-id="contactvoorkeur-post" style="display: none;">Post <span class="facet-count">(1)</span>
        </a>
    </li>
  </ul>
</div>

```

# Answer
> 2 votes
I might be wrong here, as we do know know what problem you are having...

But `{{ item.attributes.addClass('list-group-item') }}` will add the `list-group-item` class to the `item`-element. (It does not print this class.)

Because of the surrounding code: `{% if item.attributes.hasClass('facet-item') %} ... {% endif %}`, I feel you want to add a class to the childs of `item`, not to `item` itself.

Why not output this instead?

```
<li class="list-group-item">{{item.value}}</li>

```

So the condition becomes:

```
{% if item.attributes.hasClass('facet-item') %}
  <li class="list-group-item">{{item.value}}</li>
{% endif %}

```

---
Tags: theming, 8
---


# Question
Title: How to use Rules to email users when any field(s) is changed in a node (and include the unchanged/changed values for that field)?
I know how to email using Rules when a field in a node is changed and add conditions for particular fields whether they were changed.

But I would like the email to contain the info which field(s) exactly were changed and from/to which value.

E.g., I have a content type with 20 fields. Then I create a node and populate all the fields. Now I want to change two fields in the node (e.g., "First Name" and "Age").

I'd be happy to receive the following email:

The following was changed in "Node name":

"First name" changed from "John" to "George".

"Age" changed from "35" to "76".

# Answer
> 0 votes
Some of the ingredients you'll need for a possible solution to make this work:

* The Conditional Rules module.
* Rules Actions "Add a variable" and "Set a data value".

Read on for more details ...

Here is a rule, in Rules export format, which is a prototype of what you're trying to get to work:

```
{ "rules_notify_admin_of_selected_field_updates" : {
    "LABEL" : "Notify admin of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "OR" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
        ]
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "Field changes applied to a node:" },
          "PROVIDE" : { "variable_added" : { "field_changes" : "Added variable" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-optionlist" ],
                "value" : [ "node-unchanged:field-optionlist" ]
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "field-changes" ],
                  "value" : "[field-changes:value] - Field Optionlist changed from \u0022[node-unchanged:field-optionlist]\u0022 to \u0022[node:field-optionlist]\u0022"
                }
              }
            ]
          }
        ]
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-free-format-text" ],
                "value" : [ "node-unchanged:field-free-format-text" ]
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "field-changes" ],
                  "value" : "[field-changes:value] - Field Free Format Text changed from \u0022[node-unchanged:field-free-format-text]\u0022 to \u0022[node:field-free-format-text]\u0022"
                }
              }
            ]
          }
        ]
      },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "Field changes in node with nid=[node:nid]",
          "message" : [ "field-changes" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Some more details about the above rule:

* It showcases updates to (only) 2 fields, i.e.:

+ a *selection list* field with machine name `field_optionlist`, and a few possible values.
    + a *free format text* field with machine name `field_free_format_text`.
* The Rules Actions "Add a variable" is to create an appropriate variable.
* The Conditional Rules module allows for including like "Rules Conditions" within the Rules Actions.
* Using "Set a data value" we append what's appropriate to that variable.
* In the end (last Rules Action), we make Rules send an eMail with an extremely basic eMail body: the content of the variable we populated in the previous Rules Actions.

Assuming that you enabled the Conditional Rules module, you should be able to import the rules example above in your own environment (provided you first defined 2 similar fields with identical machine names to make the import work, or after you first edit the field names to match your field names).

Homework:

* Extend the prototype from 2 to 20 fields (= sames as except ...).
* You may want to improve the formatting of the eMail body, eg add some relevant HTML tags in it to make it more readable. Maybe also its subject, etc.

Voilà, happy (Conditional) Rules-ing!

PS: Would be nice if you could use a Rules "loop" to iterate over all 20 fields in a single loop, similar to what is shown in the answer to "How to create a rule to send an email to a list of selected email addresses?". However I'm not aware of anything in Rules to do so.

---
Tags: 7, nodes, entities, rules, emails
---


# Question
Title: Is there any log or receipt or anything that message was sent to someone?
I'm in a situation where I'm supposed to testify (= proof) that a message (confirmation) was sent from our site (using Drupal 7).

Is it possible to see it from anywhere? Does it register into hosting provider or something like that?

I tried looking at the log files on the server, but they didn't include anything regarding this message; the Drupal system log was one month ahead that time when the message was sent.

A custom message (confirmation) is sent with Rules when user makes an order and registers as user (of which all is done via customized "Add node" form).

# Answer
It won't help to go back in time, but for similar requests in the future I recommend you to have a look at the Message module, which is part of the Message Stack. Read on for more details ...

### Create a Message archive (audit trail)

By using the Message module, you automagically also create an archive of all Messages. Which is very handy in cases such as when a user claims to never have received some eMail. In such cases, think about how you'd proof that some eMail was mailed somewhere in the past ... as compared to using Message and just bring up that message again ...

A typical scenario (as in the question here) that would be prevented by using the Message module:

> I tried to look at the log files at server but they didn't include anything regardins this message. Also the Drupal system log was one month ahead that time when the message was sent.

### Message stack

These are the basic components and dependencies of it:

For this question only the Message module would be needed (not the other Message-related modules). But first, to explain the above picture, some more details about the Message-related modules (=quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

### Distributions / modules using Messages

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create such "*Events logging*". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its **Answers Notification** sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

### Combining Rules and Message

Moreover, by using the technique of ***Replacement tokens***, it's possible to create your own Message-"tokens" using ... Rules! If these *Replacement Tokens* don't mean anything to you (ie you don't understand what they are really about), then head over to the answer to What's the purpose of "Replacement tokens" of a Message type? for (way) more details on that.

As an example, here is a (rather basic) custom rule:

* a Rules Event like "Before saving a new node", of "After updating an existing node" (or variations of these events).
* a Rules Action to "Create a message" (of a selected Message type).

That's really it ...

A really interesting facility of the Message module is its perfect integration with the Rules module. Have a look at the answer to "How to implement a follow author (or user) function?" for way more details on that.

Yet another sample that could be a perfect fit (= a quote from the question ...):

> I'm using Drupal 7 and custom message(confirmation) is sent with Rules when user has made an order and registered as user (of which all is done via customized "Add node" form).

### You might be lucky

The prior quote got added to the question afterwards. And possibly explains also why you tagged your question with the tag (removed in revision 3 by a mod).

So if you're lucky your site might already use the Commerce Message module, in which case you already might have such audit trail (which you don't know about). Just use Views to search what you're looking for.

If you don't use that module yet, then hurry to get it enabled for similar requests in the future.

### Possible alternative for syslog

The Message module is also a possible alternative for the Syslog module (included in Drupal core). For example in situations like this one (= quote from "Syslog module overview"):

> It is not suitable for shared hosting environments.

### More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules.

Though there is ***not a lot of documentation about it*** (which is what makes it a hidden D7 gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

**Tutorials:**
> 1 votes

---
Tags: 7, emails
---


# Question
Title: How can I prevent some configuration settings getting overwritten?
I tell drush this:

```
drush @live cim --skip-modules=system,swiftmailer

```

and Drush replies with this:

```
  Collection  Config                 Operation
              swiftmailer.transport  update
              system.performance     update
  Import the listed configuration changes? (y/n)

```

and, if I reply "y", the settings in the live Drupal site are overwritten from settings previously exported from the dev system.

What do I have to do to avoid importing selected parts of an exported configuration?

# Answer
> 2 votes
I believe that Config Ignore could help you out here.

Spoiler: I am the maintainer of that module.

Install the module, go to `admin/config/development/configuration/ignore` and add the names of the config entities that you would like to **not to change**, when you import.

In this case:

```
swiftmailer.transport
system.performance

```

Save, remember to export `config_ignore.settings.yml` to the config folder (yes, some of us tend to forget that bit) and you should be golden.

---
Tags: 8, drush, configuration
---


# Question
Title: Problem with JS linked to an Ajax loaded page
I am trying to load a form via ajax, the PHP callback that send the data to the Ajax request looks like this :

```
function group_form (){

        $node_type = 'group';
        $form_id = $node_type . '_node_form';
        $node = new stdClass();
        $node->type = $node_type;
        $node->title = 'helllooo';
        $node->language = LANGUAGE_NONE;
        $node->path = '';
        node_object_prepare($node);
        $return=drupal_get_form($form_id,$node);

    echo render($return);
}

```

I use to have a problem when using `return` instead of `echo` as mentioned in this , where the whole page was being sent via Ajax instead of just the form element. However now that i use `echo` all the script attached to that form do not get reloaded, witch cause problem as my form uses the date module with a jQuery popup calender, and infinite value fields witch need some Drupal JS in order to add multiple values without page reload.

So i wonder if there is a way around that, if not, anyone has anyidea of what script i should reload on the ajax succes callback in order to have my date module popup calendar and the drupal "Add more" function for infinite value field working ?

**EDIT:** I found that using `Drupal.attachBehaviors(jQuery('#LoadedContent'));` seems to be helping as it brings me from this

---

to this ,

---

though clicking on the "Add another item" Button still reload the page and i end up with this :

Thanks a bunch for the help.

# Answer
Have a look at the Ajax Framework. It will make your life way easier. You can probably accomplish everything you're trying to do with out a single line of js.
> 1 votes

# Answer
You need to pass the JS settings that are created when the form is rendered:

```
function group_form (){

  $node_type = 'group';
  $form_id = $node_type . '_node_form';
  $node = new stdClass();
  $node->type = $node_type
  $node->title = 'helllooo';
  $node->language = LANGUAGE_NONE;
  $node->path = '';
  node_object_prepare($node);
  $form = drupal_get_form($form_id,$node);

  $response = render($form);

  $scripts = drupal_add_js();
  if (!empty($scripts['settings']))
  {
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
    $settings .= ');</script>';
  }

  $response .= $settings;

  echo $response;
  drupal_exit();
}

```

Though personally I'd put the response in an array. So instead of this:

```
$response = render($form);

$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
  $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
  $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
  $settings .= ');</script>';
}

$response .= $settings;

echo $response;
drupal_exit();

```

I'd use this:

```
$response['form'] = render($form);

$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
  $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
  $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
  $settings .= ');</script>';
}

$response['form'] .= $settings;

drupal_json_output($response);
drupal_exit();

```

Your form will be available at data.form in the ajax.

You will also need to call the following after injecting your form into the page:

```
Drupal.attachBehaviors();

```
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: How to allow Infinite Scrolling through "Views Load More" module with waypoints?
I am trying to achieve infinite scrolling for my view results in Drupal.

Now It could have been easier if I could use `Views Infinite Scroll` module but I couldn't use as it doesn't allow Views Ajax. Since I am using filters that heavily rely on AJAX, I am out of luck for using this module.

As I read, there is another option through `Views Load More` module, but it can only allow infinite scroll through `Waypoints`. This is where my problem lies as I am unable to understand how to use waypoints with Views Load More module.

I'll be super grateful if you could assist me in this.

This is Waypoints code from their site:-

```
var waypoint = new Waypoint({
  element: document.getElementById('#waypoint'),
  handler: function(direction) {
    console.log('Scrolled to waypoint!')
  }
})

```

# Answer
> 2 votes
It's actually really easy to do with standard Views and jQuery.autopager in your theme.

The most important part is using the correct classes, I can't find my working example at the moment, but it should look something like:

```
$.autopager({
  // where contents would be appended.
  // use "appendTo" or "insertBefore"
  appendTo: '.views-content',

  // a selector that matches a element of next page link
  link: '.pagination .next a:first',

  // a selector that matches page contents
  content: '.views-row',
});

```

# Answer
> 1 votes
You can have a try for Views Infinite Scroll module as now, its in stable `8.x-1.3` version.

---
Tags: views
---


# Question
Title: How to list Content A nodes on Content B's page using Entity Reference fields and Views (with Paragraph field Bundles attached)
I have **Content A (Music Albums)** with **entity reference fields** referencing **Content B (Musician)**.

I want to display a view on **Content B (Musician)** page that displays every **Album (Content A)** they are 'tagged' on. Basically using entity reference fields in place of taxonomy (per StackExchange suggestion).

**Content A (Album)** has a View displaying various info such as *album image, album name, record label etc...* and an **Entity Reference** field referencing **Content B (Musician)**. When clicked it takes me to the node page of that Musician.

On the **Musician's (Content B)** page I want to have a View displaying all **Albums (Content A)** they appear on (tagged via entity reference field).

Finally, Getting the entity reference fields attached to a Paragraph Bundle to relate to **Content B (Musician)**

# Answer
> 2 votes
Simply under **Advanced** (far right), for **Contextual Filter** add your entity reference field. In my test, I called it "Made by" `field_made_by`.

**Note:** The view preview will be blank as the view edit page does not have an ID. Just place to your Musician page and it will show up then.

---

> However, when using paragraphs module to add node bundles is more complex because technically a paragraph bundle is it's own entity, so Content A references a Paragraph Bundle with an entity reference field within its bundle (LOL). It gets pretty complicating. Any help with that?

Then make a view of Paragraph and not of Content.

Then add relationship of `Paragraph referenced from field_paragraph` (paragraph field)

Then in contextual filter add `field_made_by` (entity reference field).

---
Tags: views, entities, paragraphs
---


title: Search the node using keyword

text:
# Question
Title: Search the node using keyword
I have created a text box with button to search the node which has the key word given in text box. Is there any possible to search the node in Drupal 7 with custom search button and textbox which is in tpl file

# Answer
> 2 votes
You can not include search box generated by custom search module into views, but you can add exposed filter into views to implement search functionality in the views.

To implement search functionality in the views

* Add "field" in the filter and choose "Contains" from the operator list
* Exposed field in the filer

It will display a search box for that field in the views and work nicely for searching. Moreover, you can enhance its display by using views tpl and control where to display this views block.

---
Tags: 7, nodes, search, tokens
---


# Question
Title: How exactly do I create a variation of a .tpl file?
I am new to Drupal and am working on a partially complete site. There's a .tpl file I wish to duplicate and alter and have only be used with a certain Panel Page type ('Product Page').

I've read Drupal's documentation about template suggestions, but am not sure what to actually do.

I've placed the following in my template.php file:

```
function mytheme_preprocess_node(&$variables) {
  if ($variables['???']) {
    $variables['theme_hook_suggestions'] = 'new_tpl_file';
  }
}

```

But I've got no idea what to put in `$variables['']` so that the suggestion appears on my pages. I know my Panels page is called 'Product Pages' but that's it. Is there a machine name for that I can use as a variable? Would it work if it was something like:

```
      if ($variables['product_pages']) {

```

Does anyone know of a tutorial or guide out there? Im pretty lost here. Any help is appreciated!

# Answer
> 2 votes
If you are trying to override panel page template then I am afraid you are using the wrong hook, `hook_preprocess_node` works for node pages only.

However panel page goes through `hook_preprocess_page`, so you can add custom template suggestion in following way.

```
/**
 * Implements template_preprocess_page().
 */
 function MODULEORTHEMENAME_preprocess_page(&$variables) {
    if (module_exists('page_manager') && count(page_manager_get_current_page())) {
        $variables['theme_hook_suggestions'][] = 'custom__panel';
    }
 }

```

Then create `custom-panel.tpl.php`

Reference: page.tpl.php override for Panels Pages?

---
Tags: 7, theming
---


# Question
Title: How to make a Custom Field available as View Relationship?
I'm trying to match the data of a field to a contextual value but I cannot find my desired field in the relationships list.

Do I have to something special to this field to get it to show up under relationships?

# Answer
> 1 votes
> I'm trying to have a filter that shows content where the name of logged in user is equal to the value of custom field.

Add your custom field as a Contextual Filter.

Select `Provide a default value` then for Type select `PHP Code`

PHP Contextual Filter Code

```
  global $user; // gets current logged in user object

  if (isset($user->name)) {
     return $user->name; // gets user name
  }

```

---
Tags: 7, views
---