# Question
Title: How to get the pre-save version of a field collection in rules
I have a node with a field collection called itinerary, and that field collection contains a user entity reference called traveler. The node can have unlimited itineraries and an itinerary can have unlimited travelers.

I'm trying to make a rule to react when travelers are added.

My first thought was

1. Loop through the node\_unchanged:itinerary field
2. Loop through the travellers list within each itinerary, building a list of pre-save travellers.
3. Loop through the node:itinerary field
4. Loop through the travellers list within each itinerary, building a list of post-save travellers.
5. Loop through the pre-save travellers, removing each one from the post-save traveler list, then take action on the list of new travelers that results.

Unfortunately the new traveler list is always empty, the list of pre-save and post-save travellers are always the same, and when I look at the ids (UUID, field\_collection ID, and revision id) of the itineraries in node and node-unchanged, they are identical. So it seems as far as I can tell, that rules has no access to field collection state before the node was saved.

Is this the case? Is my only solution to populate a hidden traveler list at the end of each save so I can compare that list with what is being saved? It seems like there must be a better way.

This question is similar to How to retrieve data in a field collection within a Rules Condition?, but that question also doesn't have an answer, and I don't feel like the question is entirely clear.

*Update:* I was asked for a screenshot of my rules setup, but that is pretty long, so I'll include an export of the rule first. This includes some rules just for comparing the values and trying to understand what is happening. Here is the result of the show messages rules that show field collection ID info:

```
New Entry: UUID: afe4e63b-637f-402b-b730-5fcac4d5c809   Field collection item ID: 20    Revision ID: 471
Old Entry Itinerary ID: Field collection item UUID: afe4e63b-637f-402b-b730-5fcac4d5c809 Field collection item ID: 20 Revision ID: 471

```

And here is the rule export:

```
{ "rules_react_to_added_travellers" : {
    "LABEL" : "React to added Travellers",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "mission_approval" ],
    "REQUIRES" : [ "rules", "rules_data_transforms" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Mission Request", "type" : "node" },
      "node_unchanged" : { "label" : "Original Mission Request", "type" : "node" }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "mission_request" : "mission_request" } }
        }
      },
      { "node_is_of_type" : {
          "node" : [ "node-unchanged" ],
          "type" : { "value" : { "mission_request" : "mission_request" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E", "value" : [ "" ] },
          "PROVIDE" : { "variable_added" : { "traveller_list" : "Traveller List" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E", "value" : [ "" ] },
          "PROVIDE" : { "variable_added" : { "traveller_list_unchanged" : "Original Traveller List" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Ctext\u003E" },
          "PROVIDE" : { "variable_added" : { "text_traveler_list" : "New Traveler List (Text)" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Ctext\u003E" },
          "PROVIDE" : { "variable_added" : { "new_traveler_names" : "New Traveller Names" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Ctext\u003E" },
          "PROVIDE" : { "variable_added" : { "old_traveler_names" : "Old Traveler Name" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-mr-fc-itineraries" ] },
          "ITEM" : { "current_itinerary" : "Current Itinerary" },
          "DO" : [
            { "drupal_message" : { "message" : "New Entry:  UUID: [current-itinerary:uuid]\tField collection item ID: [current-itinerary:item-id]\tRevision ID: [current-itinerary:revision-id]" } },
            { "LOOP" : {
                "USING" : { "list" : [ "current-itinerary:field-mr-fc-travelers" ] },
                "ITEM" : { "current_traveler" : "Current Traveler" },
                "DO" : [
                  { "list_add" : {
                      "list" : [ "traveller-list" ],
                      "item" : [ "current-traveler" ],
                      "unique" : "1"
                    }
                  },
                  { "list_add" : {
                      "list" : [ "new-traveler-names" ],
                      "item" : [ "current-traveler:name" ],
                      "unique" : "1"
                    }
                  }
                ]
              }
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node-unchanged:field-mr-fc-itineraries" ] },
          "ITEM" : { "current_old_itinerary" : "Current Old Itinerary" },
          "DO" : [
            { "LOOP" : {
                "USING" : { "list" : [ "current-old-itinerary:field-mr-fc-travelers" ] },
                "ITEM" : { "current_old_traveler" : "Current Old Traveler" },
                "DO" : [
                  { "list_add" : {
                      "list" : [ "traveller-list-unchanged" ],
                      "item" : [ "current-old-traveler" ],
                      "unique" : "1"
                    }
                  },
                  { "list_add" : {
                      "list" : [ "old-traveler-names" ],
                      "item" : [ "current-old-traveler:name" ],
                      "unique" : "1"
                    }
                  }
                ]
              }
            },
            { "drupal_message" : { "message" : "Old Entry Itinerary ID: Field collection item UUID: [current-old-itinerary:uuid] Field collection item ID: [current-old-itinerary:item-id] Revision ID: [current-old-itinerary:revision-id]" } }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "traveller-list-unchanged" ] },
          "ITEM" : { "current_traveler" : "Current Traveler" },
          "DO" : [
            { "list_remove" : { "list" : [ "traveller-list" ], "item" : [ "current-traveler" ] } }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "traveller-list" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "list_add" : {
                "list" : [ "text-traveler-list" ],
                "item" : [ "list-item:name" ],
                "unique" : "1"
              }
            }
          ]
        }
      },
      { "implode" : {
          "USING" : { "input_list" : [ "text-traveler-list" ], "gluez" : ", " },
          "PROVIDE" : { "combined_text" : { "combined_text" : "Combined text" } }
        }
      },
      { "implode" : {
          "USING" : { "input_list" : [ "new-traveler-names" ], "gluez" : ", " },
          "PROVIDE" : { "combined_text" : { "new_names" : "New Names" } }
        }
      },
      { "implode" : {
          "USING" : { "input_list" : [ "old-traveler-names" ], "gluez" : ", " },
          "PROVIDE" : { "combined_text" : { "old_names" : "Old Names" } }
        }
      },
      { "drupal_message" : { "message" : "Calculated New Travellers: [combined-text:value]  Original Travelers: [old-names:value] New Travelers: [new-names:value]" } },
      { "component_rules_take_a_list_of_users_and_notify_their_area_leaders" : { "traveler_list" : [ "traveller-list" ], "node" : [ "node" ] } }
    ]
  }
}

```

This component is invoked by a rule triggered on Event "After updating existing content of type Mission Request". It runs two other rules that evaluate other thing about the state of the mission request, send out any necessary notifications, and then pass node and node\_unchanged to this component.

That looks like this:

```
{ "rules_mission_request_is_updated" : {
    "LABEL" : "Mission Request is updated",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "mission_approval" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update--mission_request" : { "bundle" : "mission_request" } },
    "IF" : [
      { "node_is_published" : { "node" : [ "node" ] } },
      { "NOT data_is" : { "data" : [ "node:field-mr-approval-status" ], "value" : "3" } },
      { "NOT data_is_empty" : { "data" : [ "node:field-mr-approval-status" ] } }
    ],
    "DO" : [
      { "component_rules_get_added_budgets" : { "node" : [ "node" ], "node_unchanged" : [ "node_unchanged" ] } },
      { "component_rules_react_to_removed_budgets" : { "node" : [ "node" ], "node_unchanged" : [ "node_unchanged" ] } },
      { "component_rules_react_to_added_travellers" : { "node" : [ "node" ], "node_unchanged" : [ "node_unchanged" ] } }
    ]
  }
}

```

# Answer
**Note**: In the case where your field collection is a multi-value field and you need to compare the contents of all field collections, checking the contents of single field collection instances isn't useful. Effectively the real answer to your question is probably that for what you want to do, the only possible solution is keeping a field to check against, but if You want to check single field collection instances at a time, the "After updating an existing field collection item" trigger is what you need.

Processing field collections is always fun, and even more fun to do so with the Rules module. My favorite sample to refer to (for actually doing so) is contained in part 1 of my answer to "How to iterate over all field collection items in an eMail body using Rules?".

However to answer your question, I think you're using the wrong technique (sorry ...). What you should do to "*react when travelers are added*" (as in your question), is to rework (simplify) your Rules Actions and use a technique which is similar to what is explained in my answer to "How to check with Rules if a new element has been added to a list in a node?".

However, your question is about field collection items, which is a slightly different story ... as indicated also in comment #2 of the issue about "Field Collection does not work with Rules' 'node-unchanged' option", and which states:

> ... For example:
>
> 1. Create a content type with a field collection that contains an integer field.
> 2. Create an "After updating existing content" rule for that content type.
> 3. Add a "Show a message on the site" action that prints the integer field attached to node:field-collection and node-unchanged:field-collection.
>
> The printed value for node-unchanged is wrong. It shows the changed value.

This seems similar to "*... the list of pre-save and post-save travellers are always the same ...*", as in your question. So far the bad news, read on in comment nr 3 of that same issue, which is like so:

> ***The reason that node-unchanged and node both show the same (new) field collection values is that the node stores a reference to the field collection. The field collection is a separate entity. Changes to it can be caught by the rules events for field collections. The "after updating an existing field collection item" event gives the correct unchanged and new values.***

With this explanation in mind, have a look at this rule (in Rules export format):

```
{ "rules_verify_updates_to_field_collection_items" : {
    "LABEL" : "Verify updates to field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "field_collection" ],
    "ON" : { "field_collection_item_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "field-collection-item" ], "field" : "field_reviewers" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "field-collection-item-unchanged:field-reviewers" ] },
          "ITEM" : { "previous_reviewer" : "Previous reviewer" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "field-collection-item:field-reviewers" ],
                      "item" : [ "previous-reviewer" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Reviewer [previous-reviewer:name] was removed from the list of reviewers in field collection item with id [field-collection-item:item-id]." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "field-collection-item:field-reviewers" ] },
          "ITEM" : { "current_reviewer" : "Current reviewer" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "field-collection-item-unchanged:field-reviewers" ],
                      "item" : [ "current-reviewer" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Reviewer [current-reviewer:name] was added to the list of reviewers in field collection item with id [field-collection-item:item-id]." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

Some details about the above rule:

* Rules Event: After updating an existing field collection item.
* Rules Condition: Entity has field, for a field with machine name `field_reviewers`, which is a multi value entity reference field (to users). Think of those reviewers as equivalent to your travelers.
* Rules Actions:
    + The 1st loop (related to `field-collection-item-unchanged:field-reviewers`), will discover all removed reviewers.
    + The 2nd loop (related to `field-collection-item:field-reviewers`), will discover all added reviewers.

Obviously, for this rule to work you'll also need the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

Here is a demo of this rule (= some Drupal messages shown after I added/removed some user references in 2 field collection items (with id = 5 and 6):

```
Reviewer Hillary.Trump was removed from the list of reviewers in field collection item with id 5.
Reviewer UltraBob was added to the list of reviewers in field collection item with id 5.
Reviewer Donald.Clinton was removed from the list of reviewers in field collection item with id 6.
Reviewer Dries.Buytaert was added to the list of reviewers in field collection item with id 6.
Reviewer Pierre.Vriens was added to the list of reviewers in field collection item with id 6.

```
> 2 votes

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


# Question
Title: How to handle session for anonymous users for CSRF tokens?
I need to provide list of CSRF tokens in drupalSettings for every anonymous user so JS can make safe requests to api endpoints.

The CSRF service mentions the need for session to exist for the seed but I am not clear about how to create the session correctly. I tried various approaches but none seem to work correctly.

So far I have tried:

```
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
// or
\Drupal::service('session_manager')->start();
// or
\Drupal::service('session_manager')->save();
// or
\Drupal::service('session_manager')->regenerate();
// or
\Drupal::service('session')->start();
// or
\Drupal::service('session')->migrate();

```

I am trying this in my route controller hook\_page\_attachments\_alter.

This is my code:

```
/**
 * Implements hook_page_attachments_alter().
 */
function foo_page_attachments_alter(array &$attachments) {
  // Needed for persistent, per-user, csrf tokens.
  $session = \Drupal::request()->getSession();
  if ($session->isStarted() === FALSE) {
    $session->start();
  }
  // or
  \Drupal::service('session_manager')->start();

  /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */
  $csrf = \Drupal::service('csrf_token');

  $attachments['#attached']['drupalSettings']['foo']['tokens'] = [
    'pathA' => $csrf->get('/pathA'),
    'pathB' => $csrf->get('/pathB')
  ];

  $session->save();
  // or
  \Drupal::service('session_manager')->save();
}

```

# Answer
> 0 votes
So the solution to this problem is that something has to be saved into the session :)

```
  if (\Drupal::service('session')->isStarted() === FALSE) {
    \Drupal::service('session')->start();
    \Drupal::service('session')->set('foo', 'bar');
  }
  \Drupal::service('csrf_token')->get('baz');

```

Also, there is no need to call save() method.

---
Tags: 8, sessions, csrf
---


# Question
Title: Programmatically save image together with its ALT
I am not sure what is the benefit of using `system_retrieve_file` mentioned on Save image from URL to a field from a custom module, so I just use the following simple code to save image programmatically:

```
    $file = file_save_data(file_get_contents($url), file_default_scheme().'://field/image/'.basename($url));
    $file->status = 1;
    $node->field_image['und'][0] = (array)$file;
    node_save($node);

```

Works fine, so now I am trying to figure out how to save the enabled alt value which is stored in $alt variable.

When I output what the $file array contains with `dsm(print_r($file,true));` it shows only:

```
stdClass Object
(
[fid] => 9
[uri] => public://field/image/150304192032_monalisa_624x351_afp_0.jpg
[filename] => 150304192032_monalisa_624x351_afp.jpg
[filemime] => image/jpeg
[uid] => 1
[status] => 1
[timestamp] => 1425596902
[filesize] => 28642
)

```

Unfortunately, it doesn't contain neither title or alt. Could anyone help me to get this sorted out? Thanks!

# Answer
Ok, I've got this done by using the following code after node\_save():

```
$update = db_update('field_data_field_image')
  ->fields(array(
    'field_image_alt' => $alt,
  ))
  ->condition('field_image_fid', $file->fid)
  ->execute();

```

It seems this is the only way. More detailed findings are given on https://www.drupal.org/node/2447091
> -1 votes

# Answer
As far as Drupal 8 is concerned, there is another solution :

```
//    $file : my File Entity
//    $node : my (Node) Entity having an Image File field associated
$node->field_my_image_field[] = [
 'target_id' => $file->id(),
 'alt' => 'Alt. text',
];
$node->save();

```

Well, I think that 'width', 'height' and 'title' are also available in the setting array (but target\_id seems required). cf: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldType%21ImageItem.php/class/ImageItem/8.2.x (look at the source code, generateSampleValue() method).
> 1 votes

---
Tags: media
---


# Question
Title: Where can I check my module information in database?
When I create a module, where does the information of the newly enabled/installed module is stored in the database?

# Answer
The information is stored in the config table.

Search for the record with name 'core.extension', the related data is an array of all enabled modules with their related weight.
> 9 votes

---
Tags: 8, database
---


# Question
Title: View outputs Access-Control-Allow-Origin header
1. I have created a view (via the views module) which outputs a JSON output (minus the template etc) I have loaded the page and it outputs data as required.
2. I now need to call this page from another domain (cross domain) - however, when I am calling the page from the other domain (through javascript) I am obtaining the common

> Failed to load https://\<\>: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

**The Query:** Where within the views module would I be able to set the 'Access-Control-Allow-Origin' value such that it would either allow all requesting sites to be served the page or only specific domains to be served the page.

**Side Note:** As things stand I am not able to install other modules on the primary domain where the JSON page resides, as I am restricted to what I can do on that site.

As people of have worked with cross domain access will no doubt have guessed by now I am using the Chrome browser.

**Side Note 2:** When I use the Chrome extension "Allow-Control-Allow-Origin: \*" I am able to load the page as required because the whole access control check is by-passed, but I need the loading functionality to work without the need for such an extension.

# Answer
> 2 votes
You can use the https://www.drupal.org/project/cors module to add the allowed domains to your project.

Or you can alter the .htaccess file or change the headers of the php file like described in https://stackoverflow.com/questions/14467673/enable-cors-in-htaccess:

```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.php [QSA,L]
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

```

---
Tags: 7, views
---


title: Cannot Login After Drupal 7 migration

text:
# Question
Title: Cannot Login After Drupal 7 migration
```
Sorry, unrecognized username or password. Have you forgotten your password?

```

The error above shows even though I have inputted correct credentials in my site(192.168.5.141/doc\_monitor). Below are the steps I have tried to solve my problem.

1. Reset my password in Drupal users table using md5 hash.
2. Verify mod\_rewrite is enabled. mod\_rewrite module is loaded as I can view it in phpinfo()
3. Verify RewriteBase rule in my .htaccess

RewriteBase /doc\_monitor
4. Repair/Truncate sesssions table.
5. Set (doc\_monitor)drupal files to 777 permission.
6. Run update.php
7. Clear browser cache and drupal table cache;
8. Truncate flood table.

I always restarted my Apache in every changes I made. Anymore suggestions? I dont know what to do anymore.

# Answer
First thing to do to see if the login is functioning is use `drush uli`, which will create a login link for user 1. If that works, after logging in, set your password to test123. Logout, then try to log in with that.

You can also set the password with drush, trying to edit the md5 hash etc is not reliable.

https://drushcommands.com/drush-8x/user/user-password/

This doesn't have anything to do with the files directory.

Another thing to do is check your settings file just to ensure you are talking to the right database. Also check the database to see if the user you are logging in as is not blocked (status).

If you had previously set cookie domain in the settings file, verify that the value is correct.
> 4 votes

---
Tags: 7, users
---


title: How can you make an HTML link?

text:
# Question
Title: How can you make an HTML link?
I need a link with another render array around it. More specifically I need a link around an image.

In the D7 days I'd just use a render array of type link and then set HTML to true and set the text as the image.

I was hoping to put it in a preprocess function.

# Answer
The HTML attribute removal was documented in change record #2932803, but the example uses the now deprecated SafeMarkup::format function. The FormattableMarkup class allows a non-deprecated way to do this. The API page has some good examples such as below:

Remember that this is has security implications, and to only use FormattableMarkup when you absolutely need it with strict placeholders.

```
$value = FormattableMarkup::placeholderFormat('<a href=":url">@variable</a>', [':url' => $url, @variable => $variable]);

```

There's probably a better way to do this without printing the anchor element and href attribute yourself.
> 3 votes

# Answer
That's what worked for me. https://stackoverflow.com/a/44163527/1151303

```
    <?php
    use Drupal\Core\Render\Markup;
    use Drupal\Core\Url;

    $form['actions']['reset_password'] = [
      '#type' => 'link',
      '#title' => Markup::create(
        '<span class="glyphicon glyphicon-cog"></span> Forgot / Reset Password'
      ), '#url' => Url::fromRoute('user.pass'),
    ];

```
> 3 votes

---
Tags: theming, 8
---


# Question
Title: How do I test if a field has a value in twig?
I am writing a template and if 2 fields, one of which is required the other is not. I would like to display the one thats not required if has been filled out by the user.

I have tried numerous things

```
{% if content.not_required %}
 {{ content.not_required }}
{%else%}
  {{ content.required }}

{% if content.not_required  is null %}
 {{ content.required }}
{%else%}
  {{ content.required }}

{% if content.not_required  == false %}
 {{ content.required }}
{%else%}
  {{ content.required }}

{% if content.not_required  == null %}
 {{ content.required }}
{%else%}
  {{ content.required }}

{% if not  content.not_required %}
 {{ content.required }}
{%else%}
  {{ content.required }}

```

all of these display all stories the same whether or not content.not\_required was filled in.

Is there a way to do this in twig or do I need to set up some variable in a preprocess function?

# Answer
> 4 votes
There is an issue about this on Drupal.org: Checking for empty fields in Twig templates is complicated.

Use the following syntax and keep an eye on updates:

```
{% if content.not_required|render %}
    {{ content.not_required }}
{% else %}
    {{ content.required }}
{% endif %}

```

# Answer
> 1 votes
First, you are not referencing the field name right. All fields from Drupal are prefixed as `field_`. So it should be `field_not_required` if you created the field.

You also don't need a module, you don't need to check the render array. You can just do `{% if node.field_name is not empty %}` which is standard Twig. This also works for any entity that passes its data object into the template, like Paragraphs or Media.

Here is an example from an actual project:

```
  <div class="hero__content">
    {% if node.field_hero_title is not empty %}
      {{ content.field_hero_title }}
    {% else %}
      <h2 class="hero__title">{{ node.label }}</h2>
    {% endif %}

    {% if node.field_hero_subtitle is not empty %}
      {{ content.field_hero_subtitle }}
    {% endif %}

    {% if node.bundle == 'article' %}
      <h5 class="hero__description">{{ node.getCreatedTime|format_date('article_full_date') }}</h5>
    {% endif %}

    {% if node.field_hero_description is not empty %}
      {% autoescape %}
        {{ content.field_hero_description }}
      {% endautoescape %}
    {% endif %}
  </div>

```

This checks to see that the field is not empty before rendering the render array in the template.

If the field you are using is a boolean:

```
{% if node.field_not_required.value == 1 %}

```

# Answer
> 0 votes
The solution is to install this module: twig\_field\_value

With this module you can drill down to the effective content of a field, without the wrappers or standard field-labels (html-wrappers or labels can give the false impresion of a field not being empty in a -n "if statement"). By adding this code"|field\_value", you can get only the bare value only of a field:

```
{{ content.field_name|field_value }}

```

Now you use a simple Twig if statement to see if a field is really not empty:

```
{% if content.field_name|field_value %}
    <p>Field "field_name" is not empty, the value is {{ content.field_name|field_value }}</p>
{% endif %}

```

---
Tags: theming, 8
---


# Question
Title: Entity reference autocomplete field node
I am using Services module to create nodes via an api and am having problems using entity reference autocomplete to populate the field.

The ER field is linked to a taxonomy and uses a multi field setting so that more than one value can be set. I have tried multiple different options including a var\_dump of the node entity upon insert and can see its not being set.

The following are the 6 ways I tried to set the field. Do you have any idea? I am using the latest Services module and the ER module.

```
{"und": ["112326"]}

{"und": [{"target_id":"112326"}]}

{"und": [{"target_id":"A S (112326)"}]}

{"und": ["A S (112326)"]}

{"und": [{"tid":"A S (112326)"}]}

{"und": [{"tid":112326}]}

```

# Answer
> 0 votes
First, to handle multi value fields you'll need this patch: https://www.drupal.org/node/2224803#comment-11477609

Second, depending on what Widget you have selected for your Entity Reference field, this does/can change what Services expects to be POST/PUT up to the server.

I personally always set the Widget as an Autocomplete, and then this JSON format is the correct one to use:

```
var node = {
  type: 'article',
  title: 'Hello world',
  language: 'und',
  field_foo: {
    und: [
      { target_id: '... (123)' }
    ]
  }
};

```

You can literally put anything you want in the position of the `...`, the only thing that matters is the Entity ID is wrapped in the parenthesis.

---
Tags: entities, services
---


title: Can a module install a theme?

text:
# Question
Title: Can a module install a theme?
Is it possible for a module to install a separate theme, or should I just ask to the users who install the module to also install a specific theme for a better experience?

# Answer
> 1 votes
Yes, it is possible. You can create a `MY_MODULE.install` file, add a `HOOK_update()` where you can call theme\_enable and `variable_set()` to set it as the default theme.

Here is an example:

```
/**
 * Enable my_new_theme and set as default.
 */
function MY_MODULE_update_7001() {
  $themes_to_enable = ['my_new_theme'];
  theme_enable($themes_to_enable);

  // Set the theme as default.
  variable_set('theme_default', 'my_new_theme');
}

```

---
Tags: 7, installation
---


# Question
Title: Site stuck on maintenance mode only for a single page
On a live, multilingual (fr/en) client site, I've just update Drupal 7 to its latest version (along with a few modules). Everything went fine, except that, even though the maintenance mode has been disabled, the maintenance page still shows up on **ONE specific URL** of the public site.

www.domain.com/ -\> OK
www.domain.com/fr -\> **!!! maintenance page**
www.domain.com/fr/ -\> OK
www.domain.com/en -\> OK
www.domain.com/en/ -\> OK

(All the other pages are OK, as far as I can tell.)

I've tried clearing all caches multiple times, and I tried running update.php again, with no effect.
Following other answers, I've also checked the database (cache\_bootstrap and variables), but as far as I can tell, everything is normal there too.

What's wrong?

**UPDATE**
Problem solved, although I haven't done anything in particular. Maybe it was caused by some third-party caching mechanism (e.g. from the hosting provider). Will look into that if the problem occurs again.

# Answer
I came across this scenario a few days back. In my case, the site was displaying maintenance page only on registration related pages in dev server.

After several hours of struggle, it was identified to be a huge secondary database (from PROD) which was connected only on enrollment related pages. I emptied the huge tables and the pages started loading seamlessly.

Hope this might help someone.
> 0 votes

---
Tags: 7, maintenance-mode
---


# Question
Title: creating nodes with many to many relationship type with some fields?
This is in line with How to structure a "many-to-many" relationship between nodes.

To keep things in line with the example from the linked thread, what if i was a book warehouse and i had a list of all my books but i want to allow each seller to name his own price and show that book in the seller's store view with only the price that he set?

How would I allow him to edit the info of his entry without having access to anyone else's entry? I am trying to avoid associating nodes from different content types like creating a node type seller's price and reference a book inside of it.

I thought about a combination of field collection, content access, and TAC to try to make each seller capable of entering and editing their own price field collection. While I thought that field collection would create a new collection for every user, this doesn't seem to work: All sellers end up editing the same collection.

Do you have any idea?

# Answer
You are looking for the capabilities in the Relation module. With it you can relate a seller to a book, and attach a price field to the relationship.

> Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.
>
> Relations are entities and can therefore have fields. This makes Relation the most flexible and powerful relation model out there. (Still, using Relation with anything but the default SQL storage will not work in most cases.)
> 0 votes

# Answer
Try Corresponding Entity References module.

> CER keeps reference fields in sync. If you have two entities that refer to each other using Entity Reference (or some other kind of reference field), it saves you the trouble of double-editing your entities in order to have them point at each other. If entity Alice references entity Bob, CER will make Bob reference Alice, and keep the references up-to-date when either entity is updated or deleted.
> 0 votes

---
Tags: nodes
---


# Question
Title: Bootstrap theme - add or remove classes in $navbar_classes
I'm using the bootstrap theme, by default in page.tpl.php the nav bar is outputted like so:

```
<header id="navbar" role="banner" class="<?php print $navbar_classes; ?>">

```

Where can I edit the $navbar\_classes variable called in the header tag so I can add or remove classes?

# Answer
```
function YOURTHEME_preprocess_page(&$vars) {
      //add news class
      $vars['navbar_classes_array'][] = 'new-class';
      //remove class
      unset($vars['navbar_classes_array'][0]);
      // you need change value 0 to value you want remove class
      // Default
      // 0  'navbar', 1 => 'container', 2 => 'navbar-default'

}

```

You can do it with

1. Override file page.tpl.php. You can copy file page.tpl.php in bootstrap/theme/system/page.tpl.php to new your subtheme and edit it. It is right way.
2. Or you can use function hook\_preprocess\_page(). You can write code in file template.php of your subtheme. That way you don't need change file page.tpl.php
> 3 votes

# Answer
1. Open `template.php` file of your current active theme and apply this code;

```
<?php
   function phptemplate_preprocess_page(&$vars) {
     $vars['nav_menu'] = str_replace('class="navbar-nav"', 'class="myclass"',
     menu_tree('navigation'));
   }
?>

```
2. Now Open `page.tpl.php` file and you can print `$nav_menu` variable to add extra class in `<header>` tag.
> 0 votes

# Answer
To improve on MrD's very good answer, I added a little extra to make the code a little less breakable.

In your template.php file for your subtheme, create the following hook.

```
function YOURTHEME_preprocess_page(&$vars) {
    //adds container-fluid class
    $vars['navbar_classes_array'][] = 'container-fluid';
    //removes class based on array value ('container' in this case)
       if(($key = array_search('container', $vars['navbar_classes_array']) !== false)) {
         unset($vars['navbar_classes_array'][$key]);
       }
 }

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to search for string in Drupal database and replace
I am wondering what would be the safest way to search through the mysql database for a specific keyword and update.

More specifically here is what I am trying to do.

In many of the nodes we have videos embedded. Unfortunately, we didn't add preload="none" to our videos. Now the pages take a long time to fully load plus they download the whole video without the user clicking on it wasting bandwidth.

I want to search the nodes (mainly the body field) for: video controls="" and replace with video controls="controls" preload="none"

I assume I can use something like this? update \[table\_name\] set \[field\_name\] = replace(\[field\_name\],'\[string\_to\_find\]','\[string\_to\_replace\]');

Which table should I search?

I don't want to mess up the database so a second opinion is highly appreciated.

# Answer
> 4 votes
You don't say which version of Drupal you are using. If it's D7, there is the scanner module which can probably do what you want.

If it is D8, I'd suggest writing a drush script to update the content. The standardization of entities and methods makes that fairly easy. Here's a snippet of code from a script I used to grab all text from our site that needed to be translated. You can modify it to do what you need.

```
use \Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityInterface;

$entity_type = 'node';
$bundle = 'article;
$fields = [
  'field_header' => 'paragraph',
  'field_summary' => 'text',
];

$entities = gen_i18n_get_entities($entity_type, $bundle);
foreach ( $entities as $vid => $id ) {
  $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($id);

  gen_i18n_parse_entity($entity, $fields, $page);
}

/**
 * Find the entity ids for the specified type and bundle.
 *
 * @param string $entity_type
 * @param string $bundle
 * @return array
 */
function gen_i18n_get_entities( $entity_type, $bundle ) {
  $query = \Drupal::entityQuery($entity_type)
    ->condition('type', $bundle);
  if ( $entity_type == 'node' ) {
    $query->condition('status', 1);
  }
  $results = $query->execute();
  return $results;
}
/**
 * Walk thru the entity fields to get required information.
 *
 * @param EntityInterface $entity
 * @param array $fields
 * @param array $page
 */
function gen_i18n_parse_entity( EntityInterface $entity, array $fields, array &$page ) {
  global $field_num;

  $field_num = 0;
  foreach( $fields as $field => $field_type ) {
    if ( !in_array($field_type, array('alias', 'menu'))) {
      $field_def = $entity->getFieldDefinition($field);
      if ( $field_def != NULL ) {
        $label = $field_def->getLabel();
      }
      else {
        print "** Could not find field {$field} in {$entity->bundle()} {$entity->id()}\n";
        continue;
      }
    }
    else {
      $label = $field_type;
    }
    switch ( $field_type ) {
      case 'text':
        gen_i18n_parse_text( $entity, $field, $page, $label);
        break;
      case 'paragraph':
        gen_i18n_parse_paragraph($entity, $field, $page, $label);
        break;
      case 'metatags':
        gen_i18n_parse_metatags( $entity, $field, $page, $label);
        break;
      case 'alias':
        $field_num++;
        $page['en']["{$field_num} - URL"] =  $entity->toURL()->toString();
        break;
      case 'menu':
        gen_i18n_parse_menu($entity, $field, $page);
        break;

    }
  }
}

```

---
Tags: database
---


# Question
Title: How to prevent the conversion of text URL to link?
I am creating a basic page having some text links as follows:

```
http://localhost:8080/student
http://localhost:8080
http://localhost:8080/login

```

D8 automatically converts this text URL to links as follows

http://localhost:8080/sutdent

http://localhost:8080

http://localhost:8080/login

I don't want to convert the text URLs to links. I also checked the text filters but did not work for me.  How to prevent this conversion?

# Answer
As far as I know this is not a problem if you a using CKeditor.

I tried to write some text URLs in both `Basic HTML` and `Full HTML` format. It worked fine, if you want to see how I did I have made a little video for you:

https://vimeo.com/234845994
> 1 votes

# Answer
I had the same problem in D7. Not sure if it's related. I am not exactly sure what fixed it but I did completely uninstall and them re-install filter\_module. I also had to restart apache to clear out some caching there.

All my settings were like yours with convert URLS to links disabled. Did not matter what text format or WYSIWYG editor I used. I always cleared Drupal cache after making changes and used browser in incognito mode to make sure there was no caching.
> 0 votes

---
Tags: 8, navigation
---


title: Drupal 7 Not Rendering HTML tags

text:
# Question
Title: Drupal 7 Not Rendering HTML tags
I have been trying to research this issue for about a week now but not having much luck as some of the similar postings do not make too much sense to me. Either way, I appreciate any help and guidance on this!

I have a custom module that utilizes the CKeditor and submits HTML tags to the appropriate column in the database table. Example tags: `<p></p><ul></ul><li></li>`

I am using the views module to display results but instead of the HTML tags rendering, I am seeing: `
This is a test:

test 1

test 2

test 3

`

When I inspect the browser I actually see:

`<p>This is a test:</p>`

```
<ul>
    <li>test 1</li>
    <li>test 2</li>
    <li>test 3</li>
</ul>

```

What I want to see is:

This is a test:

* test 1
* test 2
* test 3

# Answer
> 1 votes
You should define the HTML tags in the view using the style options for the field settings otherwise it will treat your tags like text, which is why you are seeing the text translations of those tags.

In this example, I wanted the field "category" to be formatted as a div with a certain class. See screenshot below:

I am not sure what you mean but "appropriate column in the database" table. When using views, you don't really need to worry about how Drupal is writing to the database columns.

Notice that my format is "Unformatted List". You would want to change yours to HTML List:

# Answer
> 0 votes
Figured out a workaround.

With having the views\_php module https://www.drupal.org/project/views\_php , I went into the view I was working on and clicked "add" in the fields section.

I chose Global: PHP and the field that would be pulling my database (descr in this case).

For the field that would be pulling from my database (descr), I chose to "Exclude from Display" and in the Global:PHP field, I choose the available variable (which was $row-\>descr).

There are probably better ways to do this but after spending close to a week, this works for me.

---
Tags: views
---


# Question
Title: How to use the data from a deleted Field Collection item in a Rule?
My 'Article' nodes have a Field Collection, called 'Amounts', that contains an integer field. After deleting a Field Collection item, I'd like to substract some Userpoints from the node's author, based on the sum of the integers in the non-updated and updated node.

In order to do so, I created a Rule with the event "After updating existing content of type Article" in which I'm looping over 'Amounts' for the updated and non-updated node. The problem is that both loops use the data from the updated node (after the Field Collection item was deleted, that is), resulting in identical values.

Here's the Rule's output for a node that has 3 items with corresponding values 1, 2 and 3 after deleting the first item:

> **Non-updated node**: Sum = 5. (*This should be 6.*)
>
> **Updated node**: Sum = 5.

Is it possible to run the Rule *before* deleting the Field Collection item in order to be able to grab the necessary data values? Is there another way to use the deleted data?

# Answer
Instead of trying to get access to the deleted value with Rules, it's easier to store the sum in a new hidden field, called "Sum". In that way, the 'old value' will always be available in any Rule. Just make sure that you update "Sum" when a new Field Collection item is saved or an existing item is deleted. That can easily be achieved with another Rule.
> 1 votes

# Answer
Your own answer seems like a workaround which works for you, but doesn't really address the core of the issue you mentioned in your question, i.e. what you described as "*The problem is that both loops use the data from the updated node*".

However, instead of using Rules Event "After updating existing content of type Article" (as in your question), you should use Rules Event "**After updating an existing field collection item**", combined with the typical rules Condition "Entity has field" (for your field collection field). In doing so, you will have access to both the changed (after save) and unchanged (before save) values. And therefor pretty sure also to the values before they are deleted.

For an example of a rule that uses this "After updating an existing field collection item" Rules Event, refer to my answer to "How to get the pre-save version of a field collection in rules".
> 0 votes

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


# Question
Title: How do you link a view into a listing dropdown menu?
here are some screenshots i created a new sort view and i have tried to add it to the field collection list and then selected it in the page with the drop down and it does not display the view. Am i doing this right? I am using D7 and the

I am using the nodequeue module

https://i.stack.imgur.com/ZMrh8.jpg

# Answer
> 0 votes
I'm not reputable enough to comment so I can only post here as an "answer". But instead of telling you "how", I'm telling you that it appears you can't do this, not *easily* anyway.

It looks like the options you have available in the node edit form:

are provided by these field settings:

That screenshot of your field settings shows an error: `There is data for this field in the database. The field settings can no longer be changed.` which means you can't add a new value (a view in this case) to those particular settings.

That means you can't do this. Everytime you click the save button it fails to actually save and displays that error message.

There are some options:

1. Edit the database directly -- it's dangerous, don't do it on your live site, only do it on a copy/clone of your site until you're sure it works without breaking things horribly, and you probably shouldn't try this at all.
2. Create a new field with the settings you want. Then migrate all the data from the old field to the new field. Delete the old field once the new one is in use and working. This also should be tested safely on a breakable copy of your site.

Based on what you've shown in your screenshots, those are two possible solutions and neither of them are very good (the second one is better).

It's possible that there actually is a good solution for you, but you really need to provide more information like like @Christia said. For example, going on your screenshots alone I don't see how this has anything to do with nodqueue or field\_collection modules. This "Listings" functionality in the vertical tabs is mysterious, does it use dgo.to/viewfield or dgo.to/viewreference or some other module?

---
Tags: 7, views
---


# Question
Title: Programmatically enable another language
I'm trying to programmatically enable/install another language? (Through install profile).. Any suggestions, please?

# Answer
Assuming your environment is Drupal (or may be OK, too?), you can use locale\_add\_language() function (defined in `locale` in the core). For example, if you want to enable French, run `locale_add_language("fr")` and the job's done.

Then, you can check the result via language\_list() to make sure.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Show a field to logged-in user in Drupal 8 views
I have some fields in my views called `products` but only logged in users will be able to see the product `price` field.

I am using `twig`.

I tried using.

```
<div class="menu-items">
  <div class="shopcat-image">{{ uc_product_image }}</div>
  <h3 class="font-bold font-black">{{ title }} </h3>
  {% if logged_in %} <span class="price">{{ price }}</span> {% endif %}
  <div class="item-sku text-center">
  <strong>Item # : </strong> {{ model }}</div>
</div>

```

In custom text

but still not working.

# Answer
> 1 votes
If you want to hide the price field globally to anonymous users, consider using something like field permissions.

https://www.drupal.org/project/field\_permissions

This could potentially hide the price in any context it is displayed.

If you need to use twig, other solutions include overriding the templates for the view(s) and/or the field itself.

I would recommend addressing this kind of override from a code side, as it could potentially reveal sensitive information based on the front-end.

---
Tags: views, theming, 8, users
---


# Question
Title: How can I make a user-friendly account approval for admins?
Right now on my Drupal site I have everything set to send an email to the administrator once an account is created.

The administrator receives a link that says a new account is created, and there's a link to the user's profile in the email.

Is there any way for there to be a little option on the user's profile page that just says 'approve user' (that only the admin can see), or for an admin to get a link submitted to him through the email that he can click to automatically approve a user?

I'd rather admins not have to dig through the backend, look up a user, and then edit the user and approve the account manually. Is this possible? The most preferable would be the the administrator gets an 'approval link' in the email, so he can just click 'approve' from his email, and assuming he's logged in on the site, it automatically approves the new user account.

# Answer
> 5 votes
There are two modules that you can take a look into

Admin Users

> This module helps to administrate all registered users. You can sort out users according to their status (active or blocked), the number of published nodes, the number of comments, the last visit or the period of registration. You can also change the role of any user, block or delete many users with one click just ticking them in the table.

Multi-admin pending approval notifications (MAPAN)

> **Problem**
>
> The current behavior in Drupal core when a new user registers requesting approval sends mail only to the site's contact address. Thus only one person is notified even though there may be several administrators/moderators.
>
> **Solution**
>
> This module improves this basic behavior by notifying all users that have the 'administer users' permission by default. Administrators/moderators get a setting to disable these notifications in their user profile form. A link is also appended to each of these notifications.

# Answer
> 0 votes
There is another module called User registration notification which states

* Allows admin notifications to roles or custom e-mail address
* Allows changing the 'from' address
* Allows adding custom 'reply-to' address
* Settings can change all core account setting e-mail templates
* Allows you to send emails on user create/update/delete to your delegated users
* Allows selection of e-mail message types that will be altered
* Allow customization of Core hidden Admin (pending admin approval) e-mail

but in hindsight it offers nothing towards what sound like the crux of the OP, namely that approval can be triggered by just 'clicking a link in an email'

---
Tags: emails, users
---


# Question
Title: Drupal 8 - How to add link & display in twig template
I have file in src/Form/TestForm.php.

I would like to add link of Forgot password in **buildForm** function & want to display in twig template file.

How to achieve this?

# Answer
> 1 votes
You should add the link in the form builder, something like the following example:.

```
$forgot_password_link = \Drupal\Core\Link::createFromRoute($this->t('Password link'), 'user.pass')->toRenderable();
$form['forgot_password_link'] = [
  '#markup' => render($forgot_password_link),
];

```

# Answer
> 1 votes
You can add links in Twig directly:

```
<a href="{{ path('user.pass') }}">{{ 'Forgot password?'|t }}</a>

```

see https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

---
Tags: theming, 8
---


# Question
Title: What does the outbound path processor do?
In some PathProcessor classes there is a processOutbound method which is from the OutboundPathProcessorInterface. The API for that method simply says:

> Processes the outbound path.

What *is* the outbound path? What is it for? What does it do?

# Answer
Inbound path processing is used for incoming requests to the site. Outbound path processing is used when generating URL's, doesn't matter if it is outside of the site or not, in fact it would be very uncommon to use it for those kind of links.

The most obvious example is language negotation path prefix/domain, on an incoming request to en/node/1, inbound path processing removes "en" and sets the current language to english, when generating a linke to "node/1", path outbound processing adds the en/ prefix based on the current or provided language.
> 11 votes

---
Tags: 8
---


title: How to get an instance of a plugin

text:
# Question
Title: How to get an instance of a plugin
I am attempting to use a pre-configured instance of a plugin. The plugin is of type **@CommercePaymentGateway**.

I am currently trying to use something like:

```
/** @var PaymentGatewayManager $manager */
$manager = \Drupal::service('plugin.manager.commerce_payment_gateway');
$manager->getInstance(['module' => 'commerce_paypal']);

```

But I'm getting the error `Error: Call to a member function getInstance() on null`. However, using `kint()`, `$manager` is clearly an instance of `Drupal\commerce_payment\PaymentGatewayManager`.

I see what I think is the instance configuration in the config table under `commerce_payment.commerce_payment_gateway.paypal_ec`. But that `paypal_ec` part is specific to my site.

How do I get an instance of a plugin?

# Answer
It turns out, in my case, I'm asking the wrong question. All that I need is the parent config entity (@bojanz pointed this out in slack), so I was over-complicating the issue:

```
$gateway = \Drupal::entityTypeManager()
  ->getStorage('commerce_payment_gateway')->loadByProperties([
    'plugin' => 'paypal_express_checkout',
]);

```

This will return an array of gateways, get a specific one:

```
// Get the first one
$plugin = reset($gateway);
$plugin = $plugin->getPlugin();

```

Now you have the `$plugin` to be used elsewhere.
> 2 votes

---
Tags: 8, plugins
---


# Question
Title: how to use custom markup for views field
I have a view and there are about five fields in the view now I want to apply my own HTML markup on each field in a view. because I have created it in custom just need to apply on a view. how can I apply my own HTML markup on it?

# Answer
Add a Global: custom text field and past your custom markup remove your existing content like text images etc and replace tokens by them from replacement patterns. you will get the same results on both custom and Drupal.
> 1 votes

# Answer
This can be done with the fields style settings inside the view, rewrite results setting, or you can do this within a template file(or combination of all three) for full control over the output of the view.

This can be found under Advanced -\> Theme -\> Information. There are various view template options which you can edit, but the primary one you'll probably want is: 'Row Style Output'.

You will notice various filenames after the 'Row Style Output'. The first one being the default view theme (in bold). Copy one of the file names (non bolded) and use that file name to create a new TPL file in your theme.

Once you have added the new file to your theme directory, within your view, in the theme: information settings window, at the bottom you will find a button 'rescan template files'. After clicking this button, the view will recognize your newly added TPL file and use this to style your views rows.

From here, you simply need to render your fields with whatever HTML you want around them.

---

---

---

**I prefer to keep everything in one place.** I do this by changing the style settings to render the field with '- none -' HTML elements.

Then from there I create my views TPL file and render the views with my custom HTML markup. This, for me, is easier being able to manage all the HTML in a single file rather then editing the HTML per field.

Good luck!
> 3 votes

# Answer
If you want to apply your own html wrapper for each field then edit your view and edit the field you want to apply markup.

Expand "Rewrite results" and check "Rewrite the output of this field" checkbox.

Click on "Replacement patterns" option and here you can see the token related to your field e.g (\[nid\] == Content: Nid) this is for nid field.

In textarea below "Rewrite Result" checkbox put your markup like given in image.
> 1 votes

---
Tags: views
---


title: Print a image field without styles

text:
# Question
Title: Print a image field without styles
I do print render a image field in node. I´d like to have to original image size without any styles. But when i take a look on the image path, i see that the image was uploaded to folder "large" and gets a width of 480px. In Node display settings i have set the format to "Original". What else can i do to get the original size rendered? Thanks!

```
<?php print render($content['field_image']); ?>

```

Output Browser:

```
src="http://fake.org/sites/default/files/styles/large/public/field/image/test-image.jpg?itok=FuFLPjDI"

```

# Answer
> 0 votes
If Kevin solution not woring . Then you need to image field programmatically . Use file\_create\_url() function like this.

Load Image URI From node object

```
$uri = $node->field_image['und'][0]['uri'];
$url = file_create_url($uri);
print like this
print '<img src="'.$url.'">';

```

# Answer
> 0 votes
This is not the original image, it is a derivative generated by image styles. Fortunately it is a quick change to tell the field what to use.

Simply go into the display settings for the node or entity outputting the image, and change the field formatter from the image style setting to just "Original Image". The same option exists in Views if you are outputting the field.

---
Tags: theming, entities, media
---


# Question
Title: drush "Call to undefined function module_exists()"
I cannot execute drush in my environment. Drush is installed using

```
php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > /usr/local/bin/drush \
&& chmod +x /usr/local/bin/drush \
&& drush --yes init

```

status seems ok:

```
root@c0ec24eaf070:/var/www/html# drush status
 Drupal version         :  7.43
 Site URI               :  http://localhost
 Database driver        :  mysql
 Database hostname      :  172.20.0.3
 Database port          :  3306
 Database username      :  root
 Database name          :  drupal
 PHP configuration      :  /usr/local/etc/php/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.3
 Drush temp directory   :  /tmp
 Drush configuration    :  /var/www/html/sites/default/drushrc.php
 Drush alias files      :
 Drupal root            :  /var/www/html
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

```

but any command (such as watchdog-delete) fail with:

```
root@c0ec24eaf070:/var/www/html# drush watchdog-delete all

Fatal error: Call to undefined function module_exists() in     phar:///usr/local/bin/drush/commands/core/drupal/environment_7.inc on line 187
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Call to undefined function module_exists() in phar:///usr/local/bin/drush/commands/core/drupal/environment_7.inc, line 187

```

FYI The environment is a drupal:7.43 docker container and goes ever worse if I upgrade to 7.50

```
root@80116582cabe:/var/www/html# drush status
 Drupal version         :  7.50
 Site URI               :  http://localhost
 Database driver        :  mysql
 Database hostname      :  172.20.0.3
 Database port          :  3306
 Database username      :  root
 Database name          :  drupal
 PHP configuration      :  /usr/local/etc/php/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.3
 Drush temp directory   :  /tmp
 Drush configuration    :  /var/www/html/sites/default/drushrc.php
 Drush alias files      :
 Drupal root            :  /var/www/html
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

root@80116582cabe:/var/www/html# drush watchdog-delete all

Fatal error: Uncaught Error: Call to undefined function cache_get() in /var/www/html/includes/module.inc:754
Stack trace:
#0 /var/www/html/includes/module.inc(954): module_implements('system_theme_in...')
#1 /var/www/html/modules/system/system.module(2511): module_invoke_all('system_theme_in...')
#2 /var/www/html/includes/theme.inc(798): _system_rebuild_theme_data()
#3 /var/www/html/includes/theme.maintenance.inc(57): list_themes()
#4 /var/www/html/includes/bootstrap.inc(2857): _drupal_maintenance_theme()
#5 /var/www/html/includes/errors.inc(179): drupal_maintenance_theme()
#6 /var/www/html/includes/bootstrap.inc(2594): _drupal_log_error(Array, true)
#7 [internal function]: _drupal_exception_handler(Object(Error))
#8 {main}
  thrown in /var/www/html/includes/module.inc on line 754
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Uncaught Error: Call to undefined function cache_get() in /var/www/html/includes/module.inc:754
Stack trace:
#0 /var/www/html/includes/module.inc(954): module_implements('system_theme_in...')
#1 /var/www/html/modules/system/system.module(2511): module_invoke_all('system_theme_in...')
#2 /var/www/html/includes/theme.inc(798): _system_rebuild_theme_data()
#3 /var/www/html/includes/theme.maintenance.inc(57): list_themes()
#4 /var/www/html/includes/bootstrap.inc(2857): _drupal_maintenance_theme()
#5 /var/www/html/includes/errors.inc(179): drupal_maintenance_theme()
#6 /var/www/html/includes/bootstrap.inc(2594): _drupal_log_error(Array, true)
#7 [internal function]: _drupal_exception_handler(Object(Error))
#8 {main}
  thrown in /var/www/html/includes/module.inc, line 754

```

# Answer
It resolved to be simply the missing mysql-client package :-(

So:

```
apt-get install -y mysql-client

```

resolves the issue.
> 1 votes

# Answer
I wanted to provide an alternate answer in case other people are experiencing this issue but already have MySQL installed. When I tried executing Drush commands, I was getting

> PHP Fatal error: Call to undefined function module\_exists() in /usr/local/src/drush/commands/core/drupal/environment\_7.inc on line 187

I am running Drupal 7 on a Debian server and my issue was fixed by restarting MySQL and then restarting Apache:

`/usr/sbin/service mysql start`

`service apache2 restart`

Edit: in once case, I was receiving this error because the database user password had somehow been changed and did not match the credentials in Drupal's settings.php file. In that case, I restored the password in MySQL to match what was in the settings.php file. Using command line and logged into MySQL (MySQL version 5.5.3):

```
SET PASSWORD FOR 'user'@'localhost' = PASSWORD('password');

```
> 1 votes

# Answer
For Windows users, add the Path to Environment Variables where mysql.exe sits.
> 0 votes

---
Tags: drush
---


title: Node value from form state

text:
# Question
Title: Node value from form state
I have a node which I want to update from a form states values. I can set each value individually like:

```
$node->set("foo", "bar");

```

Is there a way to mass assign the values instead of setting each individually?

# Answer
> 0 votes
You can always create an array of name/value pairs and then a simple foreach loop to set them all. Or you can pass it to Node::create() if it is a new node.

There is no setMultiple() or similar API.

# Answer
> 0 votes
You can use:

```
$node = $form_state->getFormObject()->getEntity();

```

---
Tags: 8, forms, entities
---


# Question
Title: Seven sub-theme shows branding and nav instead of local tasks / admin menu
My client wants some basic changes to the Drupal admin pages (yay!) so I'm trying to create a sub-theme of the core seven theme. I have my sub theme working and my css is being loaded, but the local admin menu normally shown in the header of the seven theme had been replaced by the branding block and main navigation from normal pages.

This is the .info.yml file content.

```
name: My Admin
type: theme
description: A sub-theme of the seven admin theme.
core: 8.x
base theme: seven

libraries:
  - my_admin/global-styling

```

The is the content of the .libraries.yml file.

```
global-styling:
  css:
    component:
      css/style.css: {}

```

I've tried copying seven.theme file to my sub-theme folder and renaming the functions with my theme name (which has an underscore), but no love there. Do you have any idea on how to properly do this?

# Answer
I think you need to copy the regions as well. Here's the YML from our custom Admin theme.

```
name: MY Admin Theme
type: theme
description: 'My administration theme'
core: 8.x
base theme: seven
libraries:
  - my_admin/global-styling

regions:
  header: 'Header'
  pre_content: 'Pre-content'
  breadcrumb: Breadcrumb
  highlighted: Highlighted
  help: Help
  content: Content
  page_top: 'Page top'
  page_bottom: 'Page bottom'
  sidebar_first: 'First sidebar'

ckeditor_stylesheets:
  - ../main_theme/css/style.css

```
> 0 votes

# Answer
You have to copy the region definitions from seven to your subtheme.

And most likely you'll need to reassign all blocks to their correct region in Admin -\> Structure -\> Block layout
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Field collection translation structure: entity translation vs. node-type translation
I have a site with field collections and the entity\_translation module that saves field collections after the following format:

When I save a new translation via the edit page, Drupal adds a new parent field collection row in field\_data\_field\_parent\_fc (en, en-gb, en-au). Each parent field collection points to a different text field (en -\> 100, en-gb -\> 101, en-au -\> 102, etc.)

This is want I want to happen. There should be one row in field\_data\_field\_parent\_fc, containing language und, which points to a single text field (100). Then in the text field table, there should be a translation for en, en-gb, and en-au.

What I want is something akin to entity translation as opposed to node translation. Is there a setting for this, within the entity\_translation module or otherwise?

# Answer
> 0 votes
It turned out that while I had field collections enabled in /admin/config/regional/entity\_translation, the language must be set to "Language neutral" for field collections. This creates a single "und" row, and the child text fields can have their own entries for language.

Also, make sure the "Field Translation" setting is disabled for field collections under /admin/structure/types/manage/{your\_content\_type}/fields/{your field collection field}. This way, the field collections won't be translated, but the underlying text fields will be.

---
Tags: 7, entities
---


# Question
Title: hreflang links added to page source without translation
When Interface Translation module is enabled in Drupal 8, I get hreflang links to ALL languages on the site for every page view sourse, no matter if the content is translated or not.

If alternate hrefland is active on all of the pages, even untranslated ones, it creates some SEO problems.

I want to remove these links. Is any Drupal way to do this?

# Answer
These are added via a hook\_page\_attachments() implementation in content\_translations.module. The code looks like it should not add any hrefs unless an entity translation has been created.

Some tests on my site seem to indicate that this is working correctly. Do you have another module that is trying to add these and doing it incorrectly?

That said, you should be able to implement a hook\_page\_attachments() function (in something with a execution weight that runs after the content code). In this look at the $page\['#attached'\]\['html\_head\_link'\] array for the items to remove.
> 0 votes

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


# Question
Title: Getting other fields during a Drupal Services GET
I made the following request via GET: api/node?fields=nid,title,field\_media

But I'm getting the errror: **Invalid query provided, double check that the fields and parameters you defined are correct and exist. SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 't.field\_media' in 'field list'**

I'm assuming its only looking at the node table, but how do you make it grab all the fields of this content type?

I couldn't easily find the documentation of these endpoints and how to call them properly. How is everyone figuring this out?

# Answer
> 0 votes
Use Views Datasource or Views data export and create a page view that contains your fields in JSON, or XML, or whatever you want to use. Then simply do a `GET` to your view's URL.

---
Tags: 7, services
---


# Question
Title: How can I create a link, within a form, for a user to download a file?
I'm new to Drupal.

I have a custom form, within a custom module, using Drupal 8.

I would like to provide a simple link (or button, whatever the correct terminology would be), that when a user clicks will download a file that I specify.

1. How do I create the clickable part in the first place? Is there something like `'#type' => 'download'`, similar to the way `'#type' => 'managed_file'` is used for uploads? Or is using the `'type' => '#submit'` route the best way to go?
2. Where do I place the file, and how do I make the clickable part grab that file?

The file will be a .xlsx in my case, but I've seen similar questions asking how to do this for a .pdf file, .doc file, etc., but none of them have a concrete answer.

I don't care what the user does with the file once they've downloaded it. It doesn't need to be protected or "read-only" or anything fancy. I just want someone to be able to download the file and save it to their computer.

Code examples would be extremely helpful. So far my best guess is something like this:

```
// Taxonomy Download
    $form['taxonomy_download'] = [
      '#type' => 'submit',
      '#value' => t('Download Default Taxonomy Terms'),
      '#submit' => array('::downloadFile'),
    ];

(...)

public function downloadFile() {
     //Get file from /file/path/
     //return $file
}

```

# Answer
> 2 votes
Okay, so I found a solution that works pretty well, though I'm sure there are better ways to do this.

I resolved on the submit button approach, as it seems all buttons in Drupal 8 turn into submit buttons anyway. Here's the code for the button itself.

```
$form['taxonomy_download'] = [
      '#type' => 'submit',
      '#value' => t('Download Default Taxonomy Terms'),
      '#limit_validation_errors' => array(),  //don't run form validation when this button is pressed
      '#submit' => array('::downloadFile'),  //call this function when the button is pressed
];

```

Then, for the `downloadFile` function:

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

    // Creates a string of the file location. SERVER_NAME returns the
    // name of the host site, e.g. 'www.example.com' or '50.0.0.1'
    $buildUrl = 'http://' . $_SERVER['SERVER_NAME'] . '/sites/default/files/Example.xlsx';

    //drupal_set_message($buildUrl);    //uncomment this line to see what is getting passed

    $url = Url::fromUri($buildUrl);     //Creates a url from the file location

    $form_state->setRedirectUrl($url);  //Redirects the user to the file location
}

```

You will need to place the file that you're trying to download into the public files folder, found in your Drupal installation's sites/default/files/ folder. You can test that you have the file in the correct location by typing the full path (e.g. http://www.yoursite.com/drupal/sites/default/files/ExampleFile.ext) into your browser's address bar. The file should download when you go to that address.

Finally, you will need to include `use Drupal\Core\Url;` at the top of your code to make the `fromUri()` and `setRedirectUrl()` functions work.

# Answer
> 0 votes
I did like below. Hope it might help someone.

```
$conn = Database::getConnection();
$query = $conn->select('file_usage', 'fu')
    ->fields('fu',array('fid'))
    ->condition('fu.module', 'mymodule')
    ->condition('fu.type', 'type')
    ->condition('fu.id', $data->id); //$data is a module data i fetched form db
$files = $query1->execute()->fetchAll();
$doclink = Url::fromUserInput('#');//set default as '#' first
if(isset($files[0]) && !empty($files[0])){
    $fid = $files[0]->fid; // Get the file id
    $file = File::load($fid); //load the file
    $path = $file->getFileUri(); //Get public path
    $filepath =  file_create_url($path); //Get the URL from publi path
    $doclink = Url::fromUri($filepath); //Convert the string to url using fromuri method
}
//To get the a tag with the url
\Drupal::l('document',$doclink,array('attributes' => array('target'=>'_blank')));

```

---
Tags: 8, forms, files
---


# Question
Title: Default to "no limit" for maximum number of options in field type select
The number of cities and sectors "small cities" in Moldova is around thousand,so we have already exceeded the arbitrary 100 limit without half-trying.

The limit causes problems when we translate the options.

We get message translations were saved successfully, however going back to translation noting is saved.

Looking into server logs we found out there is a problem with max\_input\_vars in php.ini

> 2016/02/02 11:37:26 \[error\] 1310#0: \*199007 FastCGI sent in stderr: "PHP message: PHP Warning: Unknown: Input variables exceeded 1000. To increase the limit change max\_input\_vars in php.ini. in Unknown on line 0"

We updated the php.ini file and set the max\_input\_vars = 5000. After that the Error above disappeared, however we are still unable to save the translations and there is no error in the server console logs.

Is there anything we can do about this problem.

# Answer
> 0 votes
Try to increase `post_max_size` value or disable the limit by setting it to `0`

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


title: Querystring in Views ajax_view.js

text:
# Question
Title: Querystring in Views ajax_view.js
I'm using Views 7.x-3.11 with Better Exposed Filters and Ajax auto-submit in a panels page, and running into some issues that seem to be stemming from code in `Views/js/ajax_view.js`. I want to make the exposed filters bookmarkable, and I also need to deep link to certain result sets. Because of this, I added some custom js to add the selected form parameters to the URL as the user selects them.

I also have a section that lists all the currently active terms, where a user can click to remove them. In order to update the results from here, I'm calling `$('.view-my-view').trigger('RefreshView');`.

By default, from here I can see that the `ajax_path` for submitting the form has been set to the URL *with* the query string, which doesn't work. From what I can tell, the native ajax behavior is trying to submit the serialized form data to an already-parameterized URL. To change this behavior, at line 38 of `ajax_view.js` I've changed `var queryString = window.location.search || '';` to `var queryString = '';`

It's pretty apparent that this is going to cause issues with *some* sort of intended functionality, but I can't determine what that is. I'm afraid I'm losing sight of something bigger-picture here, or not aware of something about how Views handles ajax submission typically.

Can anyone provide an example of a situation where you'd need the original code? Or what the intended purposed of it is?

**Edit**: Follow-up question that's a little more practical - is there a way I can make an equivalent change in my custom js that would override the default code in `ajax_view.js`, so that I don't need to alter the module?

# Answer
> 0 votes
I had a similar problem where I wanted to link to filtered versions of an ajaxified view, but the aforementioned line of code in `ajax_views.js` prevented the view from displaying all results when all filters where cleared. In my use case, I wanted all views filter identifiers removed, but in yours, as I understood it, you need the clicked filter value removed, so you could modify the code accordingly.

The first step is identifying all valid filter identifiers. We want to do that, so we don't parse out all of the query string's parameters, since some of them might serve another functionality. If you don't care about creating a dependency to the better\_exposed\_filters module you can find the views identifiers from `Drupal.settings.better_exposed_filters.views.[view_name].[view_display].filters`. Otherwise, you could expose them in your own Drupal setting through a views hook:

```
function hook_views_pre_render(&$view) {
  if ($view->display_handler->has_exposed) {
    $valid_identifiers = array();

    foreach ($view->filter as $name => $filter) {
      if (!$filter->options['exposed']) {
        continue;
      }

      $valid_identifiers[] = $filter->options['expose']['identifier'];
    }

    drupal_add_js(array('validViewsIdentifiers' => $valid_identifiers), 'setting');
  }
}

```

So, now we have the identifiers and in our custom js file we can change the related properties of the views instance(s). The code for my use case is the following, but you can change accordingly:

```
Drupal.behaviors.fixAjaxQueryString = {
  attach: function(context, settings) {
    if (!Drupal.views || !Drupal.views.instances) {
      return;
    }

    for (var i in Drupal.views.instances) {
      var instance = Drupal.views.instances[i],
          url = instance.element_settings.url;

      // Check for any valid views filter identifiers and remove them
      var validViewsIdentifiers = Drupal.settings.validViewsIdentifiers || '';
      if (validViewsIdentifiers) {
        url = decodeURIComponent(url);

        for (var j = 0; j < validViewsIdentifiers.length; j++) {
          var regExpr = '\\&?' + validViewsIdentifiers[j] + '(\\[\\])?=[^&]*';
          var regExprObj = new RegExp(regExpr, 'g');

          url = url.replace(regExprObj, "");
        }
      }

      // Only the .options.url part is needed for the desired functionality
      // The rest is modified for consistency
      instance.element_settings.url = url;

      if (instance.exposedFormAjax) {
        instance.exposedFormAjax.options.url = url;
        instance.exposedFormAjax.element_settings = instance.element_settings;
        instance.exposedFormAjax.url = url;
      }

      if (instance.pagerAjax) {
        instance.pagerAjax.options.url = url;
        instance.pagerAjax.element_settings = instance.element_settings;
        instance.pagerAjax.url = url;
      }

      if (instance.refreshViewAjax) {
        instance.refreshViewAjax.options.url = url;
        instance.refreshViewAjax.element_settings = instance.element_settings;
        instance.refreshViewAjax.url = url;
      }
    }
  }
};

```

# Answer
> 0 votes
This module will allow you to make exposed filters bookmarkable: Views Ajax History Module

It utilizes the History.js library

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


title: Drush installation problem

text:
# Question
Title: Drush installation problem
I've twice followed these instructions to install Drush 8. At the end of the process I can run Drush anywhere and it responds as expected.

However, whenever my server connection is broken and I log back into the server, Drush no longer responds.

Can anyone point out why that is happening?

**MORE DETIALS:**

I honestly don't know what the issue is. I get the following message each time I go through the process of reinstalling Drush:

```
sisko@localhost:~/bin/drush-master$ drush
No command 'drush' found, did you mean:
 Command 'rush' from package 'rush' (universe)
drush: command not found

```

I tried another tutorial attempting to install it manually with no success - just the message I pasted above.

I tried running `sudo apt-get install drush` and it was not found.

If it helps, I am running **PHP 7.0.22** on **ubuntu 17.04** as shown in the following (and I'm trying to install drush for a Drupal 7 site):

```
sisko@localhost:~/bin/drush-master$ php -v
PHP 7.0.22-0ubuntu0.17.04.1 (cli) (built: Aug  8 2017 22:03:30) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.22-0ubuntu0.17.04.1, Copyright (c) 1999-2017, by Zend Technologies

```

The server shell:

```
sisko@localhost: echo $SHELL
/bin/bash

```

**UPDATE:** I am still experiencing the persistent loss of the Drush command on my server each time the ssh connection drops. I then have to re-introduce the Drush command by following these steps as detailed by @Sarika:

```
echo $PATH ---> confirms Drush is **NOT** included in the path
export PATH="$HOME/.composer/vendor/bin:$PATH"
source ~/.bashrc
sudo composer global require drush/drush:8.*

```

# Answer
Did you get drush installed on your system? Check it with the following command.

```
drush --version

```

If it is a lower version please update drush using composer, if composer already installed skip the step to install composer.

```
cd ~
curl -sS https://getcomposer.org/installer | php
export PATH="$HOME/.composer/vendor/bin:$PATH"
source ~/.bashrc
composer global require drush/drush:8.*
drush --version

```
> 1 votes

# Answer
Looking at the instructions you used and the problem you describe, the issue is most likely that you are loosing the changes you have done to your PATH shell variable. You have to check which configuration files is loaded when you login and add the `export PATH` line to that file.

To verify that the path is missing the `.composer/vendor/bin` path, do `echo $PATH`.
> 0 votes

---
Tags: 7, drush, installation, composer
---


# Question
Title: Lat/Long not getting imported into Geofield via feeds importer
I am working on a Drupal 7 website where I have a content type with geofield I am importing a .csv file with lat/long (title and lat/long(geofield))

the node gets created with title, but no location coords. How do I fix it?

Thanks

# Answer
There is a bug in the Geofield module. When lat/long are set via Feeds, the Geofield module assumes the field to be empty because some other properties of the field are not set.

There is a patch available that could fix the issue: https://www.drupal.org/node/2534822
> 1 votes

---
Tags: feeds, location
---


# Question
Title: How do I modify menu links depending on context?
I'm trying to create a menu for a department & group-based company such as:

* Presentation (`/<department>/<group>/presentation`)
* Projects (`/<department>/<group>/projects`)
* Personnel (`/<department>/<group>/personnel`)

Instead of having one static menu per `<department>/<group>`, what should be a proper approach to create just one dynamic menu which automagically updates its links to `<department>/<group>`?

# Answer
So finally Menu Token is the way to go. Once installed, created my menu entries and set them up using tokens this way:

Please notice the relative link token together with the one-level-up part before last part of path: `/[current-page:url:relative]/../presentation`. This preserves the relative static path before the last dynamic part as in this case I wanted to make the dynamic menu relative to each `<department>/<group>` path. Also remember to check `Use tokens` and select `Method for Node: Context for Node`.

Hope it helps.
> 0 votes

---
Tags: navigation
---


# Question
Title: How can I get a GMap Marker field to be a target in my Feeds importer?
I have site that needs to import a CSV of hundreds of locations to be displayed on a GMap. I have set up an importer in the Feeds module that successfully imports a CSV containing Title, address, longitude and latitude. The properties all appear on my GMap view correctly.

Now, I would also like to assign different colored markers for various location types that I am importing. I have my content type properly set up with a GMap Marker Field (if I manually assign a Marker to each node they appear with the correct markers on my map view). However, on my Feed importer Mapping page, the GMap Marker field is not appearing as a *target* option in the dropdown list.

**How can I get the GMap Marker field to appear as a target option in the feeds importer?**

# Answer
Mapping targets for fields are not automatically available. For each field, a Feeds target must be written. Feeds targets for fields provided by Drupal core should be provided by Feeds itself, but Feeds targets for fields provided by a contrib module, should be provided by that contrib module.

You can do the following:

1. Open an issue in the GMap issue queue and request a mapper for the GMap Marker field.
2. Implement the Feeds target yourself. For documentation, see https://www.drupal.org/docs/7/modules/feeds/the-developers-guide-to-feeds/the-developers-guide-to-feeds#mappingapi. While the process explained there still works, the documentation is slightly outdated. The recommended way of adding a target now is to use the hook `hook_feeds_processor_targets()` instead of `hook_feeds_processor_targets_alter()`. Also in the target callback, the language of the target can be found in `$mapping['language']`. See feeds.api.php for more information.
> 0 votes

---
Tags: 7, feeds, google-maps
---


# Question
Title: How do I invoke token substitution with Pet?
I have to send some emails in a custom Drupal 7 module.

I'd like to use the PET module (*Previewable email templates*) to manage the templates and `drupal_mail()` to send emails because it already uses SwiftMailer to send emails. The problem is that the body of the email I get from Pet has some tokens that I should replace before the email is sent.

How can I replace them?

This is the code I'm using.

```
$pet = pet_load('test1');

$params['format']= "text/html";
$params['charset']= "UTF-8";
$params['email_subject']= $pet->subject;
$params['email_body']=$pet->mail_body;

///$params['email_body']= <body with token replaced>

drupal_mail('myLib', 'customNotifications', 'xxx@gmail.com', language_default(), $params);

```

# Answer
> 0 votes
I've solved in this way:

```
// SOSTITUZIONE TOKEN DRUPAL
$l_oPetTemplate = pet_load('test1');
$l_TemParams2['pet'] = $l_oPetTemplate;
$l_aSubstitutions = pet_substitutions($l_oPetTemplate, $l_TemParams2);
$l_aEmailParams['email_subject'] = token_replace($l_oPetTemplate->subject, $l_aSubstitutions, array('clear' => TRUE));
$l_aEmailParams['email_body']=token_replace($l_oPetTemplate->mail_body, $l_aSubstitutions, array('clear' => TRUE));

```

---
Tags: emails
---


# Question
Title: Token replacement by its value before indexing in apachesolr
I'm using solr 4-x (apachesolr) for search functionality in my Drupal 7 site. I'm using a token in some long text fields in some nodes of different content types across my site. Lets suppose the token is \[token\_name\] and its value is "test". So, whenever I search "test", the nodes containing this token don't show in search results. But when I search \[token\_name\], the concerned nodes show in the search results.

What is happening here is that instead of the original token value, the \[token\_name\] is stored in database. So, for indexing, the \[token\_name\] is getting indexed instead of its value. And hence, it is unable to show results related to "test" as search keyword. Is there anyway to do this? Please suggest as I need to fix this ASAP.

P.S. I can't replace \[token\_name\] by its value while saving the node by hook\_node\_presave.

# Answer
you can use `hook_apachesolr_index_document_build()` function to override node data index in apache solr
> 0 votes

---
Tags: 7, search
---


title: Views Default Contextual Filter

text:
# Question
Title: Views Default Contextual Filter
I want to create a view that will allow the user to pass a filter value using the URL, but if the filter is missing, assign a default value. The view's path is set to `results`. I created a view page and added a contextual filter that uses the URL to retrieve the value `results/somevalue`. Some value will filter the view based on it's value. What I can't figure out is if the user browses to the default page, `results`, how do I set a default value?

I tried creating a second page based on the first, using the same path. When I did this, users could not browse to `results/somevalue`.

# Answer
> 2 votes
I would suggest a small trick with contextual filters.

After adding a filter:

1. You could simply select and fill the '*Provide default value*' field.
Here you have many options to mention the default value. The one which should work for you is: "*Raw value from URL*"

Alternative:

1. Set 'WHEN THE FILTER VALUE IS NOT AVAILABLE' to (Display contents of "No results found")
2. Select 'Allow multiple values' option at the bottom (by clicking on more)
3. Now you should pass two filter with the URL

1. Your default filter
    2. Filter which user will add to url.
4. So your default url should always include the default parameter (filter).
5. Once this is done, when there is no value for the user's filter view should filter the results based on the default filter.

# Answer
> 1 votes
This works well and is, in my mind, about as straightforward as you get for this question:

1. Make your View (let's call it View A)
2. Select things to show (fields, etc)
3. Create a Contextual Filter and Provide default value with type "Content ID from URL" (or some other contextual filter mechanism)
4. Clone the View to make View B
5. Remove the Contextual Filter from View B and add a regular Filter (Filter criteria) to be your default argument
6. Go back to View A
7. Under "No Results Behavior" add "Global: View area" and choose View B (listed by machine names)
8. Hit Save

Voila!

# Answer
> 0 votes
Another solution is to use the module 'Views Contextual Filters OR' which allows you to enable OR logic in views arguments instead of the default AND logic. This means that after enabling OR in the Query settings of the view, you can add an extra views contextual filter and use Provide default value \> Fixed value.

The Fixed value filter needs to be placed at the bottom of the contextual filter section. This is because the OR logic uses the first filter that returns anything, disregarding the rest. It works from top to bottom.

NOTE: of your view uses multiple contextual filters which rely on the default AND logic, this solution won't work because this module converts everything to OR. In that case you might want to use another module: Views Evi

Views EVI allow boths AND/OR logic filtering in contextual filters, the same way as normal views filters can do by reordering and dragging dropping.

---
Tags: views
---


# Question
Title: Use a different confirmation url on completed webform submission in email confirmation link
When a user submits a webform submission, they get redirected to a confirmation page, in my case its node/40. Now if they also have to click on an email confirmation link, it also sends them to the same confirmation url node/40.

How can you set a different confirmation url for the one in the email?

# Answer
There is actually a **Set the redirect URL** field in the "confirmation" email page setting which i totally missed. See below:
> 2 votes

---
Tags: 7, webforms, emails
---


title: Webform2pdf - Message body empty

text:
# Question
Title: Webform2pdf - Message body empty
I'm trying to use webform2pdf to generate a pdf containing form inputs. The form works fine if I don't check "Generate PDF Document", and I receive a confirmation email.

If I do enable the PDF, I don't receive a confirmation email and I get the following error:

> Unable to send e-mail. Contact the site administrator if the problem persists.

In the smtp log I see:

```
phpmailerException: Message body empty in PHPMailer->Send() (line 577 of /var/www/clients/client1/web1/web/sites/all/modules/smtp/smtp.phpmailer.inc).

```

Is there additional configuration I need to make? Drupal is new to me.

* Drupal - 7.54
* Webform - 7.x-4.15
* Webform 2 PDF - 7.x-4.0
* SMTP Authentication Support - 7.x-1.6
* MIME Mail - 7.x-1.0
* TCPDF - 6.2.13

\** Edit \**

Turning off SMTP Authentication Support and using DefaultMailSystem solved this particular issue and allows PDF attachements, although DefaultMailSystem only allows plain text emails.

# Answer
> 0 votes
Webform2PDF has dependencies, did you install them?

> **Third-party tools:**
>
> * TCPDF
>     + 4.5.000 or later required from webform2pdf 2.x or 3.x
>     + 6.0.000 or later required from webform2pdf 4.x

---
Tags: webforms, files, emails
---


title: images missing - wrong base url

text:
# Question
Title: images missing - wrong base url
My website occasionally loses images due to the image url being set to http://default/sites/files/XXXX.jpg. The "default" baseurl is the issue and as i understand drupal 8 has no way of setting this manually.

As this seems to happen sporadically i am assuming it is related to a cron job running under baseurl of "default" and then the page being saved to the cache.

Anyone have any ideas how to diagnose or possible causes? i was thinking something like SimpleSiteMap could be affecting this.

thanks

UPDATE After some testing it seems likely that its a cron job accessing the pages and the image urls being cached incorrectly.

The cron jobs run under base url of 'http://default' so the chain of events seems to be: cron starts clears caches a cron job attempts to render the page causing the img urls to be cache incorrecly

If i then clear the cache again and navigate to the pages the urls are re-written and cached correctly now.

# Answer
Have you tried setting

$settings\['file\_public\_base\_url'\] = 'http://sitename.local/sites/default/files';

In sites/default/settings.php?

I do this for all of my sites both in dev and production and haven't had any issues.

I realise that you may have solved the issue, but just so you know you can set the base url for your files through that setting :)
> 1 votes

---
Tags: media, cron
---


# Question
Title: How to remove "Submitted By" data from google search engines in drupal7?
How can I prevent showing of `Submitted by username` information on google search result pages.

I looked into some of the answers but I am not sure those solutions will remove from google search. I am thinking those are related to drupal search engines.

Here are the links:

Remove "Submitted by" on search results

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

Please help me regarding this. It will be more appreciated if solution will workout for already created data/nodes as well.

# Answer
If you don't want the content to show up in Google search, you have a couple options.

1. Hide the "Submitted by" in Drupal itself. You can do this by going to the content type edit page and unchecking the box for "Display author information."
2. Use a theme template for the content types and move the "Submitted by" information to the bottom of the content. If it is shown at the bottom instead of the top, Google is unlikely to use that information in its search results, since it gives information toward the top higher priority.

What you shouldn't try to do is show information to users but somehow hide it from Google. This is likely to make Google mad and if they detect it, your site will be penalized.
> 0 votes

---
Tags: 7, theming, search
---


# Question
Title: Why is an untranslated string not showing up?
In my module I have some custom strings. I use these in the `t()` function. When I go to `admin/config/regional/translate/translate` and filter the untranslated strings my custom strings do not show here.

What could be going wrong?

# Answer
> 6 votes
The strings needs to be rendered a first time on a page in the not default language and your string keys will be visible in the `Translate interface`.

An important detail, the search is case sensitive. For example `My text` is different than `my text`.

# Answer
> 4 votes
If you're trying to see the site in English the `t()` function will not try translate the string, so you need to see the site in other language in order to for the translation system to add your translatable string to the database.

Once you do it, you will be able to translate your string.

# Answer
> 2 votes
Beside visiting the page showing your strings in a non-default language, make sure to have the version number of the module set in the .info file.

> version = 7.x-1.0

Here a trouble shooting blog post to getting your strings into the translate interface.

---
Tags: i18n-l10n
---


# Question
Title: Difference between $this->config and \Drupal::config in ConfigFormBase
I want to override a custom module configuration in the `settings.php` file. So the configuration in database can be independent from the environment.

```
$config['my_module.settings']['prop'] = 'foo';

```

I my module configuration form, the config result is different given the method I use to get it :

```
class MyConfigurationForm extends ConfigFormBase {

    public function buildForm( array $form, FormStateInterface $form_state ){
        $config = $this->config( 'my_module.settings' );
        print_r( $config->get('prop') );
        // prints database value, or nothing if there is no value in database for 'prop'

        $config = \Drupal::config( 'my_module.settings' );
        print_r( $config->get('prop') );
        // prints 'foo'
    }

}

```

Why is that ? What's the difference between these two methods ?

# Answer
> 10 votes
In a configuration form use `$this->config()` and not `\Drupal::config()`.

The difference between both is that the configuration form uses immutable configuration.

When Drupal 8 was in beta, the immutable configuration was introduced to avoid bleeding of overridden values into configuration when saved to the database. See the change record:

Configuration objects by default are immutable

This is the code executed by `$this->config()` of a configuration form, in a static version:

```
\Drupal::configFactory()->getEditable('system.site')->set('name', 'My fantastic site')->save();

```

---

For Drupal 8.7 it is discussed to display a warning for overridden values:

> This form contains values that have been overridden. Changes to these values can still be saved, but the overridden values will take precedence. Overrides are as follows ...

See the issue:

There is no indication on configuration forms if there are overridden values

---
Tags: 8, configuration
---