# Question
Title: How to skip (don't update) some fields from existing node during import if this field already has a value?
I'm using drupal 7, feeds 7.x-2.0-alpha8. How to skip (don't update) some fields from existing node during import if this field already has a value?

i.e. We periodically import some products with photo (create new and update existing). After that editor can change photo. How can I skip this photo field during next update?

There is some feeds tamper plugin to check is field in updating node is empty? Maybe there is some hook from feeds or feeds tamper?

# Answer
Had the same problem. I finally used hook\_feeds\_presave(), and unset the field I wanted to skip. Here's the code:

```
function mymodule_feeds_presave (FeedsSource $source, $entity, $item, $entity_id) {
  if ($source->importer->id == 'myimporter'){
    // I check if my imported value is equal to a special marker i set
    if ($entity->my_field['und'][0]['value'] == 'MARKER') {
      unset($entity->field_i_wanted_to_skip);
    }
  }
}

```

This automatically resets THAT FIELD ONLY. Hope this helps someone.
> 3 votes

# Answer
If you do not wants to update the previously imported feed. you can check this
> 0 votes

# Answer
Skipping the whole entity item is easy by setting `$entity->feeds_item->skip` to `TRUE`.

However unsetting the selected fields could be more tricky. The workaround is to unset these fields in `hook_feeds_presave`, however some more complex fields may not like to be unset and can generate some unpredictable errors (e.g. field collection).

So another approach is to load the old node and override the new values with the old. Here is some mixed example of unset some fields and override another:

```
/**
 * Implements hook_feeds_presave().
 *
 * Invoked before a feed item is saved.
 */
function hook_feeds_presave(FeedsSource $source, $entity, $item) {

  $config = $source->importer->getConfig();
  $skip = &$entity->feeds_item->skip;

  if ($entity->type == 'my_type') {
    if ($status == FOO_SKIP_IT) {
      // Don't update anything.
      $skip = TRUE;
    }
    elseif (condition) {

      $node = node_load($entity->nid); // Load the old values.

      foreach ($entity as $key => $val) {
        // Passing system fields and additional feed fields images and price.
        if (in_array($key,
              array(
              'vid', 'uid', 'log', 'comment', 'promote', 'sticky', 'vuuid',
              'nid', 'type', 'language', 'created', 'changed', 'tnid', 'translate',
              'uuid', 'revision_timestamp', 'revision_uid', 'metatags', 'locations',
              'location', 'name', 'picture', 'data', 'num_revisions', 'current_revision_id',
              'is_current', 'is_pending', 'revision_moderation', 'date', 'revision', 'menu',
              'feeds_item', 'guid', 'field_feed_status', 'field_collection', 'field_some_complex_field',
              ))) {
          continue;
        }
        else {
          // Unsetting unnecessary fields.
          unset($entity->{$key});
        }
      }

      // Override values with the old one.
      $entity->field_collection = $node->field_collection;
      $entity->field_some_complex_field = $node->field_some_complex_field;

    }
    else {
      // Otherwise update all fields.
    }
  }
}

```
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: programmatically disable menu based on user taxonomy reference fields
I am trying to programmatically disable menu based on account settings/user taxonomy term field, is there a better way to do it? do I need to use hook menu? to disable already built menu, as I have a lot of users in department that needs to get filtered to only show the menu they can edit

UPDATE :

I wanted to hook the permisssion of user so not all can edit the menu structure, like edit links and so on, like example I allowed permissions manage menu 1, manage menu 2, for role a, then I wanted to hook that menu 1 is only available for user with term reference 1. something like that

thank you!

# Answer
> 3 votes
The answer will depend on what your created menu items route to (`hook_menu()` is for defining new menus so it won't help you here).

Generically, `hook_menu_alter()` allows you to alter the `access callback` so that you can override access with your own logic. If the path you're overriding is specific to a special module route (e.g. **admin/dashboard**), then it would make sense to use this hook.

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['admin/dashboard']['access callback'] = 'MYMODULE_access';
}

/**
 * Access callback function
 */
function MYMODULE_access() {
  global $user;
  $user_entity = user_load($user->uid);

  // @TODO: Check your user entity's taxonomy field for access and return
  // TRUE | FALSE

  // EXAMPLE: Allow access for USER #123
  // return ($user_entity->uid == 123);
}

```

If your created menu items link to content nodes then you should look at `hook_node_access()`. This hook is specifically designed for controlling access to nodes so you'll have access to the node/user object from the hook's arguments.

```
/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access($node, $op, $account) {
  $user_entity = user_load($account->uid);

  // @TODO: Check your user entity's taxonomy field for access and return
  // NODE_ACCESS_ALLOW | NODE_ACCESS_DENY | NODE_ACCESS_IGNORE
  // depending on your logic
}

```

---
Tags: hooks, taxonomy-terms
---


# Question
Title: Need help to work with videos and FFMPEG
I am building a website that people upload a video and then they can cut a piece of the video. I am using FFMPEG.

I know how to do this using pure PHP, but since my website is based on Drupal, I prefer to use the Drupal modules.

I saw PHP FFmpeg and FFmpeg Wrapper modules that work with FFMPEG. I would like to know is there any advantage in using these modules or using the pure PHP is preferable? Can these modules save the clipped videos as a node or not?

Thanks in advance.

# Answer
The only advantage these modules is assistance in managing your dependency on FFMPEG and how you want interface it in PHP code.

* PHP FFMPEG is a helper module for managing a dependency on the PHP FFmpeg library. If you want to use the PHP FFmpeg library, and require a Drupal module that will ensure your module has FFMPEG available to it, this module will help.
* FFmpeg Wrapper is a handful of custom functions that interface with FFMPEG via PHP's `passthru()` function. If your PHP environment can execute `passthru()` and you want some basic functions to execute some ffmpeg console commands, this module will help.

Both are API modules that don't provide any other integration with Drupal.
> 1 votes

---
Tags: 7
---


title: Users can't cancel their own order

text:
# Question
Title: Users can't cancel their own order
I'm using Drupal Commerce Kickstart to create an E-commerce website.

How can customers cancel their own order if they accidentally ordered some wrong product?

>

# Answer
Find permission page (/admin/people/permissions) and You can give Authenticated users permission to "Edit own Order orders"
> 0 votes

---
Tags: commerce
---


# Question
Title: How to give permission for a role for editing help text for fields of custom types?
I want role "RoleFoo" to have only the permission to edit the Help Text of all fields of specific content types (contentypefoo1 and contentypefoo2).

How to do this?

# Answer
The Field help helper module seems to be a good fit for this. some more details about it (from its project page, which is also here the image originates from):

> The Field help helper module adds a link to entity configurable fields so that users with the appropriate permissions may easily edit the help text and label for a field in context of where the field displays.
>
> Once a user's role is given the Edit field help text permission any user with that permission will be able to edit the help text or label of a configurable field without having access to administer fields.

**Extra bonus**: comes wth an official release for both D7 and D8 ...
> 2 votes

---
Tags: 7, users
---


# Question
Title: How do I produce 2 lists with one display?
I'm back on this issue for me because I would to implement Responsive slideshows with thumbnails and many of those use 2 elements to display thumbs and full image. So I know I need to edit the style output template or the row style output template but I don't know how to find values provided by views to print them inside my template. This doesn't explain how to find variables. I'm looking for some example and explanations to understand how to do.

So I get the style output template, and I have done as you said to print fields. I want to modify the field settings in the view.

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
  <!-- Construction de la liste -->
  <ul class="bxslider">
<?php foreach ($rows as $id => $row): ?>
  <li class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </li>
<?php endforeach; ?>
</ul>
  <div id="bx-pager">
      <?php foreach ($rows as $id => $row): ?>

    <?php print ($fields['field_galerie_image_vdl_fid_1']->content); ?>

<?php endforeach; ?>
</div>

```

I can't find the right targeting for my desired field, and in the I need to exclude some part of the output.

# Answer
> 1 votes
Under Advanced, **Theming: Information**, click on Information and you will see something like this:

For template file name you want to use the last suggested name, (which I underlined for you) that way it only affects this specific view and not others.

In the above example Row Style Output: you would use **views-view--fields-shipping-cart--block.tpl.php**

To print your fields, inside the template file you put

```
<div class="example1"><?php print $fields["title"]->content; ?></div>
<div class="example2"><?php print $fields["field_name"]->content; ?></div>

```

`Title` prints your node title, else if you want to print a field, you use `field_name`

Remember to flush the cache to see changes or you could click the `Rescan template files` button

If you're unsure of the name of a field, In view's click on your field, and go to re-write the output of the field, click on replacement patterns, whatever name replacement patterns uses is the one you need to use.

Alternatively, instead of working with template files, you could work with just replacement patterns if you like as my answer shows here

Else if you just want to add classes to your fields, you can do it with views like this:

---
Tags: views, theming, 6
---


title: Fill form on ajax callback

text:
# Question
Title: Fill form on ajax callback
Seems to be an extremely simple question. But I can't figure it out. In my module's form I need to load form values depend on the value of certain one and rebuild the form using those.

here is the part of the code (form builder):

```
$namevalue = isset($form_state['values']['name']) ? $form_state['values']['name'] : "";
$form['name'] = array(
    '#type' => 'textfield',
    '#default_value' => $namevalue
);
$form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#ajax' => array(
        'callback' => 'simplenews_mod_load_subscriptions',
    )
);

```

Here is the callback:

```
function simplenews_mod_load_subscriptions( $form, &$form_state){
  $form_state['values']['name'] = "loaded value"; // here will be a function which will get the value form DB
  return $form_state;
}

```

Nothing changes in the $form\_state array. I think I just don't get the basis of ajax in D7 itself... I'd be very appreciated if someone show my the simplest example of how to change a form field value using ajax.

Or alternatively: how do I rebuild form with new values using custom submit callback. Not on validation.

Thank you.

# Answer
the problem was in the way I pass submit callback. It should be like

```
'#submit' => array('foo_submit_callback')

```

**ARRAY!**

the less visible thing is the most visible one...
> 0 votes

# Answer
You're pretty close...

```
$form_state['values']['name'] = "loaded value";
return $form_state();

```

Is wrong for a few reasons:

* Messing with the submitted values (`$form_state['values']`) directly possibly isn't the best idea; if you need to do it that way, use `form_set_value`, but even better, stash it somewhere else in `$form_state`
* `$form_state` is an array, and can't be invoked as a function. If you look in the logs, your AJAX requests will probably be returning a 500.
* You need to return the element of the form that you want to replace rather than the state; `$form_state` is by reference so changes you make are persisted to it that way.

You're also missing the `wrapper` property for the ajax array in the form function, so the system won't be able to manipulate the DOM with the new data.

With those in mind, try something like this for the form function:

```
$namevalue = isset($form_state['namevalue']) ? $form_state['namevalue'] : "";
$form['name'] = array(
    '#type' => 'textfield',
    '#default_value' => $namevalue,
    '#prefix' => '<div id="name-value-field">',
    '#suffix' => '</div>',
);
$form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#ajax' => array(
        'callback' => 'simplenews_mod_load_subscriptions',
        'wrapper' => 'name-value-field',
    ),
    '#submit' => 'foo_submit_callback',
);

```

and this for the callback:

```
$form_state['namevalue'] = "loaded value"; // here will be a function which will get the value form DB
return $form['name'];

```

and a submit handler for your button to rebuild the form:

```
function foo_submit_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

```
> -1 votes

---
Tags: forms, ajax
---


# Question
Title: How to add link to Comment Author's User Profile page
The below code is from the comment.tpl.php file:

```
<div class="comment-avartar">
<?php print $picture ?>
<div class="submitted"><?php print render($content['submitted_by'] ['#markup']);?></a></div>

```

I want "$content\['submitted\_by'\] \['#markup'\]" to link to the user profile of the user who posted the comment.

i have tried editing the code to something like this:

```
<?php $link = drupal_get_path_alias('user/' . $user->uid);?>

<div class="comment-avartar">
<?php print $picture ?>
<div class="submitted"><a href="<?php $link ;?>"><?php print render($content['submitted_by'] ['#markup']);?></a></div>

```

But it links to the user profile of the currently logged in user.

What I would like is to link it to the profile of the Comment author.

Thank you.

# Answer
Comment module does add a link to comment author name on comments view. The link is conditionally visible to user's i.e. If user has permission to "**View user profiles**" or administrative permission then he will be able to see author name as link, else plain text. See screenshots below (tested with **Anonymous** user with and without permission "View User Profiles"):

**Permissions:**

**Comment preview with permission:**

**Comment preview without permission:**

You can still add a link to author name by your own, by implementing **template\_preprocess\_comment()** function in your theme's **template.php** or **.module** file. This might lead to access denied page:

```
/**
 * Process variables for comment.tpl.php.
 *
 * @see comment.tpl.php
 */
function [THEME_NAME]_preprocess_comment(&$variables) {
  if (!empty($variables['elements']['#comment']->uid)) {
    $variables['comment_author'] = l($variables['elements']['#comment']->name, 'user/1/' . $variables['elements']['#comment']->uid);
  }
  else {
    $variables['comment_author'] = t('Anonymous');
  }
}

```

And then printing "**$comment\_author**" variable in comment.tpl.php file, see below.

```
<p class="commenter-name">
  <?php print $comment_author; ?>
</p>

```
> 0 votes

---
Tags: users
---


title: Fix Unusual Boolean Variable Behavior

text:
# Question
Title: Fix Unusual Boolean Variable Behavior
I have this `javascript` code, that calls a `php` function `myid_save_ellipse_elements`

```
jQuery.ajax({
    type: 'POST',
    url:'?q=myid_save_ellipse_elements',
    data:{
        'ellipse': true
    }
}).done(function(status){
});

```

Below is the php function:

```
function myid_save_ellipse_elements(){
   $ellipse = $_POST['ellipse'];
   watchdog('ellipse', print_r($ellipse, true));
   $fields = array('ellipse_id_side' => $ellipse);
   watchdog('fields', print_r($fields, true));
}

```

After performing the code above, the watchdog message logs two message. The first message is `true`, and the second message is `Array([ellipse_id_side] => )`.

The second logs no value. why is it?

# Answer
It is because of ellipse has value as TRUE. Use var\_export instead of print\_r. Check example below:

```
  $ellipse = $_POST['ellipse'];
  watchdog('ellipse', print_r($ellipse, true));
  $fields = array('ellipse_id_side' => $ellipse);
  watchdog('fields', var_export($fields, true));

```
> 0 votes

---
Tags: log-messages
---


# Question
Title: Content Statistics: Total View not showing up in Services
I'm pretty sure this worked the other day, but today I checked and it didn't appear in my `Services`

If I add a new field such as `body`, it appears in my `json` file.. When I add `Content Statistics: Total Views` it won't add it.

I tried doing it a dirty way by adding a `Global Text` and use a replacement pattern, but then it outputs it like: `[totalcount]`

Also worth noting I can see it in the preview.

# Answer
As I understood, this is a permission problem and it is possible that only admin is allowed to see that view.

You can set the permissions in the view itself so that it is available to all users otherwise just log-in as Admin to see the 'view'.
> 0 votes

---
Tags: services
---


# Question
Title: Avoid the user is asked to download the files
I am very new to Drupal sorry if my question is very basic or common. I am creating a web site using Drupal 7 and I am using Tack da files module to tack files which are available for download.

My problem is that I have many PDF files in my site available for download, and the sites shows a popup window to download some of those PDF files. I do not want that popup window, but the site showing the PDF.

Why does it offers the user to download the files, instead of showing them?

# Answer
So It sounds like your problem is more with inconsistent of how links being opens. A simple solution to this make links opening consistent from theme layer. In your themes folder inside

> template.php

add a theme hook

```
function theme_file_link($variables) {
//Some Code from https://api.drupal.org/api/drupal/modules!file!file.module/function/theme_file_link/7.x
if($mimetype == 'application/pdf')
$options['attributes']['target'] = '_blank'; // Force to open PDF link in new tab
return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

```

I hope always opening PDF file in new tab will solve this inconsistency.

Let me know if that helps.
> 0 votes

# Answer
By listening to it , it sounds that your browser does not have PDF plugin installed , that is why it downloads file instead of opening.

The same thing can happen to lot of your user, solution to that is Mozilla Project pdf.js

Drupal also have a module for this PDF Module, check that out and see if that helps.
> 0 votes

---
Tags: 7
---


title: Drupal cron is running very frequently

text:
# Question
Title: Drupal cron is running very frequently
Drupal cron is running every 10 minutes in my site but i have set-ed 1 day time for cron, i have cleared cache and fix all the major php error logs, please help me how to fix this issue.

# Answer
> 0 votes
> i have set-ed 1 day time for cron

Presumably you mean you've set the "poor man's cron" value at admin/config/system/cron to 1 day - that value controls how often Drupal will run cron itself as a reaction to people actually visiting pages; it's not full-automated, hence "poor man's".

Assuming the value is being persisted (i.e. you don't have a global conf override or something for that var), then Drupal will respect it, and only run cron itself when more than a day has passed since the last run.

If it's still running every 10 minutes, then you have another process somewhere doing that - not Drupal.

Check your crontab/pingdom account/your usual alternative to find the culprit. If it's being invoked via URL, not drush/other script via crontab, then you can enable/inspect access logs to get an idea of where the request is coming from. Pingdom's IP ranges are public, for example, so you'd be able to determine if it's coming from there easily enough.

---
Tags: caching, cron
---


title: Sort on Custom field in views

text:
# Question
Title: Sort on Custom field in views
I am using views 3 in D7 and have added custom field of percentage on students result listing. I want to sort on the percentage field, how can I add sort on custom field?

Thanks for your help.

# Answer
> 2 votes
Your custom field is added after the query is performed by views, and a the sort is done as part of the query, therefore your sort doesn't know about your custom field.

I'd probably try to store the percentage in a field on the content type and then you'll be able to sort using the normal views sort handlers.

# Answer
> 1 votes
I would go with using views php, they have a sorting option on there.

---
Tags: entities, views
---


title: Override template files in child theme

text:
# Question
Title: Override template files in child theme
I am newbie in Drupal. Using some articles, I have created a child theme of Bartik in Drupal 8 but I do not know how to override default template files. Can anyone help me to understand the child theme structure in Drupal 8?

# Answer
In your child theme's folder create a subfolder called "templates". In this folder you should store your own templates. Just copy the system's (or parent theme's) template to your folder and modify it.

Further on, you can create more special templates, i.e. not only node.html.twig but also node--blog.html.twig.

Finally, switch on twig debugging, then you will get comments in your html like this:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--bootasde-branding.html.twig
   x block--system-branding-block.html.twig
   * block--system.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/block/block--system-branding-block.html.twig' -->

```

Then you always know which template was finally taken.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Views exposed filter to take multiple values
I'm running a D7 system and have a requirement where I want user to be able to pass multiple values in one of the exposed filters.

I've got hundreds of nodes called 'group' and I want user to be able to pass multiple 'group' names in order to filter results.

is this possible?

# Answer
You can use Better Exposed Filters module for this type of requirement you have.

Using this module you can add multi-select option for group names, so you will filter your results on multiple values.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to make a multi field reference multiple content types?
I'm trying to implement a Project Member relationship but I don't know how to do that. I have as a content types: Project, Member and Position as the attached UML diagram shows. My doubts are about the team field in Project.

I need to relate team members with a certain positon (which can be different from default position) to the Project. One way would be to create another content type called ProjectMember, but I'm trying to avoid that.

What would be the fastest vs the most elegant way to implement that?

Is Field Collection module a suitable way to go?

# Answer
This is one way:

* **Project** (Content Type)
* **Member** (Content Type)
* **Position** (Taxonomy - Because maybe you want to classify)

In **Member** you will have a field that is a Term Reference to **Position**.

In **Project** you will have a Field Collection named **Project Position**, which will have an Entity Reference to **Member** and a field that is a Term Reference to **Position**.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Requesting REST-GET gives me 403 but works fine in DHC
I am stuck for hours now with a JSON REST problem:

I have a simple REST endpoint in my Drupal 8 App. If I call it with the DHC Chromium REST Extension like GET http://proreos/api/v1/checklawyer/1?\_format=json, I get

```
127.0.0.1 - - [07/Jul/2016:15:03:54 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 200 477 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36"

```

That's wonderful. Also Drupal does all the requested processing. But if I call it from curl like

`curl 'http://proreos/api/v1/checklawyer/1?_format=json'`

I get the bad 403 response:

```
127.0.0.1 - - [07/Jul/2016:15:10:27 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 403 409 "-" "curl/7.35.0"

```

Well actually, I want to call it from a JS plugin like:

```
function checkLawyer() {
  var server = drupalSettings.bootasde.proreos_server;
  var id = drupalSettings.bootasde.asdeid;
  var jUrl = server+'api/v1/checklawyer/'+id+'?_format=json';
  console.log('Q: '+jUrl);
  jQuery.getJSON(jUrl);
}

```

It works fine, but unfortunately, it also gives me a 403 without any further Drupal backend processing:

```
127.0.0.1 - - [07/Jul/2016:15:06:03 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 403 464 "http://proreos/asde/anwalt/1" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"

```

Console says:

```
15:17:22.973 "Q: http://proreos/api/v1/checklawyer/1?_format=json"
XHR HTTP/1.1 403 Forbidden

```

Any idea would be great! Thanks.

# Answer
Doomed, I am so stupid. Chrome had the admin cookie, FF had a simple user cookie. I forgot to permit the GET on the new endpoint in the user permissions!!!

So stupid. @Clive: Thanks a lot for your help and sorry for that waste of time.
> 1 votes

---
Tags: javascript, 8
---


# Question
Title: How do I get the block title from the plugin implementing it?
I'm attempting to print the value of the title of the block in a block plugin.

```
public function build() {
    $build ='
        <div class="header-text">
            <'.$this->configuration['header-size-submit'].'>'.$this->title.'</'.$this->configuration['header-size-submit'].'>
        </div>
            ';
    return array(
        '#type' => 'text',
        '#markup' => $build,
        );
}

```

I attempted to get the value of the title by using

```
$this->title

```

But that did not work.

# Answer
> 2 votes
If your block plugin derives from the `BlockBase` class, `BlockBase::label()` returns the default title for the block, but the block title is set in `BlockBase::buildConfigurationForm()`.

```
  $form['label'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Title'),
    '#maxlength' => 255,
    '#default_value' => $this->label(),
    '#required' => TRUE,
  );
  $form['label_display'] = array(
    '#type' => 'checkbox',
    '#title' => $this->t('Display title'),
    '#default_value' => ($this->configuration['label_display'] === BlockInterface::BLOCK_LABEL_VISIBLE),
    '#return_value' => BlockInterface::BLOCK_LABEL_VISIBLE,
  );

```

So, your block class should check if `$this->configuration['label_display']` is set to `BlockInterface::BLOCK_LABEL_VISIBLE`; if it is, then use `$this->configuration['label']` for the title.

That said, I feel like the code you want to implement is actually not necessary, since the `BlockBase` class already takes care of showing the block title.

# Answer
> 2 votes
I was able to access the title by using

```
$this->configuration['label'];

```

---
Tags: 8, blocks
---


# Question
Title: Reinstall a module that has .yml file in config\install
A good enhancement in Drupal 8 is having list of yml file to import via installation in mymodule\_root\config\install, but this means I can not reinstall a module because the configuration settings already exist in the active configuration.

Actually the problem is when uninstalling the module: The imported configuration settings, imported during installation, aren't waived.

>

### Test scenario

Put this sample .yml file in yourmodule\_root\config\install\systme.site.yml.

```
name: 'Admissions at Adelaide'
mail: admin22@example.com
slogan: ''
page:
  403: ''
  404: ''
  front: caslogin
admin_compact_mode: false
weight_select_max: 100
langcode: en
default_langcode: en

```

# Answer
> 1 votes
See How to remove mymodule configurations on uninstall for a best-practice solution.

Basically, you can enforce the dependency on your module in your configuration files. So when the module is uninstalled, it's associated configuration will be uninstalled as well.

# Answer
> 0 votes
I'm quite sure it's **not** best practice, but you may try to add a yourmodule.install file and add something like this:

```
function yourmodule_migrate_uninstall() {

  // Delete Configuration generated at at activation.
  $dir = DRUPAL_ROOT . DIRECTORY_SEPARATOR . drupal_get_path('module', 'yourmodule') . DIRECTORY_SEPARATOR . 'config/install';
  $files = file_scan_directory($dir, '/.*\.yml$/');

  foreach ($files as $file) {
    db_delete('config')
      ->condition('name', $file->name)
      ->execute();
  }
}

```

Better answers's are welcome ;)

---
Tags: configuration, installation
---


# Question
Title: How to access fields for the Registrant settings (RNG)
At the RNG module there is a possibility at the Settings to add fields to the Registrant settings. As I understand the idea behind this is to add some fields to the registrant. I want to add a color to the registrant. But how can I access these fields? After I register for an event I can see my registrants on the Registration List, but I can't see the additional fields. I also have no idea how to add the content to these fields? Thanks

# Answer
> 1 votes
> But how can I access these fields?

As I'm sure you are aware, you can add the fields here at

`Administration > Configuration > RNG > Registrant settings > Manage fields` (/admin/config/rng/registrant/fields)

> I can see my registrants on the Registration List, but I can't see the additional fields.

The registration list page is simply a page provided by Views. There are a few ways to edit the view, including the quick edit button which appears on the right side of the page. On the view, there is already a pre-made relationship from `event entity -> registrant entities -> identity entity`. The fields added to any of the entity types, including the registrant entity type, should be automatically available by using the standard Views add field button.

> I also have no idea how to add the content to these fields?

Before of 1.2, there was no **edit registrant entity** form (or view registrant entity). Adding field values programmatically to registrant entities is also fully supported using the standard Drupal entity API.

I have created an issue for RNG which can be used to discuss this kind of feature: Add a way to view and edit registrants entities

---
Tags: entities, rng
---


# Question
Title: Use Arrays in Twig Template from Custom Block
I'm attempting to use arrays in a twig template from variables in a custom block.

In my custom block I have

```
public function build() {
    $query = \Drupal::entityQuery('node')
        ->condition('type','product')
        ->sort('created', 'DESC');

    $nids = $query->execute();
    $i = 0;

    foreach ($nids as $nid) {
        $node = NODE::load($nid);
            $imageurl[$i] = $node->get('field_product_page_display')->entity->getFileuri();
            $title[$i] = $node->get('field_title')->value;
            $imageurl[$i] = str_replace("public://", "", $imageurl[$i]);
            $i += 1;

        }
    return array(
        '#theme' => 'product_display',
        '#imageurl' => $imageurl,
        '#product_title' => $title,
        );
}

```

In my mymodule.module file I have

```
function mymodule_theme($existing, $type, $theme, $path){
    return array('header' =>
        array(
            'variables' => array(
                'header_title' => 'Default Title',
                'header_size' => 'h1',
                'text_align' => 'center',
                'uppercase' => FALSE,
                'grid_size' => 12,
                ),
            ),
        'product_display' =>
            array(
                'variables' => array(
                    '#imageurl' => [],
                    '#product_title' => [],
                    ),
                ),
        );
}

```

in my product\_display.html.twig file I have

```
{% for product in product_title %}
    {% for image in imageurl %}
         <div class="large-4 medium-3 column">
            <img src="./sites/default/files/{{ image }}">
                        <div class="product-title">
                            {{ product }}
                        </div>
                    </div>
    {% endfor %}
{% endfor %}

```

I know for sure that my custom block.php file is able to retrieve the data properly because using Debug() on $imageurl or $title displays all the information. However using Dump() in product-display.html.twig shows the #imageurl and #product\_title arrays as empty.

# Answer
> 5 votes
There is a syntax error in your hook\_theme. Use this instead:

```
function mymodule_theme($existing, $type, $theme, $path){
return array('header' =>
    array(
        'variables' => array(
            'header_title' => 'Default Title',
            'header_size' => 'h1',
            'text_align' => 'center',
            'uppercase' => FALSE,
            'grid_size' => 12,
            ),
        ),
    'product_display' =>
        array(
            'variables' => array(
                'imageurl' => [],
                'product_title' => [],
                ),
            ),
    );

```

}

The # sign in a render array is used to differenciate a key that has a meaning in the rendering versus an element. It shouldn't be included in the theme definition.

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


title: Adding localized js

text:
# Question
Title: Adding localized js
I've tried to re-phrase my question in my head a million times, as there seem to be quite a number of approaches and solutions, but finally decided to ask it in a very general way:

What is the best way to localize variables in **external** javascript, such as help hints, tooltips, and such?

Currently I have my js pasted raw into PHP Code, in as many instances as there are languages on the site, and I'm switching the variable set based on:

```
<?php
  global $language;
  $lang = $language->language;
?>

```

but I strongly dislike having a gazillion of copies of same text throughout the site. This is good for testing, but for production I want just one javascript file which I could call with parameters, something like:

```
<script src="myscript.js?hl=<?php print $lang?>"><script>

```

# Answer
> 7 votes
Drupal has an in-built mechanism to handle this sort of thing, the `Drupal.settings` javascript variable you'll see in the source code for any Drupal site.

Used in conjunction with `drupal_add_js()` in your PHP code you can easily pass variables to javascript, which will be available in your custom script files.

For example in a custom module you could add a settings variable like this:

```
global $language;
$mySettings = array('language' => $language->language);

drupal_add_js(array('mymodule' => $mySettings), 'setting');

```

Then in your javascript file you can pick up that variable like this:

```
(function($) {
  $(function() {
    var language = Drupal.settings.mymodule.language;
    if (language == 'en') {
      // etc
    }
  });
})(jQuery);

```

Using this method your template code can be a lot cleaner and you don't need to worry about passing URL variables to the javascript file, or building up the javascript in PHP any more.

# Answer
> 5 votes
If you're talking localization, there's also a t() version of Javascript in the form of Drupal.t(), e.g.

```
   $("#div").text(Drupal.t('Mouseover tooltip'));

```

Your script will need to be added by drupal\_add\_js().

See http://drupal.the-aim.be/drupal-translate-jquery for a bit more on it.

# Answer
> 1 votes
Instead of passing the language in a setting or parsing the URL you can also use this code to get the actual language of the site:

```
var lang = $('html').attr('lang');

```

This works as all themes should render (at least) this info:

```
<html class="" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">

```

References:

JAVASCRIPT get current language!!!

---
Tags: javascript, i18n-l10n
---


# Question
Title: How to move the Forena report parameters block further down and give it a separate heading?
Can the Forena parameters block be moved further down and given a separate heading?

The Forena Parameters block sits at the top of the page, but I would rather have it further down the page after some report headers, and with a different title like **Conditions** or **Settings**. I would also prefer it to be opened rather than collapsed the first time the report is opened. Is there some way to set this, preferably without editing the code for the module?

# Answer
> 1 votes
# Rendering of the report parameters input form

Forena's custom renderer `FrxParameterForm` allows you to customize various aspects of the rendering of the report parameters input form. More details about it can be found in the tutorial included with Forena, located at relative path `reports/help.renderers#frxparameterform`. Here is part of what it says:

> Use it on a `div` tag anywhere within the body part of your report to control various aspects of the rendering of the parameter form.

Here is a sample of how to use it within the body tag of your report:

```
<body>
  <div frx:renderer="FrxParameterForm" frx:title="Conditions or Settings"
       frx:collapsible="1" frx:collapsed="1"
       frx:submit="Label of the submit button" id="parmeter-form">
  <p>

  put your actual report parameters here ...

  </p>
  <p>{submit}</p>
  </div>
  <div>

  here goes the rest of your report specifications ...

  </div>
</body>

```

Some more details about the above example (also from the same documentation):

* **frx:title**: The title of the parameters field set.
* **frx:collapsible**: Indicate if the form should be collapsible or not:
    + set to "1" to make the parameter form collapsible.
    + set to "0" for a parameter form that cannot be collapsed.
* **frx:collapsed**: Indicate how a collapsible parameter form should be shown:
    + set to "1" for a collapsed form.
    + set to "0" for a not collapsed form. The default behavior is to expand the form only if no data was returned by the report.
* **frx:submit**: The label of the submit button.

# Theming the report parameters input form

For the actual positioning of the parameter form, I suggest you use a custom (new) CSS file, by adding 1 line to the "skin" used in your report (which is either the default skin, or your custom skin). To do so, just add a line that looks like so (name the CSS file whatever fits):

```
stylesheets[all][] = custom_forena_styling.css

```

Within that CSS file, you could (eg) add this CSS coding to make the parameter form be shown to the very right of your page (I prefer to do so by showing it "collapsed" as detailed above):

```
/* Apply some styling to the parameters form */

#parameters-wrapper fieldset.collapsed {
  float: right;
}

```

More details about "*Report Skins*" can be found in the tutorial included with Forena, located at relative path `/reports/help.skins`, or in the demo site. An example that uses these skins is to enable dataTables (to enhance the display of tabular reports).

# Summary

With that, it's up to your own imagination to make the parameter form of your report (or chart) fit your needs, ie:

* using the custom renderer options.
* add whatever xHTML tags you want.
* style it using your custom CSS.

Disclosure: I'm a co-maintainer of Forena.

---
Tags: 7, forena
---


# Question
Title: How do I set a block title to the title of a referenced node?
In Views 3, I have a block that is showing content from a particular Node ID. I'd like to have the title of that block set dynamically to what the referenced page's title is. I know this would be accomplished using Contextual Filters and that my display's title would be an argument, like %1 but I'm uncertain what the Contextual Filter settings should be. I'd rather not use PHP code if avoidable simply because I don't have the 'PHP Filter' module enabled on most sites I create.

Which settings should I use to make a block title the same as the title of a referenced node?

# Answer
In Views, with a block output & Content Entity Relationship set up, in 'Contextual Filters':

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED \- Override title (tick this & I used %1 with some text)

which offers "Override the view and other argument titles. Use "%1" for the first argument, "%2" for the second, etc."
> 1 votes

# Answer
You can't set the block title from within the view using contextual filters the way you are thinking, only the title of the view itself. On this page there is a similar goal and a few suggestions:

Dynamic block titles
> 0 votes

# Answer
I know this is old, but maybe it can help someone. Just put on the view title `[title]`, and add the field title to field list in view; then, select *Exclude from display*. Done!

>

>
> -1 votes

---
Tags: 7, views, blocks
---


# Question
Title: What does a value like node:{node_type} mean?
I'm trying to fully understand Drupal 8 routing. I understand the basics, no problem, but some of the finer details are still a mystery.

Here's the route for adding a node from the node module.

```
node.add:
  path: '/node/add/{node_type}'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE
    parameters:
      node_type:
        with_config_overrides: TRUE

```

I'm struggling with the line `_node_add_access: 'node:{node_type}'`.

I understand what the `_node_add_access` key does. It refers to a service with a tag of `applies_to: _node_add_access`. That is provided by the `NodeAddAccessCheck` class.

What does the `node:{node_type}` do? No amount of tracing through code has answered that for me. It looks to be a unique value for some purpose. Is it related to caching?

I haven't got to the options stuff yet.

Thanks

EDIT: I'm not sure if this should be an answer but these applies\_to requirements seem to be read in `Drupal\Core\Access\CheckProvider::applies` and the value (e.g. node:{node\_type}) doesn't seem to be used at all.

# Answer
That definition isn't about what is *passed* to NodeAddAccessCheck, that is solely defined by the slug definition in the path and the type hinted argument.

Instead, it is configuration for its implementation. Which it doesn't actually use. So yes, it is pointless. See `\Drupal\Core\Entity\EntityCreateAccessCheck` for an access check that actually uses that definition to dynamically get the value it wants from the route match parameters.

I suppose this initially used that and was switch to a different implementation, without removing the now unnecessary configuration.
> 3 votes

# Answer
`{node_type}` is a slug and is available as the `$node_type` param in `NodeAddAccessCheck::access()`

https://www.drupal.org/node/2186285
> 0 votes

---
Tags: 8, routes
---


# Question
Title: How to reference existing Paragraph entity?
I'm trying to create an entity reference field for existing paragraph, but can't seem to figure it out.

I've tried creating a normal entity reference field (content) but that only gives me the options to select from content types.

I've tried creating a paragraph field and using a entity reference view to display the results. (this displays a list of paragraph entity ids but when referencing one in a node it comes up with `There are no entities matching "(21)".`

How do I reference existing paragraph entities in a node?

# Answer
Re-using paragraphs is not supported/allowed. Each paragraph has a reference to the host entity it is being used in and only supports one such reference.

If you need re-usable content in paragraphs, you need to have another entity type or bundle that you reference from a paragraph type.
> 11 votes

---
Tags: 8, entities
---


title: How to cache a paged list?

text:
# Question
Title: How to cache a paged list?
I have a list which is built by consuming an API. The data that comes from response is not stored in Drupal which mean I am using views to create the list. The list is a paged one which shows 10 items at every page. How can cache each page of the list?

What I am thinking of is setting the cache name with a variable of the page.

```
\Drupal::cache()->set('cache_demo_page_'.$page, $posts, CacheBackendInterface::CACHE_PERMANENT);
```

This will lead to a lot of cache entries as there will be 100s of such pages in many lists across the site.

What should be the best way to do this?

# Answer
Yes, having hundreds of pages also results in hundreds of caches. Not just for your cache, but also for any block that varies per URL.

That's how it is, no way around it. Except not caching at all.

Note that with remote content, you need to think about cache invalidation (Well, you need to think about that anyway, but it's different with reomote content). You have two options:

* Use a short cache expiration time. That also helps with the amount of cache entries, as they will get deleted when they are expired
* Or you need to find a way to get notified when changes happen in the remote system or check for changes in a background process to invalidate your cache entries.
> 1 votes

---
Tags: 8, caching
---


# Question
Title: How to exclude nodes from a view if they appear on another view?
I have two views called '**slider**' and '**latest news**'.

The slider view lists 5 nodes with content type **news**, **article** and **blog post** and if a custom field is selected on this nodes.

The latest news list the 5 latest nodes with content type news.

## What I want to do is to exclude nodes from latest news view if they appear on the slider view.

If the slider view has only the news content type, it would be easy to exclude nodes by using the offset feature but because the slider view could have nodes from all these three content types and it's uncertain how many nodes come from each content type I couldn't solve my problem.

**How to exclude nodes from latest news view if they appear on the slider view?**

# Answer
> 1 votes
Try the Views Excluded Previous module:

> The Views exclude previous module provides a views filter that excludes nodes that have already been loaded/displayed on the current page.
>
> This is very useful when you have pages with several embedded views, and you want to make sure that a given node only appears once in the page.

# Answer
> 0 votes
**Step 1)** Add a new boolean type field to your **Article** content type.

**Step 2)** Type `Yes` for on value, `No` for off value

**Step 3)** Checkmark ☑ Use field label instead of "On Value" as label

**Step 4)** Go to your **Events and Blogpost** content types and add the boolean field using existing fields.

**Step 5)** Edit the 5 nodes you want to see on the slider and ☑ checkmark show on slider.

**Step 6)** Go to your **Slider View** and add a filter of Show on slider, and select `Yes`.

**Step 7)** Go to your **Latest News View** and a filter of Show on slider, and select `No`.

Once you have all of this setup. You will need to print your views programmatically on the front page template using this technique: Multiple Views on a page - How to exclude already shown nodes?

---
Tags: 7, views
---


# Question
Title: How to dynamically change the path to store commerce files depending on some product variables?
All my Drupal Commerce files are being saved in the same directory on the server.

I have a Commerce product variation of type of album. Each album contains multiple Commerce files (mp3’s, m4a’s). I want each album to have its files saved in a different directory depending on artist name and album name.

For example: `commerce_mp3s/artist_name/album_name/album_files*`

I tried looking in the DB where these Commerce files are referenced, table name being `field_data_commerce_file`, but file paths are not used there.

The worst case scenario would be to change the file path of the content type every time I add a new album, but that’s not a solution. This must be a common scenario.

How can I accomplish this?

# Answer
You need to use the Token with File (Field) Paths and Pathauto modules.

> **Note**: File (Field) Paths extends the token module by adding Node tokens, without this module, you will not be able to use the node fields as tokens.

Then edit your file field.

We then use Pathauto to fix names with spaces. Ex: If the album name is "Hello World" the path/folder name will change to /hello-world/
> 2 votes

---
Tags: commerce, files
---


# Question
Title: How to switch existing file field from public to private?
I have a Drupal 7 website with an existing *file field* set to store files in the public folder
(i.e. `sites/default/files`).

I need to switch this one field so that it stores files in the private folder. Because the field has already been set to public and there are a number of existing files in place - the *option to change the settings to private is not available* in the user interface. I was wondering if anyone has a way to make this change manually in the database.

# Answer
> 3 votes
I know this was asked a while ago, but posting this in case anyone else needs it:

https://gist.github.com/thsutton/6878688

This gist takes the steps from this comment on d.o. and makes it into a simple script: https://drupal.org/node/1806220#comment-6960906

Here's the steps from the linked comment:

1. backup your site and db
2. copy the table for your field (and the revisions table for the field) to make a backup (in my case i copied: field\_data\_field\_attachments to field\_data\_field\_attachments\_bk)
3. empty table field\_data\_field\_attachments
4. go to drupal and the option to change the file system should be available, so change it
5. copy all data from field\_data\_field\_attachments\_bk back to field\_data\_field\_attachments
6. go to drupal, select your content type, select your file field, in file path settings select retroactive update
7. click save and it will move all your files to the right place in file system and update your db to the new path

I ran through the script and field updates on several fields myself recently and it just works.

# Answer
> 1 votes
Use https://www.drupal.org/project/privatize, a drush extension to convert the files for you.

# Answer
> -1 votes
In the Home » Administration » Configuration » Media path
you should set your private file path to sites/default/private.
This will automatically give you an option for public or private files while editing fields settings.

Then you can check in field settings and select private file .

---
Tags: entities, database
---


# Question
Title: How do I enable Clean urls within a migrated site?
I am currently assisting a client with a Drupal 6 to 8 upgrade. After migrating a copy of the site into a development localhost environment. I noticed that I was not able to enable clean URLs. I have checked the `.htaccess` and found the following:

```
RewriteEngine on
RewriteBase /clientname
RewriteBase /
#Redirect /clientname

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

I have have checked other forums, and according to them the issue should be fixed. However, I am dealing with this same issue.

Any new advice would be much appreciated.

# Answer
Did you read this:

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

```

Actually, you should use the original D8 .htaccess cause there are some special rewrites for core and autoloader (and more).
> 0 votes

---
Tags: 8, migrations, uri
---


# Question
Title: How to implement custom theme functions (theme_textfield, theme_form_element) for some forms only?
How to implement custom theme functions like theme\_textfield or theme\_form\_element?

I know we can do it using hook\_theme\_registry\_alter:

```
/**
 * Implements hook_theme_registry_alter().
 */
function krown_admin_theme_registry_alter(&$theme_registry) {

  //Override some Drupal defaul theme functions

  $theme_registry['textfield']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['textfield']['function'] = 'krown_admin_theme_textfield';
  $theme_registry['textarea']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['textarea']['function'] = 'krown_admin_theme_textarea';
  $theme_registry['form_element']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['form_element']['function'] = 'krown_admin_theme_form_element';
  $theme_registry['form_element_label']['theme path'] = drupal_get_path('module', 'krown_admin');
  $theme_registry['form_element_label']['function'] = 'krown_admin_theme_form_element_label';

}

```

The problem with this approach, is that the custom functions are applied on all website. I just want to apply them for some forms or for a specific theme.

# Answer
> 1 votes
Those theme functions don't get a reference to the form where the element is used. Therefore, they cannot be used to alter an element for a single form.

Every form element accepts #theme, so you can alter the #theme function used for those form fields in a single form. This is what Drupal does in `node_filter_form()`.

```
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'exposed_filters__node',
  );

```

`theme_exposed_filters()` then does its job.

```
  $form = $variables['form'];
  $output = '';

  if (isset($form['current'])) {
    $items = array();
    foreach (element_children($form['current']) as $key) {
      $items[] = drupal_render($form['current'][$key]);
    }
    $output .= theme('item_list', array('items' => $items, 'attributes' => array('class' => array('clearfix', 'current-filters'))));
  }

  $output .= drupal_render_children($form);

  return '<div class="exposed-filters">' . $output . '</div>';

```

Unfortunately, this doesn't work with `theme_form_element()` or `theme_form_element_label()`.

---
Tags: theming, forms
---


# Question
Title: Include a link of node with text in block body
How can I include a link to a particular page in the block body? I don't want to create a custom block.

# Answer
check the text format in block body changes it to full html then include link . it will working fine check this screenshot http://prntscr.com/bq9okc
> 0 votes

# Answer
Just use create a link from the editor, and give the node ID of the node.
> 0 votes

---
Tags: 8, blocks, configuration
---


# Question
Title: Teaser of full html pages without layout
I have a block/view that shows teasers of the latest 3 articles.. This articles are full html, it contains layout (build with a WYSIWYG)..

On the homepage, I create a block that shows the latest 3 articles.. I can give it CSS-layout..

But because it's build with the WYSIWYG, there are extra html-tags (span, a, p, ...) in the teaser, which can be different every time. The problem is that it overwrites the default layout for the teasers..

I just want to keep the clean text on the frontpage block, and full-html on the detail page. How can I manage it?

Normally I should use strip\_tags(); in PHP to remove html.. But how can I do it only for that specific block?

# Answer
Add the body field and trim it.

Now in your web directory, go to `/sites/all/themes/yourtheme/` folder and in **template.php** add the following code:

```
function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $vars['fields']['body']->content = strip_tags($vars['fields']['body']->content);
  }

}

```
* replace **yourtheme** with the actual name of your theme
* replace **view\_name** with the name of your view.
* replace **block\_1** with the machine name of your view. If yours happens to be block\_1 then leave it the same.

In Drupal, clear/flush your cache to see the changes.

Then add the other fields you want on your view, title, post date? comment link? etc... basically you create your own teaser.

**PS**: You can add classes to your fields, if you need to use css on them.
> 2 votes

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


# Question
Title: Views math expression or Computed field to find date difference in views
I have two content type, Bill (Type1) and Cash Receipts (Type2), Type2 referencing Type1 when cash is received.

In Type1 I have date field called (Bill Issue date), and Type2 I have date field cash receipt date.

So I want to calculate, different between those two dates. I was trying by creating views with two date (by entity reference relationship), then subtract two filed with math expression field, but it return zero.

Actually, I have no idea whether I was wrong or Its not possible to calculate different between dates with views math expression field?

I think, it can be done with Computed Field, I did one within same content type, but I don’t know how to access a field from different content type, please help.

Code that I was used to calculate date for same content type, but how I can access a field from other content type?

If the Machine name of your date-field is 'field\_example\_date', then the Computed Code (PHP) would be

```
$startdate = $entity->field_example_date['und'][0]['value']; // Value of start-date
$enddate = $entity->field_example_date['und'][0]['value2']; // Value of end-date

$datediff = strtotime($enddate) - strtotime($startdate);
/* The PHP Function STRTOTIME parses the english textual datetime description
 * into a Unix timestamp
 */

$num_leaves = $datediff/(60*60*24);
/* Since we need the number of days IN-BETWEEN,
 * we divide the resultant difference by 60*60*24 .
 *
 * Incase of counting no.of days "FROM" to "TO" days, add 1 to the above result.
 * $num_leaves = $datediff/(60*60*24) + 1;
 */

 $entity_field[0]['value'] = $num_leaves;

The Display Code (PHP) will have

$display_output = $entity_field_item['value'];

```

# Answer
You can achieve this use a template file, since you can use PHP inside templates in Drupal 7

In your view

Now, add both of your date fields and do this to each of them

In your web directory, go to **/sites/all/themes/\[yourtheme\]/templates** folder

Create a file named views-view-fields--**\[view-name\]**--**\[machine-name\]**.tpl.php

EX: `views-view-fields--hello-world--block-1.tpl.php`

Inside the template file put:

```
<?php

$date1 = new DateTime('$fields["field_invoice_issue_date"]->content');
$date2 = new DateTime('$fields["field_payment_receipt_date"]->content');
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

?>

```

Remember to flush/clear the cache to see changes.
> 0 votes

---
Tags: 7, views, entities
---


# Question
Title: Drupal 8 page manager and panels contextual filters for views_block
I'm working with Drupal 8(first project with 8) and trying to build page (via page manager) with taxonomy tid argument.

As a display variant I use panels and inside of panel I put block, generated by views and this views\_block have contextual filter.

I haven't found the way for how to attach my contextual filter to views\_block plugin from panel or associate context to anywhere.

From debug session I know what panels have my argument as a context. But how to pass it to views\_block plugin inside of panel?

Thank you for any help and information. I'm ready to digg inside of code(and contribute also, if needed) to solve this.

# Answer
Alternative, you can use Views to pick up the tax term id's

If your node has multiple tax terms, you need to allow multiple values for your contextual filter
> 1 votes

---
Tags: 8, panels
---


title: 404 Could not find the controller

text:
# Question
Title: 404 Could not find the controller
I have a strange problem. This is my code:

```
function bd7_services_services_resources() {
  return array(
      'get' => array(
        'index' => array(
          'help' => 'Ritorna le immagini inserite.',
          'callback' => 'bd7_services_get_immagini',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
        ),

          'actions' => array (
            'immagini' =>
              array(
                'help' => 'Ritorna le immagini inserite.',
                'callback' => 'bd7_services_get_immagini',
                'access callback' => 'user_access',
                'access arguments' => array('access content'),
                'access arguments append' => FALSE,
              ),
          ),
          'operations' => array(
              // Define the index callback for a GET to /cart.
            'immagini2' =>
              array(
                'help' => 'Ritorna le immagini inserite.',
                'callback' => 'bd7_services_get_immagini',
                'access callback' => 'user_access',
                'access arguments' => array('access content'),
                'access arguments append' => FALSE,
              ),
          ),

      )

  );
}

```

If I call "rest/get" all works.

If I call "rest/get/immagini" I receive "404 Not found : Could not find the controller."

If I call "rest/get/immagini2" I receive "404 Not found : Could not find the controller."

Where is my error ? "rest" is my "Path to endpoint".

Thanks.

# Answer
I have also create custom resource using services module like:

```
function vintervals_resource() {
  $api = array(
'registration' => array( // Resource name
'operations' => array(
    'create' => array(
    'help' => 'Ticket System',
    'file' => array(
        'type' => 'inc',
        'module' => 'My_module_name',
        'name' => 'includes/My_module_name.services',
    ),
    'callback' => 'My_custom_callback', // callback
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'access arguments append' => FALSE,
    'args' => array(
        array(
        'name' => 'body', // parameter name in callback
        'type' => 'string',
        'description' => 'Function to perform',
        'source' => 'data',
        'optional' => FALSE,
        'default' => '0',
        ),
    ),
    ),
    ),
)
);
return $api;
}
   // callback
 function My_custom_callback($body)
 {
      // Your work here..
      $json_array = array($body);
      $json = json_encode($json_array);
      $body_Array = json_decode($json);
      $applicationId = $body_Array[0]->appno;
      $emailid = $body_Array[0]->emailid;
      $mobileNo = $body_Array[0]->mobno;
      $password = $body_Array[0]->userpwd;
      $returnArray = array('status'=>FALSE,'application_status'=>-1);
      return $returnArray;
 }

```

URL of my web service call is :

My domain + My endpoint + resourcename

"mydomain.com"+"api/ticketsystem"+"registration"

But it will not working directly in the browser. For this I have sent post request to server with parameters and receive it in my callback then it's working perfectly.
> 1 votes

---
Tags: services, 8
---


# Question
Title: Print the main menu in overridden node page
In development site. I am using sitemap page so i need to print the all main menu and submenu in that page. I am using this code, but it is not working.

```
$main_menu = menu_navigation_links('menu-main-page');
echo '<pre>main menu';print_r($main_menu);

```

How can I achieve it?

# Answer
If you want to render the menu for sitemap purpose, better to use the "Sitemap" module

Configuration page from this link

```
admin/config/search/sitemap

```

You can see the below screen on configuration page,

Just check the menu, which you want to display in sitemap.

After this you can access your page with `/sitemap` url and you can see your menu there on that page.
> 1 votes

# Answer
if drupal 7 try this

```
 <?php print theme('links__system_main_menu', array(
    'links' => $main_menu,
 'attributes' => array(
     'id' => 'menu',
    ),
    'heading' => array(
  'text' => t('Main menu'),
     'level' => 'h2',
   'class' => array(
    'element-invisible',
       ),
     ),
     ));
?>

```
> 0 votes

# Answer
The following code works on Drupal 7.

```
$menu = menu_tree('main-menu');
$menuhtml = drupal_render($menu);
print_r($menuhtml);

```
> 0 votes

---
Tags: navigation
---


# Question
Title: How to use conditions on a COUNT Expression?
I am creating an appointment booking module for my drupal 8 site, which is 99% complete, but I am one or two lines of code away from completing my module. The problem is using a database condition on an Count Expression that has been produced after the database has executed.

This is the code I have so far:

```
public static function dateavailabilty() {
    $select = db_select('bookingdateandtime', 'e');
    $select->addField('e', 'datecode');
    $select->groupBy("e.datecode");
    $select->addExpression("COUNT(e.datecode)", 'count');
    $select->condition('count', 2, '>');

    $entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

return $entries;}

```

But the page returns "The website encountered an unexpected error. Please try again later."

The following error report is produce in the Drupal Admin Error Log Messages:

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42S22\]: Column not found: 1054 Champ 'count' inconnu dans where clause: SELECT e.datecode AS datecode, COUNT(e.datecode) AS count FROM {bookingdateandtime} e WHERE (count \> :db\_condition\_placeholder\_0) GROUP BY e.datecode; Array ( \[:db\_condition\_placeholder\_0\] =\> 2 ) in Drupal\booking\bookingDTdatabase::dateavail() (line 51 of C:\wamp\www\modules\booking\src\bookingDTdatabase.php).

I need to use a condition to only produce results that has a count of more than 2. Obviously, if I cancel out this line "$select-\>condition('count', 2, '\>');", drupal returns everything perfectly. So, using the condition doesn't work on data that has been added after execution.

How do I go about using the correct condition to apply to the Expression?

Many Thanks for reading and helping.

# Answer
Conditions on aggregates are addressed with `HAVING` in MySQL, so something similar to:

```
$select->having('count > :cnt', [':cnt' => 2]);

```
> 5 votes

---
Tags: 8, database
---


# Question
Title: How to implement quotation replies on Commerce orders by multiple users?
Commerce order will have 0 price when being placed, Once the order is placed all the users of specific role will get notification(this is working) and should be able to reply to that order(I am making a custom module and view for this) with their own price for that order. There will be multiple fields data to reply like price, qty, destination, etc.

I don't want to create a new order or order revision.I want to be able to somehow add all quotation data to that order for each user.I have seen some quotation like modules but they do not do what I need.

My question is where to save all those fields and data?How to relate it with that order?

How do I achieve that?

# Answer
> 2 votes
Use the Flag module to allow those users of a specific role to flag orders.

When configuring the (non-global) flag(s), attach appropriate fields to them, as described in Attaching fields to flags. These fields could perfectly match with the "*multiple fields data to reply like price, qty, destination, etc.*" (as in your question).

If needed, use the Rules module to add all sorts of additional (custom) logic to the mix, eg:

* only allow such flagging to happen within selected timeframes.
* send (eMail) notifications to appropriate users.
* perform field level validations (whatever may seem to be needed).
* ...

---
Tags: 7, commerce
---


# Question
Title: Find an entity that most recently referenced a particular entity
### Scenario

A content type - *Wardrobe* references another content type *Product* via **Entity Reference** field - *field\_product*.

### Problem Statement

I need to find the Wardrobe content which most recently referenced **a particular** Product content.

### Question

Could this be accomplished through **Views** alone (by playing with available options in views) or do I need to write a **customised query in php**? I cannot figure out the way with either of these options :/

### P.S.

Alternative suggestions are welcome :)

# Answer
I am afraid, it's impossible to achieve what you want with a simple entity reference field alone.

The problem is that while the wardobe content saves the date of its *most recent edit*, you can not tell which (if any) product was added during that editing session (unless you use versioning consistently and compare the products saved in different versions manually). To complicate things further, an entity only saves the date of its most recent edit (saving over the previous edit date) which makes it very inadequate to track when a particular product was added to a wardrobe.

The biggest issue you face is that the information you need (when an item is added) is not directly tracked at all. While you could probably figure it out if you use versioning, this data would still be very hard to access in views.

What you can do is make a list of wardobes a particular item is part of and order them by most recently updated wardobe (though this most recent edit may or may not have actually added that product). If that's not what you want you need to find a way to track the missing date information yourself.

Possible starting points which come to mind:

* Custom compound field with joined reference + date fields: https://www.phase2technology.com/blog/compound-fields-in-drupal-7/
* Custom module which adds a db table with columns for wardrobe id, product id and date. You can access these data on node save, during which you can still access the old version of the wardobe, check which (if any) products were added, and add those entires to the db.
> 3 votes

---
Tags: 7, views, database, entities
---


title: A lot of redirect for a simple page

text:
# Question
Title: A lot of redirect for a simple page
While working on the SEO of a site, we noticed that, just for the homepage we have 5 redirects (301 and 302).

http://mydomain.be = 301 =\> https://mydomain.be (well, that one, OK)

https://mydomain.be = 301 =\> https://mydomain.be/en (EN is the default language)

https://mydomain.be/en = 302 =\> https://mydomain.be/en/node/42

https://mydomain.be/en/node/42 = 301 =\> https://mydomain.be/fr/the-clean-url (why does the language detection only appears here? )

https://mydomain.be/fr/the-clean-url = 301 =\> https://mydomain.be/fr (because this is the homepage)

That's quite a lot of redirect jus for one page... Is there any way to reduce that?

Like don't go to the default language and directly go to the good language? Or don't redirect to the clean URL if this is juste the homepage?

# Answer
.htaccess file using redirect.

**IfModule mod\_rewrite.c**

`Redirect 301 /fromurl /tourl`

Example:

`Redirect 301 /http://www.example.com /https://www.example.com`

Try it.
> 0 votes

# Answer
For the very first redirect, from http to https, one mitigation is to use the HTTP Strict Transport Security (HSTS) response header. A way to do that in Drupal is the Seckit module. This header will help browsers to know that when they visit your site they should always use https. It would also be good to use https in links to your site wherever possible.

The rest of the redirects will probably need to be resolved with individual module/core issue queues. My guess is that the Redirect module is involved. I suggest using the Devel module's "show redirect page" feature and looking for calls to drupal\_goto so you can understand why/where the redirects are happening and then investigate how to optimize them.
> 0 votes

---
Tags: redirection
---


# Question
Title: Is it possible to hide fields on node edit form or split node edit form in two screens?
I have a content type cFoo. This content type has e.g 10 fields.

I want:

1. user has page node/cfooxx/edit/screen1 and sees only fields 1,2,3,4,5
2. user has page node/cfooxx/edit/screen2 and sees only fields 6,7,8
3. user has no access to fields 9,10

I did a lot of reseach on this but it is not clear for me.

* how to get the splitting of the standaard node/xx/edit url to edit/screen1 and edit/screen2?
* On the front I use display suite so I can manage a display. Is there a module which can do this with edit forms as well?
* If I use css, still fields of screen1 are processed in background of screen2 and the other way around. I do not want this because of possible errors in form validation. But suppose i need to do this... then the /node/cFooxx/edit url containts fields 1/2/3/4/5/6/7/8. So how to decide which css to apply when entering /node/cFooxx/edit?
* If I use hook\_form\_alter how to identify screen1 and screen2?
* Point 3 I can solve with field permissions module

# Answer
You could use different modes on the two routes. Go to `/admin/structure/types/manage/fooxx/form-display` and there you can configure which fields you want see on which mode.

You can add new modes here: `/admin/structure/display-modes`

> **Note**: While Drupal 8 core already comes with "form modes", in Drupal 7 you need to install the flexiform module.
> 1 votes

# Answer
@Sanjay's solution is the only way I can think of. I had done the similar thing before for a similar situation as question stated.

I would separate the logic into 2 different functions.

```
function mymodule_form_cfooxx_node_form_alter(&$form, &$form_state) {

  switch (arg(3) {
    case "screen1":
      _mymodule_form_screen_1($form, $form_state);
      break;
    case "screen2":
      _mymodule_form_screen_2($form, $form_state);
  }

}

function _mymodule_form_screen_1(&$form, &$form_state) {
  ...
}

function _mymodule_form_screen_2(&$form, &$form_state) {
  ...
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Is it possible to disable cache on certain fields?
I am working on a site where i'm implementing my own cookie bar module. For this module i have made it possible to write something in the CKeditor like:

Where everything between the {cookie} tags is only visible when cookies are accepted. This works fine on my dev environment, but when I deployed it to the test server where cache is enabled it won't show any change when you enable/disable cookies because the page is already cached.

Is there a way to disable cache on the text field or better yet, everything between the cookie tag?

# Answer
You need to adjust the cache context of the node.

If the cookie is a drupal session, use the predefined cache context for this:

```
$build['#cache']['contexts'][] = 'session.exists';

```

If you target another cookie, that drupal is not aware of, you would need to create your own context, more info:

https://www.drupal.org/developing/api/8/cache/contexts
> 0 votes

---
Tags: 8, caching
---


title: Strange behavior with title field

text:
# Question
Title: Strange behavior with title field
I have a strange behavior (or at least this is what I think) I have two form elements. Both are required, in the first (First Name) I want to have a required field so I use `'#required' => TRUE` and `'#required' => TRUE` in the second I don't use this properties to says that the field is required, I just add this line to the title `'<span class="form-required" title="' . t('This field is required.') . '">*</span>'`. The problem is that the output of the first element is `"First name "` (with space at the end) and in the second element the output is `"Last name"` (without space at the end). See the code and the picture with the output code.

Is this a normal behavior or I missing something here?

```
  $form['general']['group-1']['prenom'] = array(
    '#prefix' => '<div class="item">',
    '#title' => t('First name'),
    '#id' => 'cf-1',
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' => array('required' => 'required'),
    '#suffix' => '</div>',
  );

  $form['general']['group-1']['nom'] = array(
    '#prefix' => '<div class="item">',
    '#title' => t('Last name') . '<span class="form-required" title="' . t('This field is required.') . '">*</span>',
    '#id' => 'cf-2',
    '#type' => 'textfield',
    '#suffix' => '</div>',
  );

```

**The HTML code:**

# Answer
Works as designed imho.

The markup of the first is generated by the form element/Drupal. By default Drupal has a space between the field title and the asterisk. That's just how it was designed.

The second time you tell the form what to add - exactly what to add. Drupal wont add a space for you, as you may not always want a space between your custom wrapper and the title. (In most cases you probably don't.)

If it is important to remove the space you can overwrite `theme_form_element()` in your theme. Check the mid to late replies (starting with kkatusic) in this thread: How to remove asterisks from required fields?

Is there a reason why you would want to mark a field required if it isn't a required field?
> 3 votes

---
Tags: 7, forms
---


title: Behavior for displaying map doesn't run

text:
# Question
Title: Behavior for displaying map doesn't run
I'm trying to create a pretty straightforward page with a Google map that I need to customize, but the code in the behavior isn't being run for some reason. Here's the code:

```
/**
 * Implementation of hook_theme
 */
function mymodule_theme() {
  return array(
    'affiliates_map' => array(
      'template' => 'affiliates-map',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'render element' => 'content',
     )
  );
}

/*
 * Page callback for map page.
 */
function mymodule_search_map() {
  drupal_add_css('
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }', array('group' => CSS_DEFAULT, 'type' => 'inline'));

  $path = drupal_get_path('module', 'mymodule');
  $gmap_api_key = variable_get('affiliates_gmap_api_key', '');
  drupal_add_js('//maps.google.com/maps/api/js?v=3&key=' . $gmap_api_key . '&callback=initMap',  array('type' => 'external'));
  drupal_add_js($path . '/js/mymodule.js', array('type' => 'file', 'weight' => 6, 'scope' => 'footer'));

  $output = theme('affiliates_map');

  return $output;
}

```

Here's my theme template.

```
<?php
/**
 * @file
 *   This template handles the display of the affiliates map.
 */
?>

<h2>Map content goes here</h2>

<div id="naa-map"></div>

```

and the js file

```
(function($) {
  Drupal.behaviors.affiliatesMap = {
    attach: function (context, settings) {
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('naa-map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 14
        });
      }
    }
  };
}(jQuery));

```

My console is giving me an error about initMap() not being found, and when I put a breakpoint in the behavior in initMap, it doesn't get hit. What am I doing wrong that it's not finding the behavior code? I've mimicked the Location Map module, and it works fine, so I'm not sure where I went wrong.

Thanks.

# Answer
> 1 votes
The issue ended up being my CSS. I was using styles from the sample page that had a height of 100%. Once I added some height and width to my naa-map div, my map showed up fine.

# Answer
> 0 votes
I think you should not declare initMap inside of the anonymous attachment - cause it's not visible outsinde. Try it like

```
(function($) {
  Drupal.behaviors.affiliatesMap = {
    attach: function (context, settings) {
      function initMap();

    }
  };
}(jQuery));

var map;

function initMap() {
    map = new google.maps.Map(document.getElementById('naa-map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 14
    });
}

```

But I think it's anyway not so nice with that global space "var map".

---
Tags: javascript, google-maps
---


# Question
Title: Guzzle httpClient Drupal Core throwing cURL error 28 Operation timed out
I have been loading the httpClient Core Service in a drupal 8 site. The service class works just fine when the request doesn't take too long from the API. It seems that if the request takes any longer than about 20-30 seconds the site throws a cURL response error 28 saying

```
GuzzleHttp\Exception\ConnectException: cURL error 28: Operation timed out  after 30000 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in GuzzleHttp\Handler\CurlFactory::createRejection() (line 186 of ../vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php).

```

After a bit of poking around online I saw some reference to the fact that the "CURLOPT\_TIMEOUT\_MS" error doesn't work with all versions of php and they suggest to replace the reference to "CURLOPT\_TIMEOUT\_MS" to "CURLOPT\_TIMEOUT" same for "CURLOPT\_CONNECTTIMEOUT\_MS".

In the above file with the error I found that in lines 374-380 which read the following

```
if (isset($options['timeout'])) {
  $conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
}
if (isset($options['connect_timeout'])) {
   $conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
}

```

if it's changed to the following

```
if (isset($options['timeout'])) {
    $conf[CURLOPT_TIMEOUT] = $options['timeout'] * 1000;
}
if (isset($options['connect_timeout'])) {
   $conf[CURLOPT_CONNECTTIMEOUT] = $options['connect_timeout'] * 1000;
}

```

removing the "\_MS" then the site doesn't throw any errors.

Is this an error in the core code? Is this issue possibly related and can it be fixed with the patches attached to this d.o issue? Also please see this comment on that issue with reference to what I mentioned above.

Any suggestions or direction on this would be greatly appreciated!

# Answer
As @cilefen suggested in his comments my problem was related to the timeout value that was being set in the calling code rather then an error with an undefined constant. I had fixed the error in my particular situation by adjusting the timeout value in my custom code that was making the API call with the following (600 is an example).

```
$request = $client->post($url, [
  'timeout' => 600,
  'json' => [array(...)],
]);

```
> 3 votes

---
Tags: 8, http-request
---


# Question
Title: Add user points to author for every up vote received to content using Rate module
I saw the post Add user points for every upvote But that was for rewarding the voter, I want to reward the author like Reddit karma. Does anyone know how to do this with Rules? Vote integration for rules is installed of course

# Answer
I recommend to go for a combination of these often used modules to add (or subtract) user points when some node is voted up (or down):

It's also the approach used in the Answers module (disclosure: I'm a co-maintainer of it), i.e. within its submodule "Answers Userpoints". If you agree, read on ...

# Required Rules

To handle all variations of voting, you need 4 rules (only!), which cover these 4 cases:

* a node is upvoted.
* an upvote for a node is canceled (= no longer upvoted).
* a node is downvoted.
* a downvote for a node is canceled (= no longer downvoted).

Below are the required rules, for each of these cases (use the Rules UI to import them in your own site, after you enabled the required modules mentioned above). These rules are enhanced versions of the rules included in the 7.x-4.0-rc2 version of Answers (and are expected to be committed to its dev version also). They use a content type with machine name `answers_question` (adapt this name to fit your own machine name).

Have a close look at how user points are added (or subtracted), and also who gains (or looses) those points. Obviously, then actual amounts of userpoints can be adapted in those rules to fit your own needs.

### Upvote a node

The rule below will grant +5 user points for an upvote (to the author of the node):

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

```

### Cancel the upvote a node

The rule below will grant -5 (= remove +5) user points for a cancelled upvote (to the author of the node):

```
{ "rules_voteup_question_cancel" : {
    "LABEL" : "voteup_question_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-5",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Unupvote [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionUpvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

### Downvote a node

The rule below will subtract -2 (grant -2) user points for a downvote (to the author of the node) ... **AND** also -1 user point for the voter:

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

```

### Cancel the downvote a node

The rule below will grant +2 (= remove -2) user points for a cancelled downvote (to the author of the node) ... **AND** also +1 user point for the voter:

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

```
> 1 votes

---
Tags: 7, rules, rating, userpoints
---


# Question
Title: ERROR: MAIL not accepted from server: 530 Authentication required , SMTP Authentication
I used SMTP Authentication Support Module to send the email. I also added my authentication. But still got this error:

```
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "220 email-smtp.amazonaws.com ESMTP SimpleEmailService-1488596457 6vQ6zwf88YaT38JwrmH9 "
SMTP -> get_lines(): $data is "220 email-smtp.amazonaws.com ESMTP SimpleEmailService-1488596457 6vQ6zwf88YaT38JwrmH9 "
SMTP -> FROM SERVER:220 email-smtp.amazonaws.com ESMTP SimpleEmailService-1488596457 6vQ6zwf88YaT38JwrmH9
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "250-email-smtp.amazonaws.com "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com "
SMTP -> get_lines(): $str is "250-8BITMIME "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME "
SMTP -> get_lines(): $str is "250-SIZE 10485760 "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 "
SMTP -> get_lines(): $str is "250-STARTTLS "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS "
SMTP -> get_lines(): $str is "250-AUTH PLAIN LOGIN "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN "
SMTP -> get_lines(): $str is "250 Ok "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok "
SMTP -> FROM SERVER: 250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "220 Ready to start TLS "
SMTP -> get_lines(): $data is "220 Ready to start TLS "
SMTP -> FROM SERVER:220 Ready to start TLS
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "250-email-smtp.amazonaws.com "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com "
SMTP -> get_lines(): $str is "250-8BITMIME "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME "
SMTP -> get_lines(): $str is "250-SIZE 10485760 "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 "
SMTP -> get_lines(): $str is "250-STARTTLS "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS "
SMTP -> get_lines(): $str is "250-AUTH PLAIN LOGIN "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN "
SMTP -> get_lines(): $data was "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN "
SMTP -> get_lines(): $str is "250 Ok "
SMTP -> get_lines(): $data is "250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok "
SMTP -> FROM SERVER: 250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-STARTTLS 250-AUTH PLAIN LOGIN 250 Ok
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "530 Authentication required "
SMTP -> get_lines(): $data is "530 Authentication required "
SMTP -> FROM SERVER:530 Authentication required
SMTP -> ERROR: MAIL not accepted from server: 530 Authentication required
The following From address failed: sales@test.com

```

Does anyone know what's going on here? Why did I get "530" error?

# Answer
> 0 votes
I figured out. I used a wrong password for Authentication. I create a new ses authentication credentials in AWS and the problem solved.

Thank you.

---
Tags: 7, debugging
---