# Question
Title: Problem with storing values in multiple textboxes
I'm having problem while storing values in multiple text-boxes, its stores value only in 1st text-box, here i'm using following JSON format of drupal 7 services.

```
"field_raoster_travel_time":{"und":[{"value":"8"},{"value":"81"}]}

```

( Note : I have set "Number of values" : "Unlimited" for text-box )

# Answer
When a field is set to `Unlimited values`, Drupal Services does not yet properly support them. There is an open issue here, and a patch in progress that I've used multiple times to get around this limitation. Grab the latest development version of Drupal Services 7.x-3.x and apply the patch mentioned above, and that should fix it.
> 1 votes

---
Tags: 7, services
---


# Question
Title: How to schedule a Rules component at the end of the month?
The users on my website can flag articles with Flag. I want them to be able to do this exactly once every month, but they do not have permission to unflag content. Therefore, my plan is to create a Rule that triggers when an article is flagged and that schedules a Rules component that takes care of the unflagging.

How can I schedule this component at the end of the month, i.e. which value should I add in the field *Scheduled evaluation date* of the action *Schedule component evaluation*?

# Answer
Introducing `last day of 23:59` works for me (`last day of` is the last day of the current month, and `23:59` just before the day ends). You can see the full reference of DateTime relative formats here: http://php.net/manual/en/datetime.formats.relative.php

In general, you can pass anything recognised by `strtotime()` as the scheduling date.
> 2 votes

# Answer
Your question seems a variation of "Schedule a mail on the 1st day of the following month", which has an accepted answer like so:

> Try **"first day of +1 month"** as your scheduled date.

With that, you may get it to work by using something like **"last day of +0 month"** as your scheduled date, or maybe simply **"last day of month"**.

Another approach (plan b ?) might be to try to use the "***Day of the month***" Rules Condition that comes with the Rules Ones per Day module. Though in that case you have to specify an integer for the `monthday` (between 1 and 31). So to make that work for each month (with 31, 30, 29 or 28 days) you might end up with pretty complicated Rules logic (possibly combined with the Conditional Rules module to consolidate it all in a single rule). If however it would be acceptable for your case, I'd rather use "1st day of the month" (= 1 day later), which would avoid such complicated rule.
> 1 votes

---
Tags: 7, rules, flags
---


# Question
Title: How to use Rules to perform a monthtly reset of a field for all users accounts?
Once a month I would like to reset a field on all users accounts to 0.

At the moment I have a horrible way of doing it. Each time a user logs in the data is scheduled to be changed only for that user. This is done through a rule (using the Rules module) which whenever a user logs in runs 'Schedule component evaluation' with a data selector of `site:current-user` and a date of the first of the month. The component that the rule calls 'set a data value' of 0. This is obviously not an efficient way of handling this. However it does work.

Ideally I would like to have a rule that runs occasionally, I could use when cron is run. This rule would schedule setting the data value for all users of the site. The problem is that I don't seem to have a data selector of 'all users' to pass to the component.

Am I missing something really obvious here?

# Answer
> 0 votes
You can make a small module for this to write some code using hook\_cron().

Inside hook function you can write query to collect all the user ID & update one field value in loop.

Then use Elsia Cron to schedule your made cron function.

# Answer
> 0 votes
If you don't have "***... a data selector of 'all users' ...***" in your rule (as in your question), then a possible solution is to make one available in an appropriately triggered Rules Event, as further detailed below.

### Step 1: Trigger a monthly rule

Create a rule using the Rules Once per Day module to actually trigger a rule once a ***month*** (not ***day***!). And add a Rules Condition "***Day of the month***" (which comes with this module also). Further configure this Rules Condition with an actual "\*Day of month\** (an integer between 1 and 31) to actually fit your needs. E.g.: if you specify `1` as your *Day of month*, this rule will be triggered on the 1st of every month.

As an example, have a look at this simplistic rule (in Rules export format):

```
{ "rules_monthly_email_reminder_to_admin_account" : {
    "LABEL" : "Monthly eMail reminder to admin account",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_onceperday", "rules" ],
    "ON" : { "once_per_day" : [] },
    "IF" : [
      { "rules_onceperday_condition_dayofmonth" : { "comparison" : "==", "monthday" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "Time for the monthly operations on the 1st of every month",
          "message" : "It\u0027s the 1st day of the month again, time for the monthly operations ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

All this rule does, is to send an eMail to the site admin, on the 1st of every month, with a subject like "*Time for the monthly operations on the 1st of every month*" (and some eMail body that goes with it).

If you have the Rules UI enabled, and after you also enabled the Rules Ones per Day module, you should be able to just import the above rule in your own site.

### Step 2: Create a view of all users to be processed

Create a view (using the Views module) of those users for which you want to "*reset a field to 0*" (as in your question).

### Step 3: Make the monthly rule process all users

After you created such view, you can ***process the results of a VBO enabled view via Rules***, by replacing the Rules Action in the rule from Step 1 like so:

* Load the VBO list of the users in your View.
* Add a loop to perform a Rules Action to "*reset a field to 0*" (as in your question), for each user contained in your Views result.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

---
Tags: 7, users, rules
---


# Question
Title: how to show the foreign characters in tpl.php file
I would like to set my website as Multilingual. I typed some Korean words (eg."한국어") in tpl.php file, but when I check my webpage, it shows me some question marks (eg."???").
Here is the code:

```
 <div class="row">
     <h2>한국어</h2>
     <p></p>
 </div>

```

I think it might be somewhere I need to set first. Does anyone know about this? I really appreciate anyone's help.

# Answer
> 1 votes
Make sure that your theme is using the utf-8 character set. You can see this in the headers of the page:

```
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

```

You'll also want to make sure that the web server you are using to serve the page is sending the correct HTTP header as the response (you can use the web developer inspector tool in either Firefox or Chrome to see this). It should be:

```
Content Type: "text/html; charset=utf-8"

```

If your browser is set to use a different content-type encoding this might also explain the difference.

---
Tags: 7, i18n-l10n
---


# Question
Title: Is there a module/Drush command for updating multiple field settings at once?
Just for convenience I wish change all required fields to optional at once.

Is there module or even better, a Drush command supporting module to do so?

# Answer
> 3 votes
I don't think there's a module or anything to do this, as it's quite a specific use case.

However, you could try something like the following in either a custom module's update/install hook.

***Note*** I've not tested this, but you'll have to tweak it for your use case anyway.

```
$options = array(
  'entity_type' => 'node'
);
// Get all field instances that are on nodes
$fields = field_read_instances($options)

// Loop through the fields...
foreach ($fields as $field => $data) {
  // ...and prune the array to remove any non-required fields
  if ($data['required'] == 0) {
    unset($fields[$field]);
  }
  // $fields now only contains data for required fields attached to nodes
}

// Loop through the remaining fields
foreach ($fields as $field) {
  $instance = array(
    // Provide the default information that field_update_instance requires
    'entity_type' => $field['entity_type'],
    'bundle' => $field['bundle'],
    'field_name' => $field['field_name'],
    // Make your required changes
    'required' => 0
  );

  // Take the data in the $instance array and pass it through to field_update_instance.
  field_update_instance($instance);
}

```

You can filter down your selection of fields by passing different options through to `field_read_instances()` (e.g. if you only want fields attached to the Basic Page content type, the `$options` array would look like this:

```
$options = array(
  'entity_type' => 'node',
  'bundle' => 'page'
);

```

As a sidenote, `field_update_instance` clears the field cache at the end of every call, so if you have a lot of fields, then this might take a while .

**Documentation:**

# Answer
> 1 votes
You can use the Required Fields module:

> This project provides an admin interface which lists all the fields grouped under content types. And it has a functionality to make the fields as required or optional.

---
Tags: entities, drush
---


# Question
Title: How to display a computed field in an automatic node title?
I am trying to display something like "Field A - Field B" as a title for each content created on a Drupal 7 website.

The Field A is entered manually through Drupal standard form.

The Field B is computed with the module Computed Field and it depends on Field A value (this part works fine).

Now I would like to create automatically the node title on saving with Automatic Entity Label, using Token. (This is the new Automatic Nodetitles).

Unfortunately, using \[node:field\_a\] - \[node:field\_b\], the computed field B value is invisible. More, if you edit the node and save it a second time, the title is OK...

It seems like the field value calculation is made simultaneously with the title generation and thus this value can not be used to generate the title. Of course, I can not tell my client to save twice, we can not say it is user-friendly...

Is there another way to build this automatic title based on a computed field?

Related questions :

How to Compute fields on the fly

What's wrong in my code for setting up entity title in a Computed Field?

On the same subject on Drupal.org :

https://www.drupal.org/node/370850

# Answer
> 1 votes
What about setting up a rules event to set a data value for the node title using the event "after content is saved" ?

This should work...

1. Set up a rule with the event "after content is saved".
2. Set up the action "set a data value"
3. Choose the title field, and use the tokens to set your value.

---
Tags: 7, entities, nodes
---


# Question
Title: Ajax callback function in custom form class is not firing
Related to my previous question, but this specifically pertains to how ajax works rather than what `$form_state` does.

I have a form class defined with the following code (an "instruction" in this code is just the name for a blank text field, and there needs to be the ability to add as many of these text fields as the user desires):

```
namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MymoduleSubmitForm extends FormBase {
/**
 * {@inheritdoc}
 */
public function getFormId() {
    // Unique ID of the form.
    return 'mymodule_submit_form';
}
/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
    // Create a $form API array.

    $form['#tree'] = TRUE;
    $i = 0;
    $num_instructions = $form_state->get('num_instructions');
    if (empty($num_instructions)) {
        $num_instructions = $form_state->set('num_instructions', 1);
        $num_instructions = $form_state->get('num_instructions');
    }
    $form['instructions'] = array(
            '#type' => 'fieldset',
            '#title' => 'Instructions',
            '#prefix' => '<div id="instructions-wrapper">',
            '#suffix' => '</div>'
    );
    for ($i = 0; $i < $num_instructions; $i++) {
      $form['instructions'][$i] = [
        '#type' => 'textfield',
        '#title' => $this->t('@num', ['@num' => $i + 1]),
      ];
    }
    $form['add_instruction'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Add step'),
        '#ajax' => array(
            'callback' => '::addInstructionCallback',
            'wrapper' => 'instructions-wrapper'
        ),
    );
    $form_state->setCached(FALSE);
    $form['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Submit')
    );
    return $form;
}

/**
 * Implements callback for Ajax event
 *
 * @param array $form
 *   From render array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current state of form.
 *
 * @return array
 *   Form fields.
 */
public function addInstructionCallback(array &$form, FormStateInterface $form_state) {
    ddl($form);
    $name_field = $form_state->get('num_instructions');
    return $form['instructions'];
}

/**
 * {@inheritdoc}
 */
public function validateForm(array &$form, FormStateInterface $form_state) {
}

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
    ddl(1); //ignore this for now
}

```

The form is called in `mymodule.module` like this:

```
function mymodule_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    $current_path = \Drupal::request()->getRequestUri();
    $paths = explode('/', $current_path);
    if ($paths[1] == 'submit-set')
        $build['myform'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MymoduleSubmitForm');
}

```

My problem is that my Ajax callback function `addInstructionCallback` does not seem to be firing *at all.* The indicator appears when I click the button to show that the ajax function is doing its work, and then it goes away and the form hasn't changed. I check /admin/reports/debug and it is completely empty, the `ddl($form);` call from within my callback function has not fired. There are no PHP error messages to be found in reports or log files either.

I am mostly following the code in this example, but I have also tried an approach using `AjaxResponse` like in this example and it hasn't made a difference. I have also tried changing the button to a checkbox in case it was breaking because of my unfinished submit function, but that didn't make a difference either.

What am I doing wrong with Ajax?

**Update**: Console is doing some weird stuff:

```
Uncaught AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /submit-set?ajax_form=1
StatusText: OK

```

`ResponseText:`(entire contents of my page, including theme headers and footers, followed by

```
{"ajaxPageState":{"theme":"bartik","libraries":"admin_toolbar\/toolbar.tree,admin_toolbar\/toolbar.tree,admin_toolbar_tools\/toolbar.icon,admin_toolbar_tools\/toolbar.icon,bartik\/global-styling,bartik\/global-styling,bartik\/messages,classy\/base,classy\/base,classy\/messages,classy\/messages,classy\/node,classy\/node,contextual\/drupal.contextual-links,contextual\/drupal.contextual-links,contextual\/drupal.contextual-toolbar,contextual\/drupal.contextual-toolbar,core\/drupal.active-link,core\/drupal.active-link,core\/html5shiv,core\/html5shiv,core\/normalize,core\/normalize,history\/mark-as-read,history\/mark-as-read,quickedit\/quickedit.inPlaceEditor.plainText,shortcut\/drupal.shortcut,shortcut\/drupal.shortcut,system\/base,system\/base,toolbar\/toolbar,toolbar\/toolbar,toolbar\/toolbar.escapeAdmin,toolbar\/toolbar.escapeAdmin,tour\/tour,tour\/tour,user\/drupal.user.icons,user\/drupal.user.icons"},"ajaxTrustedUrl":{"\/search\/node":true},"history":{"nodesToMarkAsRead":{"45":true}},"toolbar":{"breakpoints":{"toolbar.narrow":"only screen and (min-width: 16.5em)","toolbar.standard":"only screen and (min-width: 38.125em)","toolbar.wide":"only screen and (min-width: 61em)"},"subtreesHash":"Y9yCNrSN2LUELxt5wnz-3xSDjtgka559ps7ynAoGrpw"},"path":{"baseUrl":"\/","pathPrefix":"","currentPath":"node\/45","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en","currentQuery":{"_wrapper_format":"html","ajax_form":"1"}},"pluralDelimiter":"\u0003","user":{"uid":"1","permissionsHash":"d0f6778fd5e1fddf0d1d92a309af30862905f78390534ce1aa8a064cbc51b24e"}}

```

)

Trace:

```
Drupal.Ajax.error       @   {cache}:2995
complete                @   {cache}.js:2540
t.complete              @   {cache}.js:1320
j                       @   {cache}.js:2
fireWith                @   {cache}.js:2
x                       @   {cache}.js:4
(anonymous function)    @   {cache}.js:4

```

Have already tried clearing cache.

**Update:** Modified code to match another example. Still getting the same error.

**Update:** Adding a `console.log(status);` to the called `complete` function above `return ajax.error(xmlhttprequest, ajax.url);` returns the string `parsererror`. Trying to log anything else related to the ajax request to console (such as the `xmlhttprequest` parameter) crashes the page.

# Answer
> 2 votes
I've figured it out. My problem was that I was inserting an Ajax-using form into a page node. I don't know why this is a problem, but I installed the Examples module and saw that the AjaxAddMore.php form was working fine as-is once installed. I replaced my custom form with the AjaxAddMore form in the setup I had (inserting a form into a page node), and it also returned the same console error I was getting before.

I looked at the `fapi_example.routing.yml` file in Examples, particularly the following lines:

```
fapi_example.ajax_addmore:
path: 'examples/fapi_example/ajax_addmore'
defaults:
  _form:  '\Drupal\fapi_example\Form\AjaxAddMore'
  _title: 'Add-more button'
requirements:
  _permission: 'access content'

```

and set up my form to display on its own in this manner. I did not need the form to exist with any other page content, so I removed it from the page insertion setup I had before entirely.

I wouldn't call this a solution for a use case where it would be necessary to insert a form into a page node, but for my purposes the form ajax is working now.

---
Tags: forms, 8
---


# Question
Title: Why is my custom module is not listed with the drush command pm-projectinfo?
If you have drush \>= 8 you can use `drush pm-projectinfo` to show a report of available projects and their extensions. If you use `drush pm-projectinfo devel` you should see the information about the devel module something like this:

```
 Name             :  Devel (devel)
 Type             :  module
 Version          :  7.x-1.3
 Status           :  1
 Extensions       :  devel
                     devel_generate
                     devel_node_access
 Drush Commands   :  devel-download
                     devel-reinstall
                     fn-hook
                     fn-view
                     devel-token
 Datestamp        :  1338940281
 Path             :  sites/all/modules/development/devel

```

I come from creating a custom module named my\_custom\_module, but when I use `drush pm-projectinfo my_custom_module` the output is:

```
 [warning] my_custom_module was not found.

```

It's very weird because I know that my module works fine, I use it every day, but the command doesn't work.

How can I solve this? Is it a problem with drush or is it a problem with my custom module?

# Answer
> 2 votes
The solution is very simple, you just need to add project property in your .info file.

In this case:

```
project = "my_custom_module"

```

The Drupal documentation page Writing module .info files (Drupal 7.x) says about the project property:

> **project** ***(Discouraged, packaging use only)***
>
> Module maintainers should not use this at all. The packaging script on drupal.org will automatically place a string here to identify what project the module came from. This is primarily for the Update status module, so that Drupal installations can monitor versions of installed packages and notify administrators when new versions are available.

But as this is a custom module I think that I need to put this property in my .info file because if not, `drush pm-projectinfo my_custom_module` will not works.

*Let's see why if you don't use the project property this doesn't works*

Inside the drush code you can see the implementation of the drush pm-projectinfo command:

```
function drush_pm_projectinfo() {
  // Get specific requests.
  $requests = pm_parse_arguments(func_get_args(), FALSE);
  // Get installed extensions and projects.
  $extensions = drush_get_extensions();
  $projects = drush_get_projects($extensions);

```

If you use:

```
drush ev 'print_r(array_keys((drush_get_extensions())))' | grep my_custom_module

```

You will see something like this:

```
[112] my_custom_module

```

So, we need to test the next step:

```
drush ev 'print_r(array_keys(drush_get_projects(drush_get_extensions())))' | grep my_custom_module

```

Nothing to show

So, if we go inside the drush\_get\_projects() function we can found the following code in line 673:

```
  foreach ($extensions as $extension) {
    $extension_name = drush_extension_get_name($extension);
    $extension_path = drush_extension_get_path($extension);
    // Obtain the project name. It is not available in this cases:
    //   1. the extension is part of drupal core.
    //   2. the project was checked out from CVS/git and cvs_deploy/git_deploy
    //      is not installed.
    //   3. it is not a project hosted in drupal.org.
    if (empty($extension->info['project'])) {

```

And in number 3 we have our answer.

---
Tags: drush
---


title: How to debug EntityQuery?

text:
# Question
Title: How to debug EntityQuery?
I have a query with a 'BETWEEN' operator and I should have some results. Is there any way to show the actual SQL query made ?

Here is my entity query :

```
    $query = $this->entity_query->get('node');
    $query->condition('type', 'store');
    $query->condition('status', 1);
    if ($lat_min && $lng_min && is_numeric($lat_min) && is_numeric($lng_min) && $lat_max && $lng_max && is_numeric($lat_max) && is_numeric($lng_max)) {
      $query->condition('field_store_geolocation.lat', [$lat_min, $lat_max], 'BETWEEN');
      $query->condition('field_store_geolocation.lng', [$lng_min, $lng_max], 'BETWEEN');
    }
    $nids = $query->execute();

```

Of course I made sure that my values were the one expected and I also tried with '\<', '\>' and with no vars but actual values to make sure nothing was wrong there.

I'm using the 'Geolocation Field' module here.

# Answer
If you use devel module a simple approach for debugging entity query could be use the `debug` tag (simply add `$query->addTag('debug')` to your query). Here an example

```
$query = $this->entity_query->get('node');
$query->condition('status', NODE_PUBLISHED);
$query->addTag('debug');
$query->execute();

```

And the result
> 20 votes

---
Tags: 8, database, entities
---


title: Node title does not update

text:
# Question
Title: Node title does not update
I wanted to add a word in front of the title for certain nodes. So I run an update sql statement on nodes table. The result can be seen in the attached image.

I empty the cache (flush all) but my new titles still do not appear on the website. Should I update in a different place in database also? Do I have to do something else to see the new titles?

Thanks in advance for helping me out with this !

# Answer
> 4 votes
I am pretty sure you have to update "node\_revision" too.

https://www.drupal.org/node/320614

> Note that the node\_revisions table in the database will always have one record associated with each record in the node table, which it keeps track of as the current revision. This will happen even if you do not have revisions enabled.

---
Tags: database, updating
---


# Question
Title: Add field value in the value of another field
I'm sorry about the title (I think it's a bit confused :D) I can explain better what I need to do. I have one product with several fields, among which: title,date, description, price, etc... I would add in a field (for example: description) a value of another field (for example: price). I would also that this setting is applied to content type because that field must always belong to the other field, for every content creation.

I searched on Google and it seems the module Token could be a solution but there are many tutorials (and also different among them), so could you help me. Are appreciated other solution, no just Token. Thank you

# Answer
> 0 votes
You might find Field reference useful. If you're trying to leverage more functionality, you might like to use Entity reference. But you sound like you want embed the value of one field within the value of another, more like concatenating strings?

# Answer
> 0 votes
If what you are aiming to do is include values from other fields within the content of a formatted text field, then you could try using a module that provides token support as an input filter.

Advanced Text Formatter looks like it should do the job (and it has d7/d8 versions). You would then be able to use a token such as `[node:field_price]` within the text and it will be replaced with the value of that field when it is displayed.

It does sound like you should be using tokens, as this is pretty much what they are designed to facilitate.

# Answer
> 0 votes
I tried to use Advanced Text Formatter but the problem is in the Available Token list, I can't see the field that i need. I don't see the tokens like "\[node:....\]". Where are the tokens about the same content?

---
Tags: entities, tokens
---


title: Create a post method in Drupal 8

text:
# Question
Title: Create a post method in Drupal 8
I've been trying to create a post method in Drupal 8, I used the following code:

custom\_rest/src/Plugin/rest/resource/CustomRestResourceUserCheck.php:

```
<?php

namespace Drupal\custom_rest\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "custom_rest_resource_user_check",
 *   label = @Translation("Custom User Check"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/custom/user_check"
 *   }
 * )
 */
class CustomRestResourceUserCheck extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('custom_rest'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to POST requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function post() {

    // You must to implement the logic of your REST Resource here.
    // Use current user after pass authentication to validate access.
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }

    return new ResourceResponse("Implement REST State POST!");
  }

}

```

I have activated:

I tested this functionality in Postman but I get the following error:

Someone may know that something is wrong?

**Edit 1**

Drupal version: 8.1.9

# Answer
**Solution:**

We need a different path:

```
 * @RestResource(
 *   id = "custom_rest_resource_user_check",
 *   label = @Translation("Custom User Check"),
 *   uri_paths = {
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/custom/user_check"
 *   }
 * )

```

Source: https://www.drupal.org/node/2799383#comment-11619919
> 1 votes

---
Tags: 8
---


# Question
Title: Pathauto for a multilingual site not generating alias for non-default languages
I have a site with 90% content in Chinese, and only 10% in English.

Thus the requirement of the client is that when viewing an article in English, everything around it remains in Chinese. Blocks, menus etc

a) Enable language prefix

What this does is sets english article with `en/[node:title]` which is acceptable. But the problem occurs as it appends that to every url in the menu, and other places. So they become like `en/categories/CHINESE-CHARACTERS` which is not right, and no content is displayed.

In pathauto for English articles, I thus tried, specifically giving it `[node:title]`. Yet it prepends the `en`.

b) Disable language prefix.

Now all my links are fine. But the english article is now a `node/[nid]`. The url aliases just don't seem to be working in this case. If I could just have the URL alias working in this case, things would be great too.

Any solution to my misery is welcome.

# Answer
Aliases indeed disappear from nodes with non-default language after disabling language prefix in URLs. The solution to that is easy, but you have to do it in code, using Pathauto's `hook_pathauto_alias_alter()`.

Basically all you need to do is:

```
function yourcustommodule_pathauto_alias_alter(&$alias, array &$context) {
  // Force all aliases to be saved as language neutral.
  $context['language'] = LANGUAGE_NONE;
}

```

This way you make sure that the language of the saved alias (not of node!) will always be `und`, meaning it will show for nodes of all languages.

Note: For existing aliases it is not enough to re-save the node. You have to delete the alias first and then have it recreated. Often the easiest is to do it in bulk via Pathauto's configuration interface. First delete all paths, then bulk-recreate them.

For more, see https://www.drupal.org/node/1234924
> 2 votes

# Answer
this is an old question, but for future readers I recommend take a look to Pathauto i18n module. From the module page:

> As you know by default Pathauto creates alias only for one language or for all languages one alias. This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.
>
> **Example**
>
> When you create node without pathauto\_i18n: English alias: en/articles/first\_article Italiano alias: not exist Deutsche alias: not exist
>
> When you create node with pathauto\_i18n: English alias: en/articles/first\_article Italiano alias: it/articolo/first\_article Deutsche alias: de/artikel/first\_article
>
> The same for taxonomy and users.
>
> This module contains 3 submodules pathauto\_i18n\_node, pathauto\_i18n\_user and pathauto\_i18n\_taxonomy which allows enable separate functionality for each entity.
>
> How to use
>
> * Enable multilingual support for nodes(needs only for nodes)
> * Configure alias patterns on page admin/config/search/path/patterns
> * Create entity with option "Generate automatic URL alias for other languages"
> 1 votes

# Answer
Try the Pathauto Persistent State module. Details from project page:

> Pathauto tries to do it's best to remember if it should be allowed to continue automatically alias a node, but in some cases it needs some help to really remember if you clicked the 'Automatic alias' checkbox or not. So let's save that into the database!

Looks like pathauto as it is has problems dealing with multilingual settings. The module prevents it from "forgetting" these settings.
> 0 votes

# Answer
Try neutral\_paths www.drupal.org/project/neutral\_paths
> -1 votes

---
Tags: 7, i18n-l10n, path-aliases
---


# Question
Title: How can I use Rules to 'Set a Data Value' on a node's field WITHOUT updating that node's 'updated' timestamp?
I am using rules to set a data value of a field on a node. Works great!

BUT, when the rule is triggered, the node's 'updated' timestamp is changed. In my particular application, I do NOT want this to happen. I totally understand why this behavior might be desired by some (most), but in my case I don't.

Is there any way to prevent the 'updated' timestamp from being updated when rules is used to set/change the value of a field on that node?

Here are the nitty gritty details of my application: I have two node types: Parent & Child The child node includes an entity reference field to relate it to its parent node. When a child node is created or updated, I use rules to change a field value of it's parent node. I got that all to work great, but, when the rule is triggered, the parent node's 'updated' timestamp is changed to the current time, which I do not want.

I also posted this question to the Rules issue queue on d.o: https://www.drupal.org/node/2796899

# Answer
If it is not necessary for you to use rules, you can also try to invoke the hooks node\_update and node\_insert. There you can load the parent, change the fields value and save it with the field\_attach\_update function.

You can find an interesting article about this at https://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself
> 1 votes

---
Tags: rules
---


# Question
Title: Attaching Google PHP Library to custom module
How do I use an external PHP package in my own module?

This is the one I want to use: https://github.com/googleads/googleads-php-lib

I have some questions

1. Where should i put the library?
2. Where should i declare the library?
3. Should i include something like `use`

Thanks in advance

# Answer
I advise using composer to do this.

First, you need to pull in the library:

```
composer require googleads/googleads-php-lib:dev-experimental

```

The reason you want the experimental branch is it has added PSR-4 support and namespaces to its various classes. The master branch does not have these changes.

Then, to use any of the classes in your own class files, you need to use `use` statements.

```
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201605\cm\OrderBy;
use Google\AdsApi\AdWords\v201605\cm\Paging;
use Google\AdsApi\AdWords\v201605\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

class MyController extends ControllerBase {

  // code...

  public function foo($args...) {
    $adWordsServices = new AdWordsServices();
    // code...
  }

}

```

Check the README in that branch (not the master) for more examples.

https://github.com/googleads/googleads-php-lib/tree/experimental

`composer require` (run it from the root of the application) will add this package to the list of dependencies.

If you are shaping this module to someday be a contributed module on drupal.org, you can add your own composer.json file to the custom module folder, and add this Google package as a dependency of the module. When users run `composer require drupal/drupal_rollers_module` \- it will automatically fetch the Google library as well for them.

One last thing, the example above is kinda not so great (instantiating a new object in a method) and what you really want to do is have dependency injection provide that for you. I haven't taken a deeper look at the Google library you want, but you would need to define some services that pull in those classes in order to get to that point. Feel free to open another question later or peruse the ones already discussing DI.
> 0 votes

---
Tags: 8, theming, composer
---


# Question
Title: Is there a way to add new custom selection rules for panels?
I find the pre-supplied list of selection rules to create panel variants to be quite lacking. For instance, if I am using panels to override taxonomy term pages, and I have some arbitrary boolean field on each term (say, "Is Blog?"), then I would like to create a panel variant based on this field being equal to TRUE.

However there is no such flexibility when using Selection Rules to create variants. Am I alone in thinking that this missing functionality greatly diminishes the power of Panels and panel variants?

How would a site builder, or developer, go about creating new "custom" selection rules?

# Answer
> 1 votes
Well, there is an inelegant workaround, suitable only for someone comfortable working with code. There is a choice in the Selection Rules dropdown called: "PHP code" where the contexts are available in the $contexts variable. This means all fields of the current taxonomy term are in there.

I ran this: return @$contexts\['argument\_term\_1'\]-\>data-\>field\_is\_blog\['und'\]\[0\]\['value'\];

It will return 1 if the is\_blog field exists and has a value of 1. Otherwise (if the field does not exist or it otherwise evaluates to false), it fails silently.

I'm not totally happy with this solution, but it gets the job done.

# Answer
> 1 votes
We initially did it the way that you did. However, after a site security audit, we were told that we should not include PHP in that way (even though it's there and available). The solution is to create a custom rule using ctools access plugins. This page has an excellent breakdown of how to do it. We now have about 5 or so custom ones we use through custom modules.

---
Tags: taxonomy-terms, panels
---


# Question
Title: Display POA in Ubercart 3 / D7 for products of zero dollars
I'm building an ecommerce site where some products are price negotiable and want a way to add POA instead of a listing a price when a product is displayed.

I'm kinda surprised at how hard this is to do.. I have a snippet that works for Ubercart 1 in Drupal 5, but it looks like the hooks have changed in Ubercart 3 and I can't find a pricing hook:

```
    <?php
function zen_uc_product_display_price($price) {
  $output = '<div class="display_price">';
    if ($price!=0) {
      $output .= uc_currency_format($price);
    } else {
      $output .= t('P.O.A');
    }
  $output .= '</div>';
  return $output;
}
function

zen_uc_product_sell_price($price, $teaser) {
  if ($teaser) {
    $output = '<span class="sell_price">';
        if ($price!=0) {
            $output .= uc_currency_format($price);
        } else {
            $output .= t('P.O.A');
        }
    $output .= '</span>';
  }
  else {
    $output = '<div class="sell_price">';
        if ($price!=0) {
            $output .= t('Price: !price', array('!price' => uc_currency_format($price)));
        } else {
            $output .= t('Price: P.O.A');
        }
    $output .= '</div>';
  }
  return $output;
}
?>

```

I've managed to hook the add to cart function and direct it to a webform with the following snippet:

```
<?php

function fmc_uc_product_add_to_cart( $variables ) {
$sell_price = $variables['form']['node']['#value']->price;
if ($sell_price <= 0) {
return '<form action="http://www.example.com/" method="post"><input type="hidden" name="product" value="' . drupal_get_title() . '" /><input type="submit" class="form-submit" value="' . t('POA') . '" /></form>';
}
else {
return fmc_uc_product_add_to_cart($variables);
}
}

```

But I'm having no luck with the pricing function, if anyones got a code snippet I can run in my template.php file that'd be the ideal solution, but any ideas / advice is hugely appreciated. Is there a way this can be broken out inside a node--product.tpl.php file maybe?

# Answer
> 1 votes
I have not tried this out but I would think you could override theme\_uc\_price() in your template.php something like this:

```
function THEMENAME_uc_price($variables) {
  if ($variables['price']) {
    $output = '<span class="uc-price">' . uc_currency_format($variables['price']) . '</span>';
    if (!empty($variables['suffixes'])) {
      $output .= '<span class="price-suffixes">' . implode(' ', $variables['suffixes']) . '</span>';
    }
  }
  else {
    $output = t('P.O.A');
  }
  return $output;
}

```

# Answer
> 0 votes
I finally managed to get this to work for me in Drupal 7/Ubercart 3 for an art gallery where we wanted POA to display for $0.00 and the price to display for priced items. The code below goes in the bottom of your theme template.php file. (please note to get all the code to show on here without this forum stripping bits out, I had to remove the opening tag before span so you just need to pop that back in eg: '(less-than-sign)span in line 2. Also right near the end replace '(less-than-sign)/div\> as per this screenshot. Code to copy is below.

Hope this saves someone some hours!

```
    /* change uc price to show POA if price is zero */

 function YOURTHEMENAME_uc_price($variables) {
$output = 'span class="uc-price">';

if ($variables['price']!=0) {

  $output .= uc_currency_format($variables['price']);
} else {
  $output .= t('P.O.A');
}

```

$output .= '/div\>'; return $output;

}

---
Tags: 7, theming, hooks, ubercart
---


# Question
Title: Recover from a Lost Drupal Administration Menu
When I log into the Admin on my site, the drupal controls are all missing. Our former Web Developers refered me to an article online that told me I need to enable the toolbars by:

What you need to do is access the main "Modules" page. The best way to get there is by typing in the URL of the modules page.

Try adding one of these to your main domain name: •/admin/modules/ •?q=admin/modules

Neither of these worked. With /admin/modules/ I get "Page Not Found".

With ?q=admin/modules I get "Access Denied"

How can I get the drupal controls back so I can make edits?

# Answer
Open below URL and change settings

admin/people/permissions

Or else you can edit here roles & permissions

admin/people/permissions/roles
> 0 votes

# Answer
If you use "Devel" Module than load user and edit access

```
$a = user_load(1);
dpm($a);

```
> 0 votes

---
Tags: rules
---


# Question
Title: Moving File Directory to Other Partition
I want to know if it's possible to move the files directory, put it in another partition, and point to it. I've tried several methods and can't find the solution.

This is what I've tried:

* I created a second partition on my disk and moved all `/files/` folders into it, so I have a `D:/files` folder.
* I went to admin/config/media/file-system and changed the 'Public file system path' prompt from 'sites/FirstProject/files' to `D:/files/`.

However, the styles are missing from the site and I don't know why.

The installation path of my project is `C:/xampp/htdocs/www/proyects/sites/FirstProject/files` (it is a multi-site installation), and I want to move the files directory to this partition, D:/files.

Can someone help me?

Thanks in advance.

# Answer
> 2 votes
It's probably easier to simply use symlinks to point to the new folder. That way, you can leave the default settings as they are. In addition, Windows will deal with the change instead of Drupal. Move the files folder to `D:/files`, open a command prompt (cmd), and run the following:

```
C:\> mklink /j "C:\xampp\htdocs\www\proyects\sites\FirstProject\files" d:\files\

```

Are you sure its `proyects` and not `projects`?

# Answer
> 0 votes
Although I haven't used Windows in years, your approach seems basically fine. Your problems with image styles may stem from write permissions in the new location; you may want to check whether all directories in the path for the derived images are actually present. If not, check the watchdog log for errors regarding the creation of these directories. You *could* manually create them, but that may run you into problems down the line when e.g. new styles are added.

---
Tags: 7, files
---


title: How to have a secure HTTPS login form?

text:
# Question
Title: How to have a secure HTTPS login form?
I have Drupal site with a login form on my home page.

How do I go about posting to a HTTPS url, and then after a successful authentication, redirect back to HTTP admin page?

# Answer
Given the way things are heading on the internet now, and Google making statements about weighing HTTPS sites higher than HTTP in the past couple of months, you might as well make it totally HTTPS.

You don't want to log in on HTTPS then redirect back to HTTP, you'll have issues with people being logged in and out intermittently. People have tried to address this issue over the years, but I don't think it has ever been solved.

I would set HTTPS always on and handle it in .htaccess, redirecting any non HTTPS traffic to HTTP. (to clarify, you do not need a module to do any of this - just follow the instructions in .htaccess and work with your hosting provider to provide an SSL cert).
> 4 votes

# Answer
If you want to view the /user (login) page on https and you already have a certificate available. Installing the certificate and using the https://www.drupal.org/project/securepages module.

But... when logging in via https i wouldn't recommend redirecting back to https in the admin side of things.

What would be an option, and is possible with that module is, when not logged in just using the secure pages (https) for webforms / login forms etc. (every page that requires user input).
> 0 votes

# Answer
Use Secure Login

> For sites that are available via both HTTP and HTTPS, Secure Login module ensures that the user login and other forms are submitted securely via HTTPS, thus preventing passwords and other private user data from being transmitted in the clear. Secure Login module locks down not just the user/login page but also any page containing the user login block, and any other forms that you configure to be secured.
>
> For Drupal 7 and 8, Secure Login module enforces secure authenticated session cookies, thus preventing session hijacking by eavesdroppers. For previous versions of Drupal, PHP's session.cookie\_secure flag must be enabled on the HTTPS site to enforce secure session cookies.
> 0 votes

# Answer
To strictly do what you are asking, I would recommend the secure pages module. You will need to make sure that your web server setup is correctly configured to use https. Contrary to another answer, it is definitely possible and can work quite well, once it is all configured. There are many caveats, though, such as getting sessions to correctly share between http and https.

All in all, though, in this day and age I would heartily recommend to not bother and just run the entire site through https. The overhead of encryption is not a factor anymore with modern hardware, and since it allows the use of http 2, it can actually be *faster* than plain old http. Also, it is starting to have small SEO benefits to have your site accessible through https (Google has announced over a year ago that they will give pages some extra ranking when they are https).
> 0 votes

---
Tags: 7, ssl
---


# Question
Title: How to show specific rows within an unlimited field group?
I am trying to assign value to unlimited field group on load of content using form alter hook. Value get assign successfully for all rows. But when form get loaded it display only one row. On click of "Add Another Item", it display second row with value assigned in form alter hook.

Is there any way to display number of rows as required? Can I handle this in form alter hook?

# Answer
> 1 votes
Yes you can do it by form\_alter. Seeing through the code of other similar question, I see that unsetting the Add More button can do it for. You can review that code & apply for your case.

You can do it by help of Field Validation module too, which has been mentioned in 2nd answer & more feasible way. I have also used it for some projects of mine, where I did set minimum & maximum required for a field accepting multiple values.

---
Tags: entities
---


# Question
Title: How to load a node based on current language?
I have 2 content bundles for node entity:

1. Custom Layout Pages (custom\_layout)
2. Recipes (recipe)

Then I created two content using those content types, Potato (recipe) and Homepage (custom\_layout).

I have 2 languages for both content, en and fr. I'm trying to load the potato recipe node inside of the homepage content.

So inside the preprocess hook, I have this code

`...
if(isset($vars['node']) && $vars['node']->type === 'custom_layout'){
 $recipe_id = 10;
 $vars['recipe_side'] = render(node_view(node_load($recipe_id)));
}
...`

Then I echo the $recipe\_side in the custom\_layout template file.

When I load the fr version of the page, I expected the recipe to be loaded in fr as well, but it always displays the en version.

I'm guessing it's because the en recipe node id is 10, and it doesn't load the translated node.

If that's the case, how can I make it work so that the loaded node follows the current language?

# Answer
> 1 votes
Try this code:

```
 $node_trad = node_load($variables["node"]->nid); // in your case, 10.
 $idi_trad = translation_node_get_translations($node_trad->tnid);

  $vars['recipe_side'] = render(node_view(node_load($idi_trad["fr"]->nid)));
  //$vars['recipe_side'] = render(node_view(node_load($idi_trad[$language->language]->nid)));
  // alternative, more dynamical

```

Essentialy you load the node in original language, use the translation function to get all available translations, and use that what you need. Instead of "fr" you could use `language->language` instead to make it completely dynamical.

# Answer
> 0 votes
Use the following code to get the TRANSLATED node for the current language:

```

$node_id = 10;  // Put the node ID here where you want the translation for.
$translation_node = translation_node_get( $node_id );

// Show the translated node
print_r( $translation_node );

function translation_node_get( $node_id )
{
    if ( is_numeric($node_id) && $node_id > 0 )
    {
        // Get current language code
        global $language;
        $lang_code = $language->language;

        // Get translation node id
        $base_node = node_load( $node_id );
        $tnid = $base_node->tnid;

        // Search the database for the translated node of the current language
        $result = db_select('node', 'n')
        ->fields('n', array('nid', 'type', 'uid', 'status', 'title', 'language'))
        ->condition('n.tnid', $tnid)
        ->condition('n.language', $lang_code)
        ->addTag('node_access')
        ->execute();

        foreach ( $result as $trans_node )
        {
            // Return the correct language node
            return node_load( $trans_node->nid );
        }
    }

    // No translation node found!
    return false;
}

```

---
Tags: i18n-l10n, nodes
---


# Question
Title: How to force a cron run after a Rules component is scheduled?
This question is a sequel on Why is the database not updated before a next Rule is launched?. I have a Rule that schedules a Rules component 5 seconds after the current time (this number is arbitrarily chosen). Since this component uses information from a frequently changing View, it should be executed as soon as possible. However, in my current configuration, that only happens when cron is run; which takes place once in an hour.

Can I somehow force a cron run (eventually with Rules) when the Rules component is scheduled?

# Answer
> 0 votes
you can give this module a try , it makes it possible to run cron via configurable rules Ultimate cron

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


title: List through fieldName: illegal value

text:
# Question
Title: List through fieldName: illegal value
I have created content type with field as List(text). If I select any of above option and try to save it, it through "fieldName: illegal value" error.But if I modified option in below format and then try to save it. It get saved successfully.

```
-option1

-option2

-option3

-option4

```

Does list doesnot support first format? Is there any other way to resolve this without changing its format ?

# Answer
You can achieve that by using `hook_form_alter` function.

I've tested the following code on my instance. It's working fine.

Use the following code in your custom module.

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
        if ($form['#form_id'] == 'YOUR-CONTENT-TYPE_node_form') {
         $form['YOUR-FILED-NAME']['und']['#options'] = array (
       'Group1' => array(
          1 => 'Option1',
          2 => 'Option2',

        ),
        'Group2' => array(
          3 => 'Option3',
          4 => 'Option4',
        ),
    );
    return $form;
        }
    }

```
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to create one node tpl files for multiple content types?
In my site I have 10-15 content types that have the exact same node template layout. Like `node--productone.tpl.php`, `node--producttwo.tpl.php` etc...

How can i create one *node tpl* files for that similar type of content types?

# Answer
> 1 votes
Yes you can. Here is the example:

```
function YOURTHEMENAME_preprocess_node(&$variables) {
  if ($variables['node']) {
    $node = $variables['node'];
    switch ( $node->type ) {
      case 'type1':  // Replace with your actual content types
      case 'type2':
      case 'type3':
      // looks for node--common.tpl.php in your theme directory
      $variables['theme_hook_suggestion'] = 'node__common';
      break;
    }
  }
}

```

---
Tags: 7, theming
---


# Question
Title: How can i maintain the database for CMS in Bitbucket for a Drupal used website
I am using Drupal 7 for my website development and my question is How can i maintain a database for a version control system (Bitbucket). is there any best tools/ modules available to do?

# Answer
> 0 votes
No. many have tried to version control databases and it simply does not work well.

If you want to manage config, you can use Features, which can save config and variables to code.

---
Tags: 7, database
---


# Question
Title: Custom blocks created as a plugin in a module not showing for Block::load()
I have a couple of blocks that have been created using the `... extends BlockBase` syntax in my module. They work perfectly fine, and I can add them on the blocks layout page, can add them into DS as a field, etc. They definitely exist fine.

However, when I try and render them using `Block::load()`, they won't show up, unlike other blocks that work fine.

For example, if I have the following docblock:

```
/**
 * Provides a 'Cute Cats' Block.
 *
 * @Block(
 *   id = "cute_cats",
 *   admin_label = @Translation("Cute cats yo"),
 * )
 */
 class CuteCats extends BlockBase { ... }

```

... and then try and call it like this:

```
$block = \Drupal\block\Entity\Block::load('cute_cats');
return render(\Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block));

```

Any idea why? Thanks in advance.

# Answer
`Block::load()` loads a configured block, that means a block that is placed in the block layout. It does not load plugins.

The name of the configured block is displayed in the block layout as *Machine name*.

You can place the block in the *Disabled* section, if you only want to configure the block, but don't want to show the block in a region.
> 1 votes

# Answer
It turns out that I was using the wrong syntax, and should have used a different one for plugin blocks (as @4x4 mentioned). The correct code for plugin blocks is:

```
$plugin_manager = \Drupal::service('plugin.manager.block');
$block = $plugin_manager->createInstance($block_id, array());
return render($block->build());

```
> 1 votes

---
Tags: 8
---


title: Can't enable dev module from Drush

text:
# Question
Title: Can't enable dev module from Drush
I am downloading a dev version of the Drush Search & Replace module via

`drush dl sar-7.x-2.x-dev`

And then trying to enable it

`drush en sar`

But returns contradicting options. First it says the project was not found, and then asks to overwrite the project that was downloaded previously

```
drush en sar
sar was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                              [ok]
sar
Would you like to download them? (y/n): y
Install location /home/ubuntu/.drush/sar already exists. Do you want to overwrite it? (y/n):

```

Using drush 5.10.0

# Answer
> 2 votes
You need to clear drush cache. I have seen this same thing before, where I try to do a drush action from a module and am told the action is not available. Then a `drush pm-list | grep "module"` shows me it is enabled.

```
drush cc drush
drush en sar

```

As we say around my office daily, "When in doubt, clear cache." If this is not working, then take a step back and verify your assumptions.

We assume the download succeeded, so we should be able to find the module in a "not installed" state. Verify with drush:

```
drush pm-list | grep "sar"

```

We assume drush handled the download properly, try again with another folder. Verify with drush:

```
drush dl sar --destination="sites/all/modules"

```

**Solution:**

I assumed, since you were asking about enabling, that this was a site module. After downloading it on my local system I see that this is a drush command package, and that `[user]/.drush/sar` is correct. Verify the module does not need enabled and is already working with:

```
drush help sar

```

---
Tags: 7, drush
---


title: Unable to install Cart with ubercart

text:
# Question
Title: Unable to install Cart with ubercart
I'm trying to install Cart form ubercart after an uninstall:

I'm getting the following message what can I do?

> Unable to install Cart, image.style.uc\_cart, uc\_order.status.abandoned already exist in active configuration.

# Answer
This can be done with drupal console, you can find it here: https://hechoendrupal.gitbooks.io/drupal-console/content/en/index.html

The command to use is this: drupal module:install --overwrite-config

Just install drupal console and use the command.
> 1 votes

---
Tags: 8, ubercart, installation
---


# Question
Title: Add and/or option to Drupal Views' Contextual Filters?
How can I add the "and/or" option to Drupal Views' Contextual Filters panel? I added it to Filter Criteria, but I can't seem to get it for Contextual Filters.

# Answer
You can achieve your requirement by installing Views Contextual Filters OR module. By default contextual filters are in AND condition.

> The module provides a views plugin which modify query to support OR conditions for contextual filters.
> 1 votes

---
Tags: 7, views
---


# Question
Title: What's a good way to prepopulate web form fields with data from an external database?
What might be a sane approach to prepopulating web form fields using data from an external database on the fly? This is my scenario: there is a form that we need clients to fill out, but we already have a lot of the client's information in our database. So to make it easier on the client, we want to fill out the form as much as possible before sending it to them to fill out the rest. I'm using the webform module on our Drupal 7 site, but all the data needs to come from our other database. Ideally, there would be either a page or just a field where I can select the client ID. After choosing the client ID, other fields would use that ID to pull information like contact name, address, etc. Is there a reasonable way to do this?

# Answer
I ended up figuring out what to do (thanks bgrobertson). I decided to post the information on my blog instead of just putting it here.

Connecting To External Databases In Drupal 7
> 0 votes

# Answer
You would need to expose an API from your external database. If the external database is also a Drupal 7 site, you could use the RestWS module to do this (https://www.drupal.org/project/restws).

Once you have your data exposed via api, you would then have to connect to the api on the client's site, and you could auto populate some hidden fields via an ajax call when they select the ID. You would want to do this in a custom module.
> 0 votes

---
Tags: webforms
---


# Question
Title: A question about Drupal Books and assigning classes to the body based on last viewed book
I have client site with a few different books in it. There are also some basic pages and other nodes that are not within the books. When you are in the first book the sidebar is blue, when you are in the second book the sidebar is green and the the third has an orange sidebar. This is controlled by a class that is applied to the body from a field in the book module.

Currently, when you access a global page (meaning a page or view outside a book) the sidebar color is a default color. But the client wants these global pages' sidebar color to stay the same as the last viewed book and not switch to a different color until a new book is viewed.

I am not even sure how to begin to go about doing this and am looking for ideas.

Thanks

# Answer
> 1 votes
Thanks to No Sssweat's comment my solution for this was to use Jquery to look for the body class that controls the sidebar color then use jQuery.cookie (already packaged in Drupal just need to make sure it loads on every page) to set a cookie with that value. Then if a page visited that doesn't have the body class that indicates it was a book and therefore also doesn't have the color class then I had jQuery .addClass to add the cookie value to the body element.

---
Tags: nodes
---


title: Where are the comments stored?

text:
# Question
Title: Where are the comments stored?
I need to know where the mandatory comment that we have set up in the Voting API module is stored. I can find the scores in the voting\_api table, but not those comments.

I need to do a query in a module to get this information. How can I achieve this?

# Answer
> 0 votes
they were stored in the content of a specific node type, with custom code.

---
Tags: 7, rating
---


# Question
Title: Custom module implementation for menu items as JSON
Through the use of a Drupal 8 custom module for the purpose of providing the menu items/menu structure as a JSON resource, I have encountered a problem which I'm hoping someone will have an answer or lead for.

The output to the extent that it's currently functioning appears in JSON format, the structure following the same as the defacto menu system outputting title, weight, and whether the item is active.

```
    [
  {
    "title": "Vehicles",
    "url": {},
    "weight": "1",
    "active": true
  },
  {
    "title": "Automotive Parts",
    "url": {},
    "weight": "2",
    "active": true
  },

```

The URL is not displayed, even though in Drupal there are paths entered for the items. I have made several attempts at browsing the Drupal 8 documentation to search for answers about URL and menu classes. Currently, the relevant code responsible for the output is this one.

```
public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$result = array();

foreach ($tree as $element) {
  $link = $element->link;

  // if ($link->getUrlObject()->isExternal() == true) {
  //   $route = $link->getUrlObject();
  // }
  // else {
  //   // $route = $link->getUrlObject()->getInternalPath(); //this is breaking the module because apparently there are no "internal routes".
  // }
  dpm($link->getUrlObject());
  if ($link->isEnabled() == true) {
     array_push($result, array(
      'title' => $link->getTitle(),
      'url' => Url::fromUri($link->getUrlObject()->toUriString()),
      'weight' => $link->getWeight(),
      'active' => $link->isEnabled()
    )
  );
 }
}
return new JsonResponse($result);

```

}

How can I make the `'url' =>` part of the code output the path entered in Drupal for that menu item?

# Answer
> 0 votes
You'll want to use this kind of implementation based on the Alias Manager service.

```
<?php
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode);
?>

```

Details and a further explanation can be found on D.O https://www.drupal.org/node/1853148

If you'd be willing, I'd also like to see the full code for that resource.

---
Tags: services, 8
---


# Question
Title: Cannot add files to a specific folder using file resumable module
I recently moved to a droplet at DigitalOcean. Because they have small hdd's I added 20GB extra space to my droplet.

Because my resources does not fit neither on extra space or on the server's hdd I split the

> sites/default/files

folder by creating 2 symlinks for 2 folders that hold around 15GB pointing to the extra space.

Now if I try to create a node of the type that should put the files in the extra space I get this error:

```
The upload directory public://xxx for the file field field_fisiere_audio could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.

```

All the folders where I upload files have 700 rights. The owner and group is www-data.

Any idea why do I get this? Is this because of the symlinks? Is there any other way of splitting the files folder?

I also tried with 777 and is not working either.

# Answer
Because I was pressed by time I made the following changes:

1 I moved the whole sites folder to the extra space (after I bought some more)

2 I created a symlink to sites

Everything seems to be working ok.

My idea is that inside files drupal can't handle symlinks.
> 0 votes

---
Tags: files
---


# Question
Title: How to refer to a custom field in a node template?
For the basic page content type I added a custom boolean field called field\_login\_required.

In my node template node--page.html.twig I have

```
    <h2>{{ title }}</h2>
    {% if content.field_login_required %}
        {% if user == 0 %}
        <p class="must-login">You must be logged in to view this page <a href="/user">Please click here to login</a></p>
        {% else %}
            <p>{{ content.body }}</p>
        {% endif %}
    {% else %}
        <p>{{ content.body }}</p>
    {% endif %}

```

However content.field\_login\_required is null no matter whether the checkbox is checked or not. To test what was available I used

```
{{ dump(content|keys) }}

```

However the result of this is

```
array (size=1)
  0 => string 'body' (length=4)

```

field\_login\_required is omitted. Is there anyway to refer to a custom field in a node template?

# Answer
The issue occurred because

```
{{ content.field_login_required }}

```

was used. Node should be used in place of content. The proper code is

```
{{ node.field_login_required.value }}

```
> 1 votes

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


# Question
Title: Print field from reference of reference (node)
I use the module "entity reference" and I ave "Inline Entity Form" in the node. The first reference has another reference inside. In total there are 3 nests, a grandfather, a father and son. In node.tpl the first parent node how can I print a field of his nephew?

```
- Node.1
-- Ref. Node.2
--- Ref. Node.3

```

I want to print a Node.3 field's in Node.1

Thanks so much!

# Answer
> 0 votes
There is always more than one way to solve a problem in drupal. How easy those ways are is up for debate, but they exist.

You could:

1. Make a view with those reference fields as relationships and a nid context filter that would recognize the Node.1 end of the relationships. Set this view to have a block display, and A) put the block on the page with a context or B) summon the view to be rendered by name in your tpl. Or with the function views\_embed\_view
2. Make database fetches or entity field queries directly in your node.tpl.php. This is uncouth, as such logic should not be put in the theme layer, but functional.
3. Forget about node.tpl.php entirely and do this in panels. I'm pretty sure it supports using referenced fields.

The `echo $view->render('block_view');` method would be my suggestion to you. Views is a very powerful module, has built in theming overrides (and more if you want more tpls) and can do all sorts of rewrites and manipluations while laying things out for you. Add the ability to conjure it's database bending powers from your tpl with just 6 lines of code, and it is stupendous.

---
Tags: theming, entities
---


# Question
Title: Renaming a content type during migration
I am migrating a Drupal 6 site to Drupal 8. On the Drupal 6 site I have a content type called *book\_page* but would like it be called *faq* on the new site.

I set the `default_bundle` to faq in my yml file but it still migrates as book\_page.

Here is my yml file:

```
uuid: a67dbd6f-416c-44c0-9698-05ec3bb3c5a9
langcode: en
status: true
dependencies: {  }
id: upgrade_d6_node_book_page
migration_tags:
  - 'Drupal 6'
migration_group: d6_migrate_group
label: 'Nodes (book_page)'
source:
  plugin: d6_node
  node_type: book_page
process:
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  body/format:
    plugin: migration
    migration: upgrade_d6_filter_format
    source: format
  body/value: body
  body/summary: teaser
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_image:
    plugin: d6_cck_file
    source: field_image
  field_upload_files:
    plugin: d6_cck_file
    source: field_upload_files
destination:
  plugin: 'entity:node'
  default_bundle: faq
migration_dependencies:
  required:
    - upgrade_d6_user
    - upgrade_d6_node_type
    - upgrade_d6_node_settings
    - upgrade_d6_filter_format
  optional:
    - upgrade_d6_field_instance_widget_settings
    - upgrade_d6_field_formatter_settings
    - upgrade_d6_upload_field_instance

```

Anyone have an idea what I am doing wrong?

**Update:**

I have also tried adding the following under process under each of my node yml files?:

```
type:
  plugin: default_value
  value: faq

```

I wonder if the All node types are created in ....node\_type.yml?

# Answer
> 5 votes
As you've figured out, modifying the d6\_node-based migration affects how the *content* of a given node type is migrated, but does not affect how the actual node type itself is migrated - that is done in d6\_node\_type. To rename the types themselves in migration, while you could modify the source query as you did, it's simpler to modify the .yml to remap values. In upgrade\_d6\_node\_type.yml, you can replace

```
process:
  type: type
  name: name

```

with

```
process:
  type:
    plugin: static_map
    bypass: true
    source: type
    map:
      story: post
      book_page: faq
  name:
    plugin: static_map
    bypass: true
    source: name
    map:
      story: post
      'Book Page': Faq

```

# Answer
> 0 votes
I was able to perform this by creating a custom module and adding a custom source plugin to modify the query.

*custom\_migration/src/Plugin/migrate/source/d6/CustomNodeType.php*

```
<?php

namespace Drupal\custom_migration\Plugin\migrate\source\d6;

use Drupal\node\Plugin\migrate\source\d6\NodeType;

/**
 * Drupal 6 Node types source from database.
 *
 * @MigrateSource(
 *   id = "custom_node_type"
 * )
 */
class CustomNodeType extends NodeType {
  /**
   * Override the query() method, and provide a custom query that selects just
   * the node types you want.
   */
  public function query() {
    // Our custom query returns only the node types we want and renames them.
    $query = $this->select('node_type', 't');
    $query->fields('t', array(
        'module',
        'description',
        'help',
        'title_label',
        'has_body',
        'body_label',
        'min_word_count',
        'custom',
        'modified',
        'locked',
        'orig_type',
      ));

    // Rename content types.
    $query->addExpression("
      CASE
        WHEN t.type = 'story' THEN 'post'
        WHEN t.type = 'book_page' THEN 'faq'
        ELSE t.type
      END
    ", 'type');

    // Rename content type names.
    $query->addExpression("
      CASE
        WHEN t.name = 'Book Page' THEN 'Faq'
        WHEN t.name = 'Story' THEN 'Story'
        ELSE t.name
      END
    ", 'name');

    // Exclude content types you don't want to migrate.
    $query->condition('t.type', array('forum', 'program', 'show', 'webform', 'homepage_slide'), 'NOT IN');
    $query->orderBy('t.type');

    return $query;
  }
}

```

---
Tags: 8, migrations
---


# Question
Title: Setting Drupal Image Field via Services, and image won't attach to node?
I'm uploading an image via my iOS app and setting a created node's image field to the image through Drupal Services. Everything appears to be correct (see uploaded photo from 'Recent Logs'). However when I navigate to the node, the image field is empty? Any idea as to why this might be? All help is appreciated, thanks.

# Answer
I'm late to the party, but I think you might be encoding the image wrongly. You need base64 encoding. Here is how encoding works on my end with Python 3.5.2:

```
import os, base64
size = os.path.getsize(filename)
filesize = os.stat(filename).st_size
filemime = mimetypes.guess_type(filename)
fd = open(filename, 'rb')
image_data = base64.b64encode(fd.read())
fd.close()

```
> 0 votes

---
Tags: 7, services
---


# Question
Title: Drupal 8, how fix the error 'class not found' for custom class ?
Its a php issue but maybe I missing a 'Drupal 8' thing ?

I have this custom module :

```
> mymodule (directory)
    > mymodule.module
    > src (directory)
        > myclass.php
        > myclassinterface.php

```

In myclass.php, I have :

```
namespace Drupal\mymodule\src;

Class myclass implements myclassinterface{
    ...
}

```

In my mymodule.module, I have :

```
use Drupal\mymodule\src\myclass;
...
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    $test = new myclass();
    // or $test = new Drupal\mymodule\src\myclass(); // same error, class not found
}

```

And when I load a page via my browser, I get a blank page and apache log tell me the class 'Drupal\mymodule\src\myclass' not found.

I don't understand..where is my mistake ?

# Answer
> 7 votes
Drop the "src" from your namespace and use statements. Wipe the cache after making that change.

---
Tags: 8
---


# Question
Title: How do change address field titles to another language in Ubercart?
In D7 you could just rename the title and type them in a different language.

But in D8, there is no such option like in D7.

# Answer
Installing the Ubercart translation solves the issue. Import the file using the `Interface Translation` module.
> 0 votes

---
Tags: 8, ubercart
---


title: Customize Search Form Block Text

text:
# Question
Title: Customize Search Form Block Text
I'm attempting to customize the search form block. I'd like to be able to change the search submit button, by either changing the text, or turning it into an icon and other various changes.

I assumed I'd be able to make these changes within a template, but the default block--search-form-block.html.twig only contains

```
{%
  set classes = [
    'block',
    'block-search',
    'container-inline',
  ]
%}
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}
</div>

```

I don't see anyway I can change anything such as the submit text. Is there any way to make direct changes to the search form block?

# Answer
> 0 votes
try something like

```
#search-block-form input[type="submit"] {
background-color: white;
padding: 15px 25px;
color: black;
border-radius: 0px;
border: 1px grey dotted;
background-image: url(http://cashbin.win/sites/default/files/favicon.ico);
background-size: 30px 30px;
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
}

```

This is an example obviously replace the image and/or border, color, background, position, and padding options.

Add this into you /sites/all/themes/**CURRENT\_THEME**/css/style.css

Hope this helps, God Bless!

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


# Question
Title: Request a new password mail without any content inside of the mail.
I got a problem. When I want to request a new password due to password forgotten, the system definitely send a mail to my email address. But, this mail is without any content inside. I check the Configuration-\>People-\>Accounting Settings. I already setup all the content. But, I can't get any content. Hope someone can help me. Thanks.

# Answer
admin/config/people/accounts Check this section make sure this is not empty.
> 0 votes

# Answer
I got fixed. The problem is on "wysiwyg" and "mimemail" the both modules. I adjust wysiwyg configuration. Here is my mimemail setting and I use advanced HTML. Then, I go into wysiwyg configuration. The both configuration I show the below pictures. Thanks.
> 0 votes

---
Tags: users, emails, authentication-authorization
---


# Question
Title: Twig template suggestions for paths such as page--node--page-url
using D8, I'd like a twig template for a page I've created based off the path of the page and not *`node %`*. I look in my twig suggestions and all I see are:

```
page--node--8.html.twig
page--node--%.html.twig
page--node.html.twig
page.html.twig

```

As template suggestions. However, as I'm working in multiple environments and don't know what the node number will be when I actually create this page I'd like to just base it off the path I've set for the page which is '404-error'. Anyone know how to do that?

I'm imagining something like `page--node--404-error.html.twig`

However that doesn't seem to work (I tried it).

# Answer
> 2 votes
You can add suggestions for the page template in a hook:

**mytheme.theme:**

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
}

```

This is an example how to add a suggestion with the path for any page. You can narrow it down to the pages you are interested in and if necessary check for paths that are too long.

---
Tags: theming, 8, path-aliases
---


# Question
Title: Two-factor authentication with code sent to email
I'd like to ask you if there are any possibilities of a two-factor authentication with authentication code sent to email. I've found TFA module which can send an SMS, and according to their documentation, also email:

> The TFA code can be sent out over mobile phone SMS (recommended) or via email.

but I haven't found any settings for email, it seems they just provide "API to customize the communication chanel". I've also found Rules module, which could be maybe used combined with other module.

Are there any other possibilites how to do the two-factor authentication with email?

# Answer
> 3 votes
It looks like the recently posted OTP module supports emailing of its one-time passwords. It's still a sandbox project though and I haven't tried it myself.

It shouldn't be too difficult to add email support to the TFA module you mentioned. If you're interested in getting your feet wet with Drupal development, it might make a good starter project.

I suspect you would have to do some custom development to get Rules to handle generating of the codes. Either of the two options above would probably be quicker.

Maybe it's just an academic point, but keep in mind that by emailing the token, you're straying a bit from the idea of two-factor authentication, which entails "a knowledge factor ("something the user knows"), a possession factor ("something the user has")." The line gets a bit fuzzy already though, when you talk about logging in from your phone or forwarding text to a computer via services like Google Voice.

# Answer
> 0 votes
Was looking for the same security but without SMS/e-mail burden.So I developed the module and android app which will extend the login screen to 2-step authentication process and after successfully logged in with username/password in the second form user must enter TOTP code generated using module's companion android app Drulapp.

Module is not published yet at D.O but you can install module from https://drulapp.org .

---
Tags: rules, emails, users
---


title: Clear cache routing.

text:
# Question
Title: Clear cache routing.
I follow topic to create dynamic routes. Examples i have a form, when user click submit form. new route will be created. It's working. But after clear cache by UI (or function drupal\_flush\_all\_caches()). I want this auto but don't want use drupal\_flush\_all\_caches() because it's very slow. So maybe i use other function to clear cache routing.

# Answer
Use can use service **router.builder** with method **rebuild()**. Paste it's in function submit form:

```
\Drupal::service("router.builder")->rebuild();

```
> 3 votes

---
Tags: 8, routes
---


title: Best way to do geo redirection?

text:
# Question
Title: Best way to do geo redirection?
I am working on a multilingual Drupal 7 site. I've been asked to set up an automatic redirect based on the user's location. I've tried the geo\_redirect module but it does not work with internal URLs because it creates a redirect loop.

My site uses paths to switch languages. For example the German homepage is example.com/de.

It seems like there are various modules that say they can do this but some are just dev versions, some require a subscription to a geo-location service, and some like to populate the Drupal database with 200MB of geoIP data (huhhh???).

Here is an example of what I need...

1. User located in Germany goes to example.com
2. Website detects that they are located in Germany
3. User gets redirected to example.com/de (the German homepage)
4. If user in Germany goes to any URL with /de in it then no redirect occurs

Just wondering if anyone has any experience with this and how they went about doing it.

Thanks!

# Answer
I would use Smart IP module.

> Smart IP identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored in session variable ($\_SESSION) with array key 'smart\_ip', Drupal $user-\>data object with array key 'geoip\_location' in Drupal 6 and 7 and user data service using the parameters 'smart\_ip' as module and 'geoip\_location' as name in Drupal 8 of the user but optionally it can be disabled (by role) at Smart IP settings page. Other modules can use the function smart\_ip\_get\_location($ip\_address) in Drupal 6 and 7 and \Drupal\smart\_ip\SmartIp::query($ipAddress) in Drupal 8 that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.

You can get the user location in different ways using this module.

```
<?php
$smart_ip_session = smart_ip_session_get('smart_ip');
if ($smart_ip_session['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

```

Or

```
<?php
if ($_SESSION['smart_ip']['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

```

Now, in the `Theme_preprocess_html` function of your theme in the `template.php` file, use the above codes to check if the user is in a right place. Create `template.php` file in your theme and use this function:

```
function themeName_preprocess_html(&$variables){
{
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = arg(1); //it returns the /de or any language
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}

```

If the default provides the language code, it works well but if not, you need to handle that case. For example if the default language is English and the `/en` is not coming after `example.com`, then you need to check if `arg(1) == 'en'`. It is easy to do.

---

# update

To get the user language use this code

```
global $language;
print $language->language;

```

So your code will be

```
function themeName_preprocess_html(&$variables){
{
      global $language;
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = $language->language;;
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}

```
> 1 votes

---
Tags: 7, redirection
---


title: Table with total per month

text:
# Question
Title: Table with total per month
I created a table with operations sorted by date. How to display a second array with the total transaction per month ?

I want to show by example the total in September 2016, the total amount of August 2016 ...

Table should display one line per month with the total amount of transactions.

The same month are not grouped :-(

# Answer
> 0 votes
I would recommend trying to use Views Aggregator Plus

See Example here: https://www.drupal.org/node/2361413 It says a similar thing would work(aggregate and group by column).

God Bless.

# Answer
> 0 votes
Maybe you can convert your date field in a PHP format to display 'month YEAR' (like *august 2016*) and then use grouping on the month + sum on the money field to aggregate on the month. As Sammy7 said Views Aggregator Plus might give you an handy option.

---
Tags: views
---


# Question
Title: Output node.type in page.html.twig gives "EntityReferenceFieldItemList cannot be printed"
Not sure if this is a bug, but I wanted to add some debug into an HTML comment in my `page.html.twig` file. I added `<!-- type={{node.type}} -->` but I get:

```
Uncaught PHP Exception Exception: "Object of type Drupal\Core\Field\EntityReferenceFieldItemList cannot be printed." at /www/cn8/core/lib/Drupal/Core/Template/TwigExtension.php line 443

```

It took me a while to track down since I was sure this would work. Shouldn't EntityReferenceFieldItemList have a toString() function for this purpose?

# Answer
> 4 votes
`node.type` is a reference to the node type entity. You can get the id of the content type with `target_id`, as you have mentioned in the comment. For debugging this might be OK, but most times you want to get the label, which is nicely formatted and translatable:

```
{{ node.type.entity.label }}

```

---
Tags: theming, 8
---


title: How to put my FB code in a block?

text:
# Question
Title: How to put my FB code in a block?
Im noob in Drupal and I don't know how can I put the FB code for display the last post in a block. I'd create a block with php code text format, but doesn't work, the block does not render the code. This is the code from FB, if I put it into a plain html file it works fine

```
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.7";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<div class="fb-page" data-href="https://www.facebook.com/mysupersite" data-tabs="timeline" data-width="320" data-height="450" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"></div>

```

How can I put this into a block? I'd created a block--fb.tpl.php cloning the block.tpl.php and pasted the code but this doesn't work either. This is for not use the FB module because I should create an app and FB request my data and I don't want an app, just render the last post of the profile can someone give me some gide with this? Thank you so much for your help

# Answer
if you using ckeditor firstPut your block **text format** on `FULL HTML` then click on `soruce` and finally paste your markups there.
> 6 votes

# Answer
An alternative way if you love coding...

You can create module for fb add block.

module name : custom

```
function custom_block_info() {
  $blocks = array();
  $blocks['add_fb'] = array(
    'info' => t('Add fb'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implement hook_block_view().
 */
function custom_block_view($delta = '') {
  $block = array();
  switch ($delta) {
      case 'add_fb':
        $block['content'] = t('<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.7";
  fjs.parentNode.insertBefore(js, fjs);
}(document, "script", "facebook-jssdk"));</script>

<div class="fb-page" data-href="https://www.facebook.com/mysupersite" data-tabs="timeline" data-width="320" data-height="450" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"></div>');
      break;
  }
  return $block;
}

```

Now you can see a block on "admin/structure/block" named as "Add fb". Place the block where ever you want.
> 6 votes

---
Tags: blocks
---


# Question
Title: How to translate "Sort by" region of the KickStart commerce into Russian?
How to translate "Sort by" region of the KickStart commerce into Russian?

Need to completely translate KickStart commerce. Are there any ways except translating the core and searching for .po for an every single left module?

# Answer
> 0 votes
To translate "Sort by" region:

1. Go to the "Display products" view edit at path admin/structure/views/view/display\_products/edit
2. In edit view page of the view you will find "Edit View Name/Description" dropdown menu on the right, from dropdown select "Translate View".

On the translate page, you will get fields to translate view stings.

---
Tags: commerce
---


# Question
Title: entity_metadata_wrapper - how to remove one item from entity reference field
I have a entity reference field that holds relations to multiple nodes. I have to remove one item programmatically based on nid. Normally to remove item I've just set it to null like this:

```
$wrapper->field_foobar = NULL;

```

But entity reference is a list, so I have to know delta for element to do something like this:

```
$wrapper->field_foobar[$delta] = NULL;

```

So I have content\_id and target\_id what should I do to find delta? I know it's possible to do it with simple SQL query, but I gues there should be some way to do that with entity metadata .

Any sugestions?

I'm on Drupal 7 of course.

# Answer
Use unset instead, followed by a save:

```
unset($wrapper->field_foobar[$delta]);
$wrapper->save();

```

To find the delta, you can iterate over the collection and look for the node id:

```
foreach($wrapper->field_foobar as $delta => $item)  {
  if ($item->nid->value() == $my_id) {
    unset($wrapper->field_foobar[$delta]);
    $wrapper->save();
    break;
  }
}

```
> 6 votes

# Answer
You could create a function for it, like this:

```
function remove_entity_reference_from_field(&$field, $reference_id){
  $field = array_filter($field, function($value) use ($reference_id) {
    return ($value['target_id'] != $entity_id);
  });
}

```

Usage:

```
$node = node_load(98765);
remove_entity_reference_from_field($node->field_foobar[LANGUAGE_NONE], 12345);
node_save($node);

```
> 0 votes

---
Tags: entities
---


title: Features auto delete field

text:
# Question
Title: Features auto delete field
I've been using Feature to provision changes between my DEV, STAGING and LIVE sites.

What I'm finding is when I make a field redundant on a node type on my DEV site, features does not automatically delete is on my STAGING site.

For example: I originally had a field called **Key Contact** in my Basic Page node type. I created a feature which I uploaded to my STAGING site, the Key Contact field was created and it worked fine.

However, that same field is now redundant. I have deleted it on my DEV site. I re-created the Feature and uploaded to my STAGING site.

**The problem is the Key Contact field still exists on the STAGING version of my website.**

*Can anyone give me some direction to get Features to not just create new fields but remove fields I have deleted on DEV - so I don't have to delete a lot of fields manually on both STAGING and eventually the LIVE site?*

# Answer
> 1 votes
As declared in https://www.drupal.org/node/649298#comment-7710069 there won't be any such support in Features module itself. In the same issue, there is also relevant answer in https://www.drupal.org/node/649298#comment-10219951:

> You can instead add a hook\_update\_N function to a custom module and delete the field with code (see field\_delete\_field).

This should be used in `my_feature.install` file. Note that if you go this way, you will probably need to add something like

```
function my_feature_features_export_files($module_name, $export) {
  if ($module_name == 'my_feature') {
    return array('my_feature.install' => array('file_path' => 'sites/all/modules/my_feature/my_feature.install'));
  }
}

```

to you `my_feature.module` file. This ensures that `my_feature.install` file is added to feature on any further export.

---
Tags: 7, entities, features
---


# Question
Title: How to use prepareKey() for the Migrate module
I am trying to do write a migration class extending the Migrate module. The migration will be from an XML file so I will want to extend the `XMLMigration` class. Based on the Migrate modules wine.inc example, I'm going to have to something like this:

```
class WineProducerXMLPullMigration extends XMLMigration {
 public function __construct($arguments) {
  ....
  $item_xpath = '/producers/producer';  // relative to document
  $item_ID_xpath = 'sourceid';          // relative to item_xpath

  $this->source = new MigrateSourceXML($items_url, $item_xpath,
                                       $item_ID_xpath, $fields);
  }
}

```

My issue is that my xml doesn't have any unique ID per row, and therefore I can't really pass a `$item_ID_path`. I read this post https://www.drupal.org/node/1444356#comment-6974360 and found that the prepareKey() function is supposed to be used for this purpose, however as far as I can tell, you don't ever call this directly, and its called after this class is finished processing. This being the case, I'm not sure what I should be passing in `$item_ID_xpath` and it is a required field.

# Answer
> 0 votes
You can set the $item\_ID\_xpath to something that does exist in the XML, for example 'name'

Then inside your migration class, you can use the **prepareKey** method to generate an ID

```
public function prepareKey($source_key, $row) {
  $row->glid = crc32($row->xml->name);
  $key['glid'] = $row->glid;
  return $key;
}

```

I am using crc32() to generate an ID from a string, but I have no clue whether that is smart or not, so use at own risk.

Now that you have an ID ('glid' in the example) you use in the mapping:

```
$this->map = new MigrateSQLMap($this->machineName, array(
  'glid' => array(
    'type' => 'varchar',
    'length' => '255',
    'not null' => TRUE,
    'description' => 'id generated from a string'
  ),
), MigrateDestinationNode::getKeySchema()
);

```

Dont forget to deregister the migration if you change this schema.

---
Tags: migrations
---


# Question
Title: How to find which content type is using which context?
How to find which content type (`abc`) is using which context? As I do have around 30 contexts in my site.

Is there a way to find which context is using content type (`abc`)?

# Answer
Here are some module suggestions that may help get you closer to find the exact answer to your question:

* # Context Inspector block provided by the Devel module

If you use the Devel module you'll have a "Context Inspector" block. You can place that block in a region on a page and then see the current contexts output via Krumho.
* # Devel Catcher module

To enhance your "debugging" experience (hm, hm ...), there is also the Devel Catcher module, which has Devel as a module dependency.

Here is an excerpt from its project page (why you may want to consider this module):

> ... aggregates or "catches" all development debug info into one easy to access place.
>
> Similar in style to Firebug or Chrome's Inspector. Devel Catcher intercepts common debug info into a tabbed interface as opposed to having to assign debug blocks to a region or dumping the output at the end of your HTML document.
>
> Currently Devel Catcher can catch the query log from the Devel module, node access rules from the Devel Node Access module and the context inspector block from the Context UI module.

So by using (repeating) this approach for a page of each of your content types, you might be able to find out which content type is using which context, no?
> 1 votes

# Answer
May be it helps someone.

```
$active_contexts = array_keys(context_active_contexts());
foreach($active_contexts as $active_context) {
  print $active_context;
}

```
> 1 votes

---
Tags: 7, nodes
---