# Question
Title: How to delay sending emails using Rules to avoid being considered as a spammer?
I created a rule for users, who subscribed on another user to get messages of this user new content:

```
Events
  EVENT
    After saving new content
Conditions
  ELEMENTS
    None
Actions
  ELEMENTS
    Fetch users who have flagged a user
      Parameter: Flag: subscribe_this_user, user: [node:author]
      Provides variables: subscribers (user)

    Loop
      Parameter: List: [user]
      List item: Current list item (liker)

     Send mail
       Parameter: To: [liker:mail], Subject: New event on [site:name]!, Message: New content [node:title] by..., From: [site:name

```

How can I send these emails with delay? I heard that sending a lot of emails is spamming. I heard about Rules Scheduler, but don't know how to integrate that in my rule.

# Answer
> 1 votes
Below is a summary of how you can get this to work:

1. Introduce an additional flag to allow "flagging" these (new) nodes by all users "*who subscribed on another user to get messages*" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
2. Adapt the rule you already have, like so:

* Remove the Rules Action "send eMail".
    * Flag the newly saved content, using the new flag (from step 1) for each of the users you already have in your existing list in your existing Rules Action.
3. Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
4. Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

* eMail each of the users in that VBO list (you can probably reuse the Rules Action "send eMail" that you already had, but removed in step 2).
    * unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the exectuion of the same rule within Y minutes or hours (pick a value for Y that fits your needs).
5. Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will notify X users "as requested".

# Answer
> 0 votes
I think that deferring emails is the wrong solution for you here. A question like this often indicates the hosting may not be suitable for the site profile.

Unless it's part of your site model, a workaround of delaying delivery will just show user engagement. Over the course of a day you'll end up sending the same number of emails, so this won't reduce your chances of being flagged as a spammer.

What will work better is to ensure you use a reliable mail delivery mechanism, and avoid spam behavior (like sending excessive or unwanted notifications).

If your existing hosting limits outbound email, and you need to send more emails than the limits they offer, find a provider who does suit your needs (and will scale for future success). There are plenty of mail providers on the market for you to choose from, and options for reliable self hosted systems too.

---
Tags: 7, rules, emails, advertising
---


# Question
Title: What values can I use for _entity_access in a configuration entity I am developing?
Looking at search.routing.yml, I noticed it contains the following code.

```
entity.search_page.enable:
  path: '/admin/config/search/pages/manage/{search_page}/enable'
  defaults:
    _controller: '\Drupal\search\Controller\SearchController::performOperation'
    op: 'enable'
  requirements:
    _entity_access: 'search_page.update'
    _csrf_token: 'TRUE'

entity.search_page.disable:
  path: '/admin/config/search/pages/manage/{search_page}/disable'
  defaults:
    _controller: '\Drupal\search\Controller\SearchController::performOperation'
    op: 'disable'
  requirements:
    _entity_access: 'search_page.disable'
    _csrf_token: 'TRUE'

```

While it's clear that the first part of the *\_entity\_access* value is the ID of the configuration entity used in the annotation for the class implementing it, I don't understand what I can use as part after the dot. Is it restricted to a set of values (e.g. *add*, *update*, *use*, *delete*), or is it a value the access controller class for that entity handle?

# Answer
According to the Drupal 8 documentation:

> \_entity\_access: In the case where an entity is part of a route, can check a certain access level before granting access (e.g., \_entity\_access: 'node.view').

The part after the dot is the type of access you want to check on the entity. To find the full set of possible values, you have to look at the code of the entity (in your case, in `\Drupal\search\Entity\SearchPage`). The default possible values are view, update, delete, create. Entities implemented by `SearchPage` can also be disabled and enabled. (See search.routing.yml and `SearchController`.)

See also `EntityAccessCheck::access()`.
> 5 votes

---
Tags: entities
---


# Question
Title: Is there a way to set a session variable but not save them in the sessions table?
I wanted to save a huge array in a `$_SESSION` variable. If I understand it correctly, Drupal saves the entire `$_SESSION` into the sessions table. But when the `$_SESSION` variable gets to around 3mb, MySQL throws an error.

I don't want to increase max\_allowed\_packet size, and I don't really need Drupal to save the array variable in the sessions table.

So, is there a way to set a `$_SESSION` variable that can be excluded from being saved into the sessions table?

# Answer
> 0 votes
You should probably look first at either not storing this data but instead deferring its calculation, or at alternative storage methods, eg perhaps `cache_set()` and `cache_get()`. You could easily run into the same DB limitations there of course.

**You probably don't need to store this data to the session at all**, and as you've discovered it can be problematic to do so.

I've seen developers use `$_SESSION` as a global variable to pass data around, and as temporary per-visitor storage. This is possible, but there are limitations and likely better ways - for which you might need to zoom out to the actual problem at hand. (*Do you need to store a rendered collection of kitten profiles, or just a list of kitten IDs then render later?*)

If you do actually need to store such large datasets to the session, you'd probably have to replace the default session management in Drupal or reconfigure your DB (which you've said you'd rather not do). In that case perhaps modules like Session Proxy or perhaps Memcache would help ... But try not to go there :)

---
Tags: sessions
---


# Question
Title: http://example.com/node/111 also accessible through http://example.com/node/111.000
An acunetix scan has complained about the following:

http://example.com/node/111.000 or http://example.com/node/111.0 or http://example.com/node/111.000000 (any number of zeros) serves the node http://example.com/node/111

For the regular url, the pathalias is then used, for the url with .0 added, it is displayed as is.

Two questions: is it possible to disable this behavior, and if not, is there a standard reference to justify this to our security team?

# Answer
Automated scans sometimes report issues that are non-issues, and the results of an automated scan do need to be combined with an understanding of the issues at hand (and, if they require fixing, the risks of introducing new code to mitigate supposed vulnerabilities).

As R. Leurquin says, in Drupal there are multiple URLs that may work to access the same node or path directly. While this might not be ideal for SEO (if people link to multiple URLs), it likely isn't an actual security concern.

This can likely be solved using approaches like the Global Redirect module in Drupal 7, and the Redirect module in Drupal 8 (and in D7 if patched from #905914: Merge global redirect functions into Redirect module).

You'll get the SEO improvements, and if the security team really need convincing, hopefully it's an easy item to knock off the list!

If those don't cut it, you could do something similar to what Global Redirect or Redirect do, eg implement `hook_url_inbound_alter()` or `hook_init()`, check for those zeroes, and redirect them. In that case, be careful that the "fix" for this "problem" is not riskier than the existing situation.

You could also handle this with redirects at the webserver layer.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Register a new namespace for autodiscovery
I'm using a vendor library that isn't managed through composer. I want to register the namespace for the library so that it will be discovered through PSR-4. I'm not sure how to go about doing this in D8 though. Can anyone point me at something?

# Answer
The autoload is still done using Composer. To add an extra namespace you'll have to run a composer command to rebuild the autoload file.

See https://stackoverflow.com/a/31505011/113057 for how to add a namespace to composer.

The key is in `composer dump-autoload`
> 4 votes

---
Tags: 8
---


title: Multi-domain cookie

text:
# Question
Title: Multi-domain cookie
The website I'm working on has 5 domains (two top level and 3 subs, not including www). I need to limit the cookie that the site creates to only work on 4 of the domains.

I have found from here that in Drupal 8 cookies are defined in the services.yml file using this:

```
parameters:
  session.storage.options:
    cookie_domain: '.domain.com'

```

But I'm unsure how I can add multiple domains. Is it as simple as something like this?

```
cookie_domain: 'www.domain1.com'; 'domain1.com'; 'sub1.domain.com'; 'sub2.domain.com'

```

# Answer
> 4 votes
A cookie can only have 1 domain value. So you can either set it to a specific domain or the top domain wich includes all the subdomains.

See https://stackoverflow.com/questions/1062963/how-do-browser-cookie-domains-work

---
Tags: cookies, 8
---


title: Change default tab for Media browser

text:
# Question
Title: Change default tab for Media browser
Is it possible to change the default tab for Media browser (Media module) in Drupal 7? Currently I have: **Upload**, **Web**, **Library** and **My Files**.

I would like to open **Library** by default, instead of **Upload**.

# Answer
This is what you are looking for:

http://jimbir.ch/blog/changing-order-drupal-7-media-module-file-browser-tabs

I just tried and it works perfect:

> Blockquote
>
> Here is the original order of the file browser:
>
> In order to change the order and hook into this function, I created a simple custom module, mediamenu. In this module, I will be able to hook into the media module using the hook Brandon showed me, and change the weight of the tabs, re-ordering them. The module has a folder named mediamenu, and inside two files, named mediamenu.info and mediamenu.module. You can view and download these files from this github repo. mediamenu.info
>
> The .info file contains information about the module, name, description, version, which version of Drupal, and where to group it on the modules page.
>
> ```
> name = Media Menu
> description = This module organizes the tabs on the Media browser.
> version = "7.x-1.0"
> core = "7.x"
> package = Media
>
> ```
>
> mediamenu.module
>
> In the .module file, we hook in and change the weights of the tabs, which will re-order them, the heaviest weight/lowest number first.
>
> The first two items here are provided by the Media module, and the Media Browser view (Machine name: media\_default). The two tabs are made by the two displays of the view, media\_browser\_1 and media\_browser\_my\_files. The media\_internet tab is provided by the module of the same name. Upload is provided by the media module.
>
> ```
> < ?php
> /**
>  * Change Order of Media Browser Tabs
>  *
>  * Implements hook_media_browser_plugin_info_alter().
>  */
> function mediamenu_media_browser_plugin_info_alter(&$info) {
>   $info['media_default--media_browser_1']['weight'] = '-10';
>   $info['media_default--media_browser_my_files']['weight'] = '-9';
>   $info['media_internet']['weight'] = '-8';
>   $info['upload']['weight'] = '-7';
> }
>
> ```
>
> You may have additional tabs provided by other modules. You can find their machine name but looking at the source markup of the page, and looking for the data-tabid of the tab.
> 0 votes

---
Tags: media
---


# Question
Title: CKEditor "Source" button does not brings back the full html
I have written a full html code

```
<div style="background-color:red"> </div>

```

But when I edit the content and click on the "Source" button provided in the CKEditor toolbar. nothing is showing up

In Advanced content filter I have given in Extra allowed content

```
p(*)[*]{*};div(*)[*]{*};li(*)[*]{*};ul(*)[*]{*}

```

In Custom JavaScript configuration I have given

```
config.allowedContent = true;

```

# Answer
> 0 votes
I know D8's CKEditor doesn't allow you to use the `style` attribute to prevent click jacking attacks, example.

Can't remember if D7 CKeditor did or not, but either way, it's bad security practice to allow people to use `style` attribute.

The better approach is to use a class.

```
<div class="bg-red">...something goes here...</div>

```

Your Drupal theme's **style.css**

```
.bg-red {
  background-color:red;
}

```

---
Tags: 7, wysiwyg
---


# Question
Title: Webforms: Is it possible to set maximal value for Number in relation to another Number value?
I am new in Drupal...

In webforms I use `Number` field to set age of person:

**How old are you?** \[Number\] /min 10, max 100/

**When did you smoke for the first time?** \[Number\] /min 10, max *`here should be the value of the previous number.`*

Is it possible to set it somehow in Webform GUI, or the only by the code?

Thanx

# Answer
> 1 votes
You might try making the age a drop-down with the given range and then webform conditional becomes an easy, ready to use option.

Many other ways to get this done but this is probably the most straightforward imho.

---
Tags: webforms
---


# Question
Title: Should I start a project on Drupal 7 in 2017?
I have a company intranet project that includes some features like:

* advanced user permissions
* company events calendar
* collaborative edition of nodes and workflows

Drupal 8 was interesting for me because of **OOP** and **Inline editing** of nodes (which is a huge point for the User Experience of non technician users of the company).

I tried to make a prototype with Drupal 8, but I encountered a **lot of beta modules** and some weren't even usable (Calendar module for instance).

In May 2017, Drupal 8 seems to be not as usable and stable than Drupal 7. This is why I'm tempted to use Drupal 7 for this project.

Do you think that starting a Drupal 7 project from scratch is a good choice in 2017 ?

# Answer
If you're not a coder, then D8 probably isn't ready, for the exact reasons you have run into. Major modules have not been released, and a huge majority of modules are still in beta version. Unless you have the coding skill to help fix bugs and/or to upgrade modules to D8, you will run into plenty of roadblocks. So D7 will likely be a better fit for you.
> 1 votes

---
Tags: 7
---


# Question
Title: Is it possible to create a pre-filled select list field with Drush?
The syntax to create fields is on https://drushcommands.com/drush-8x/field/field-create/

For those it works:

Images:

`drush field-create article img,image,image_image`

Text fields:

`drush field-create user address,text,text_textfield --entity_type=user`

text long:

`drush field-create user address,text_long,text_textarea --entity_type=user`

Decimal:

`drush field-create user userpoints,number_decimal,number_textfield --entity_type=user`

Boolean:

`drush field-create content haspurchase,list_boolean`

Is there a way to create a select list field pre-filled with values?

# Answer
You can create select field also from drush command. Just type the command from drupal root directory `drush field-create content_type_name` and hit enter key and follow the instruction. Please see the attached screenshot.

Copy the last output which is edit url of your field where you can refinement your field.
> 2 votes

---
Tags: 7, entities, drush
---


# Question
Title: How do I configure the database using php_server module
I am trying to set up an existing site locally. It seems that Drush cannot find the site. When I run `drush cc all`, I get this error.

> No Drupal site found, only 'drush' cache was cleared.

I think the issue may be with my server configuration. I am using the PHP Server module, and I'm not sure how to get it to point to the database.

This is what `drush status` returns, for your reference:

```
 Drupal version         :  7.41
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database username      :  root
 Database name          :  quorum
 PHP executable         :  /usr/local/bin/php
 PHP configuration      :  /usr/local/etc/php/7.0/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/Cellar/drush/8.1.11/libexec/drush.php
 Drush version          :  8.1.11
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/Jillian/ideometry/quorum-dev
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

```

# Answer
> 0 votes
This is because you are running the drush command in directory where your project code doesn't exists. I think you are getting logged in to home directory of a server where the project code does not exists. Your project code is in another directory. for e.g

```
-opt
 -webcode
  -project_code
-home
-etc

```

So you are getting loggedin in the home directory but your code is inside /opt/webcode/project\_code. You need to reach to project\_code directory first and then run the drush command.

You can use filezilla if you are not aware of the directory stucture. It will help you to know which directory has your project code.

---
Tags: 7, database
---


title: How to add a Product Catalogue Field

text:
# Question
Title: How to add a Product Catalogue Field
I have a drupal commerce website, where i have items separateed by category: see here

I'd like to add as well, another field called BRAND, so that an item can be associated to both a category ie: CHIPS and a brand: ie Lays

i've tried to create another taxonomy term, but it doesn't appear then when i create the product.

I'd like to have this inserted as well as a criteria in the search form.

how can i do this?

thanks in advance for your help

# Answer
> 0 votes
I am not sure if I understood your question correctly.

Nevertheless, maybe you misunderstand **taxonomy vocabulary** and **taxonomy term**? I would have expected that you create **two** vocabularies: one for **brand** and another one for **category**. Both should be referenced by your content type for products.

---
Tags: commerce, taxonomy-terms
---


title: node_save JSON field formats

text:
# Question
Title: node_save JSON field formats
I'm having an issue where node\_save() (inserting new node) ignores some fields in my JSON node. This happens with several content/widget types. I've posted this to Drupal services with no response.

I followed Tyler's post here recommending to do a GET to observe and mimic the JSON format returned - unfortunately I'm finding the format returned in a GET is not always the same format as expected in a node\_save() POST. https://github.com/signalpoint/DrupalGap/issues/418

I also saved a node on our Drupal website and captured the format of the POST body, trying to translate that format to analogous JSON. No luck.

1. Date time field, with start and end date, using Date (Unix timestamp) field type and pop-up calendar widget. Formats recommended in the post below does not save, only default value (now) is saved. Example is field\_when\_available below. Services module update date field
2. Integer field types with Text field widget will not save. I've tried over 20 permutations of formats, posted here, no response. htt ps://www.dru pal.org/node/2870095 field\_scrap\_weight is an example below.
3. Reference to another node will not save. Same link above describes using target\_id, tried that, no success.

What *will* save are are term reference and List(text) content types from Radio button widgets. field\_surplus\_type and field\_unprepared\_or\_prepared are examples.

I am posting to http://127.0.0.1:8083/?q=drupalgap/node.json

Below is one example, but I've tried literally hundreds of permutations with and without array brackets, with/without the "und" element, with/without quotes in the data value, etc.

I'm beginning to think there's a more global/systematic issue like a content-type setting.

```
{
  "type": "donation",
  "form_id": "donation_node_form",
  "language":"und",
  "field_unprepared_or_prepared": {    // saves OK (List text, checkbox/radio)
    "und": {
      "value": "unprepared"
    }
  },
  "field_surplus_type": {        // saves OK (Term ref, checkbox/radio)
    "und": [ 1, 3  ]
  },
  "field_scrap_weight": {        // NOT saved (integer, text field)
    "und": {"value": "1"}
  },
  "field_when_available": {      // NOT saved (Unix timestamp), popup calendar
    "und":[
      {
        "value": {
            "date": "05/29/2017",
            "time":"09:00pm"
        },
        "value2": {
            "date": "05/29/2017",
            "time":"09:00pm"
        },
        "timezone": "America\/New_York",
        "timezone_db": "UTC",
        "date_type": "datestamp"
      }]
  },
  "field_surplus_location": {     // NOT saved - node reference
    "und": {"target_id":"256"}
  },
  "body": {           // NOT saved (long text w/summary, text area widget)
    "und": {
      "value": "dd"
    }
  }
}

```

# Answer
> 0 votes
It's important to understand that the Services module is closely tied to the Drupal Forms API, meaning that the JSON delivered via POST/PUT is sometimes dependent on the Widget that is selected for the field(s) in question, so it won't always match what is delivered via GET.

That being said, I can see some problems with your JSON. Try these instead:

**integer, text field**

```
"field_scrap_weight": {
  "und": [ { "value": "1" } ]
},

```

**node reference**

```
"field_surplus_location": {
  "und": [ { "target_id":"... (256)" } ]
},

```

**long text w/summary, text area widget**

```
"body": {
  "und": [ {
    "value": "dd"
  } ]
}

```

Often times it appears you are missing the wrapping `[]`, this indicates the delta value for the field's item, i.e. it's an array so you can pile up extra values if your field is configured for more than 1 value.

The entity reference field can be any text, but the target id must be wrapped in the parenthesis.

The Date field is the trickiest and I would advise looking at the following answers:

If you're looking to POST/PUT exactly what is delivered via GET, then check out the Services Entity module and this extra configuration that can be added to jDrupal.

---
Tags: javascript
---


# Question
Title: Why subscribe/unsubscribe button in the custom entity named group cannot appear?
I have created a custom render in `group_module.js` exactly as the example Rendering Entities with the exception of the line `items['group/%'] = {` instead of `items['team/%'] = {`. All other content nodes but group nodes (`group/%`) show ok. Group nodes show no subscribe/unsubscribe button and no menu tabs mentioned below in the `groups_menu_module.js`. I suppose that this module, `groups_menu_module.js`, is not loaded somehow.
I have to mention that without the custom rendering of entity group and with 2 LOCAL\_TASK\_MENU menu tabs, everything works perfect.

groups\_menu\_module.js

```
function groups_menu_module_menu() {
  try {
    var items = {};
    items['group/%']={
      title: 'view',
      page_callback: 'drupalgap_get_entity',
      page_arguments: ['groups_menu_module_default_page', 'node', 1]
    };
    items['group/%/provoli'] = {
      title: 'view',
      type: 'MENU_DEFAULT_LOCAL_TASK'
    };
    items['group/%/melh'] = {
      title: 'members',
      type: 'MENU_LOCAL_TASK',
      page_callback: 'groups_menu_module_melh_page',
      page_arguments: [1],
      title_callback: 'groups_menu_module_melh_page_title',
      title_arguments: [1],
      access_callback: 'groups_menu_module_page_access',
      access_arguments: [1],
      options: {
        reloadPage: true
      }
    };
    items['group/%/anarthseis'] = {
      title: 'posts',
      type: 'MENU_LOCAL_TASK',
      page_callback: 'groups_menu_module_anarthseis_page',
      page_arguments: [1],
      access_callback: 'groups_menu_module_page_access',
      access_arguments: [1],
      options: {
        reloadPage: true
      }
    };
    return items;
  }
  catch (error) {
    console.log('groups_menu_module_menu - ' + error);
  }
}

function groups_menu_module_default_page(node) {
  try {
    var content = {};
    content['title'] = { markup: node.title };
    return content;
  }
  catch (error) {
    console.log('groups_menu_module_default_page - ' + error);
  }
}

```

I have to mention that all functions needed are present in the actual .js file, i just opted them out because i think they are irrelevant. The `pageshow` function of the other module is as the example in the above link:

group\_module.js

```
function example_team_pageshow(nid) {
  node_load(nid, {
    success: function(node) {
      var content = node.title; // Add other content here...
      $('#' + example_team_container_id(nid)).html(content).trigger('create');
    }
  });
}

```

So to conclude the question is how to make the subscribe/unsubscribe button appear in the custom entity render? How to call og\_ui\_field\_formatter\_view() from my module to make the button appear?

I don't know if i made my self clear what is needed. If anyone need more information please ask so in the comments below to clarify some points.

# Answer
Since you are taking over the display of Organic Groups nodes using your custom page callback path `group/%`, DrupalGap doesn't know to apply the field format view functions to your fields. Essentially you need to manually create/render your own widgets in your `page_callback`:

```
var content = {};
content.title = { /* ... */ };
content.subscribe = { /* ... */ };
return content;

```

There are helper functions in the `og.js` file related to joining/leaving groups that will be of help. From there just use simple HTML/CSS/JS to build your button(s) (perhaps with an `onclick` handler) to help the user interact with the group subscriptions.

If you want to call the `og_ui_field_formatter_view()` function directly (not recommended) you can, you just need to pass it all the correct parameters:

`(entity_type, entity, field, instance, langcode, items, display)`

Not the easiest things to do to be honest, and you'll probably find yourself happier in the long run by building your own custom widget to subscribe/unsubscribe from the Group.

Feel free to copy any code you need from the `og.js` file to make your life easier.
> 1 votes

---
Tags: 7, organic-groups, javascript
---


# Question
Title: Feeds tamper to find element in text and replace it with part of the element or 0
I have a set of HTML pages that I'm importing (regularly) into a Drupal site using Feeds and Feeds Tamper.

One of the elements in the feed can take one of two forms:

`Birth 1869 Location Merthyr Tydfil, Glamorgan, Wales<a class="gs-pl" href="https://maps.google.com/?t=m&q=51.7479,-3.37779" target="_top" title="Google">G</a>`

or

`Marriage Calculated 1894` (i.e. without a Location section).

The feed contains an unlimited number of these elements which will be imported into a multivalued Field Collection attached to a node.

I need to extract part of the Location section (a latitude) or if there is no Location provide a default value of 0.

I'm using the Find Replace Regex plugin to extract the latitude and add a pipe character (to allow me to Explode the results into an array).

My find regex currently looks like:

`.*?Location.*?"gs-pl".*;q=(.*?),(.*?)".*|.*`

which either identifies the latitude or returns the full string if there is no Location element.

My replace regex looks like:

`\1|` which works fine for the case where the Location element exists.

However, I can't see how to replace any empty string returned (i.e. when the capturing group is emtpy) with a figure 0.

Is this possible using the Find Replace Regex plugin, on its own or in combinations of other tampers as well? I wondered if I could process the original element to add a Location element with the values required as a default if it was missing but that still involves a conditional replacement so it's essentially the same problem.

I can't set insert missing Location elements in the HTML before the import, and setting the default value in the String Collection doesn't work because of the way field collections are imported (basically the method I'm using puts the data in the wrong field collection item if there are any empty fields)

# Answer
You can add a Tamper plugin of type "Set value or default value". Set "Value" to "0" and enable the "Only if empty" option (see image below). This way, the value "0" will be set only if the "Find replace REGEX" returned an empty result.

I tested with your example data if this would work and in my case it did. `Birth 1869 Location Merthyr Tydfil, Glamorgan, Wales<a class="gs-pl" href="https://maps.google.com/?t=m&q=51.7479,-3.37779" target="_top" title="Google">G</a>` resulted into `51.7479` and `Marriage Calculated 1894` resulted into `0`.
> 1 votes

---
Tags: 7, feeds
---


title: Show Image from Referenced Node

text:
# Question
Title: Show Image from Referenced Node
I am building a book review site. I have two kinds of content: 'Book Listing' and 'Review.' The Review content type has an entity reference field which links back to the Book Listing. Using entity prepopulate, I have created a button which opens the 'Review' add/edit form and automatically sets the value of the entity reference field to the corresponding Book Listing NID.

Now, what I would really like to do, since the button opens a new page, is add the book cover image that is on the Book Listing page to the add/edit form, to help the customer remember what they are reviewing. Amazon has a similar feature. To further complicate things, my 'Review' add/edit form is being rendered with panels. I've been playing around with views (with relationships) and passing arguments into the panel, but am not having any luck. Has anyone done something like this before? Any idea on what to try next?

# Answer
With the relationship to the second content type properly defined (and possibly also required) you should be able to display the image requested.

One problem area I've seen is the base tables defined. You can see the base table in the export text of a given view right on top.

If your base tables do in fact differ, then there are further nuances to the relational display in views, but it can be done.

Post back if you have more details to this view creation to guide a useful example. I'll post more step by step instructions.
> 0 votes

---
Tags: views, entities, panels
---


title: Import users from LDAP

text:
# Question
Title: Import users from LDAP
I want to import user accounts to my Drupal site via the LDAP server. How do I do that? I installed LDAP feeds, but I don't understand how it works. I have LDAP query installed and working.

# Answer
As the comment noted this question would benefit from much more detail.

There are 2 very broad scenarios here;

1. Loading LDAP user attributes for use and reference within Drupal (probably user entities) users that exist.
2. Linking LDAP users to Drupal in an ongoing fashion including some form of authentication requirement.

In the first case you won't likely be dealing with LDAP user credentials (which is good) and greatly simplifies the implementation. This is a good example; on Drupal.org using LDAP feeds.

In the second case LDAP feeds is probably not the best or only module you'll need. This d.o article covers some ground but there are important gaps, but also some good linked resources in that section that could be of great help to you depending on your needs.

There are a plethora of variants on these cases. One time vs ongoing, update bi-directional or with one resource overwriting the other as authoritative, updating non-user entities and keeping them in reference to users, and many more. This split is designed to identify the most likely cases from the question you asked.

If this is one-time, an option (not ideal) may be to bring the users into an interim D7 instance and then migrate them to D8. This could be done repeatedly but would require a standing D7 instance to maintain. I'd only suggest this until the D8 LDAP feeds project is further along. It could give you time to dig in and contribute as well. ;)

Giving this further thought and since the module isn't fully ported, this could be done with a server cron, a little scripting and a docker D7 instance. A nightly docker spin up, pull from LDAP into D7 and migrate users to D8. It's far from a good solution. But it sounds like your need is immediate and this would work. If time isn't a factor either porting the module yourself or paying someone to do it is the best path.

I'm happy to amend or expand this answer as needed based on additional information added in your question.
> 1 votes

---
Tags: 8, users, feeds, importing-exporting, authentication-authorization
---


# Question
Title: Where are features displayed after they are created?
I just created a feature on one site for copying to another and on the site I created the feature it doesn't appear in the list of features, and I am sure I didn't delete it.

When features are created on a site as opposed to being installed do they remain in the UI or do they have to be installed as well to appear in the site's Features UI?

Is there a module that provides a UI for managing the Features which are created on a site but not installed there?

# Answer
I think its important to know that essentially, Features result in modules that capture site configuration.

Fundamental differences in D7 and D8 with what Features is designed to accomplish with configuration essentially in Core.

However, if you create a feature and "write" as opposed to "download" the UI should show your saved configuration. This section of d.o gives some detail.

You may prefer to try downloading features once they are what you want, and commit them to a git repo. Much safer and stable working this way in my experience.
> 0 votes

---
Tags: 7, features
---


title: Class loader not finding form class

text:
# Question
Title: Class loader not finding form class
I am trying to create a custom form in my drupal 8 instance, and I have followed a few different tutorials, but every time I try to go to the forms path I see the following error on the page:

```
The website encountered an unexpected error. Please try again later.

```

When I check my apache log, I see it came because of this error:

Uncaught PHP Exception InvalidArgumentException: "Class "Drupal\report\_service\_call\Form\ReportServiceCallForm" does not exist." at /var/www/html/abcnj/core/lib/Drupal/Core/DependencyInjection/ClassResolver.php line 24

I do have my ReportServiceCallForm set up at the following path under my module:

lib/Drupal/report\_service\_call/Form/ReportServiceCallForm.php

this is the contents of that file:

```
<?php
/**
 *@file
  *Contains /Drupal/report_service_call/Form/ReportServiceCallForm
  */

  namespace Drupal\report_service_call\Form;

  use Drupal\Core\Form\FormBase;
  use Drupal\Core\Form\FormStateInterface;
 /**
  *Implements Drupal form Interface
  */
 class ReportServiceCallForm extends FormBase{

 /**
  *{@inheritdoc}
  */
  public function getFormID(){
     return 'report_service_call_form';
  }
 /**
  *{@inheritdoc}
  */
public function buildForm(array $form, array &$form_state){
  $form['company_name'] = array(
    '#type'=> 'textfield',
    'title'=> $this->t('Company Name')
  );

$form['cotact_name'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Contact Name')
);

$form['current_system_type'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Current System Type')
);

$form['telephone_number'] = array(
  '#type'=> 'tel',
  'title'=> $this->t('Telephone Number')
);

$form['email'] = array(
  '#type'=> 'email',
  'title'=> $this->t('Email Address')
);

$form['service_request'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Service Request')
);

$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
    '#button_type'=>'primary',
);
return $form;
}

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

  }

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

  }
}

```

Also I have the contents of my routing.yml as follows:

```
report_service_call.form:
    path: '/Customer-Service/Report-Service-Call'
defaults:
  _title: 'Report Service Call Form'
  _form: 'Drupal\report_service_call\Form\ReportServiceCallForm'
requirements:
  _permission: 'access content'

```

# Answer
> 5 votes
The file needs to be located at `[MODULE FOLDER]/src/Form/ReportServiceCallForm.php`

---
Tags: 8, forms
---


title: How do I print main_menu?

text:
# Question
Title: How do I print main_menu?
I try to render a main menu but it doesn't render. My old Drupal 6 template try to upgrade Drupal 7 template.

I've render in page.tpl.php.

```
<?php if (isset($main_menu)) : ?>
    <?php print phptemplate_primary($main_menu); ?>
  <?php endif; ?>

```

This is the code for `phptemplate_primary()`.

```
function phptemplate_primary() {
  $output = '<div id="primary-links-region">';
  $element = menu_tree(variable_get('menu_primary_links_source', 'primary-links'));
  $output .= drupal_render($element);
  $output .= '</div>';
  return $output;
}

```

How do I resolve this problem?

# Answer
> 1 votes
You can do it both ways:

1. You can add menu block to your template - just like any other block (this method is the easiest).
2. If you need more customization, you can do it in template:

page.tpl.php

```
<?php if ($primary_nav): print $primary_nav; endif; ?>

```

template.php

```
if (isset($variables['main_menu'])) {
  $variables['primary_nav'] = theme('links__system_main_menu', array(
    'links' => $variables['main_menu'],
    'attributes' => array(
      'class' => array('links', 'inline', 'main-menu'),
    ),
    'heading' => array(
      'text' => t('Main menu'),
      'level' => 'h2',
      'class' => array('element-invisible'),
    )
  ));
}
else {
  $variables['primary_nav'] = FALSE;
}

```

---
Tags: 7
---


# Question
Title: How to show all subterm nodes of a parent term with the simple_hierarchical_select module?
I use drupal 7 and simple\_hierarchical\_select module.

I have a vocabulary called "news group" that has two level term (parent term and subterm) like the attached picture:

When I use exposed filter and simple hierarchical select for this (select term reference filed for "news group vocabulary") views filters show me two select list.first level list show parent terms (like HSE) and when select any option from first select list another select list appear that contain subterms of this parent term (like 5 subterm of HSE term) So I must select a option from **Secound select list (subterms)** to have any result for my view.

I want to filter views results by first level (parent term) of taxonomy (like HSE) . But the Simple\_hierarchical\_select module Does not support first level of terms.must select deepest term for result.

I am not selected "force use to select deepest level" in field settings of term reference field.

Is any way to force SHS module to filter **all subterms of a parent term**? Is another module for add "select all subterms of a term" feature to views exposed filter?

# Answer
I found this issue solution after 2 weeks searching and experiments. in views filter add "Simple hierarchical select - taonomy **with dept**" and in dept field of **settings of this filter select 1** . Now , when select a parent term , secound term with dept 1 has been showing too.
> 1 votes

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: Is there a way to add a timestamp to messages print from drupal_set_message()?
Sometimes when I am editing I may accidentally edit the same page in different tabs, or I might forget whether I have updated the page earlier or not. I use a Save and Edit button when saving and when I save I want to know when I last saved based on the notice in at the top of the page, where I normally see a message like the following.

>

There is some sample code for a module that changes the message handling - https://atendesigngroup.com/blog/drupal-7-drupal-8-customize-or-remove-node-creation-message. How could I change it just to add a timestamp to the message?

# Answer
> 0 votes
I found a solution from the related questions Simple way to change messages after node creation.

The solution uses Rules to accomplish it, but the OP mentions a Custom Submit Messages which didn't work for Drupal 7 at the time of the question but has been updated since them.

# Answer
> 1 votes
The problem is that at the point where these hooks are being used you have SESSION and FORM available and what you're asking for is a NODE attribute.

This can be done, simply loading the given NODE under the right conditions... but one should recognize doing this does have broader impact as these hooks are called fairly frequently.

How node\_load is done is accomplished very differently in D7 and D8, not sure which one you're using from the question. Lots of answers out there how to render fields from a node. One more tip; your D7 install should have entity - the future proof method of getting node values is probably entity\_load as nodes are entities in late D7 and all of D8...

---
Tags: notifications, status-messages
---


title: How do I discover property names?

text:
# Question
Title: How do I discover property names?
When doing a custom D7 to D8 migration, i sometimes need to migrate a specific value such as 'fid' (for example file ID of an images) into the

```
'field_image/target_id'

```

property. How do I find out which property i can use for D8 fields? By property i mean the `target_id` part. For example for `uid` field? The devel module does not seem to be helpful here, or I may be wrong.

# Answer
You can use the EntityFieldManager. This is an example how to get the properties for the field `uid` of the entity `node`:

```
$fields = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node');
$properties = $fields['uid']->getPropertyDefinitions();

```

From the command line you can use this in a `drush php-eval` command:

```
drush ev "var_dump(\Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node')['uid']->getPropertyDefinitions())"

```
> 0 votes

---
Tags: entities, migrations
---


# Question
Title: Views Better exposed filter, input required
In which hook\_ of the views.api can i hide the results if no exposed inputfilter is selected.

I tried:

hook\_views\_query\_alter($view, $query) {

```
if($view->getExposedInput() ...) {
 // Do not show any results, make clear no results should be shown..
}

```

Or

```
hook_views_pre_render($view) {
    if($view->getExposedInput() ...) {
      $view->result = array();
      // But pager still shown and $view->getPager()->destroy() gives error.
      // Also feels wrong, query should not be executed.
    }
}

```

Any suggestions, solutions, .... Thx!

# Answer
> 1 votes
Solved it by adding condition which yields no result.

```
hook_views_query_alter($view, $query) {
    // Don't show any result if exposed filter empty.
    $exposed_input = $view->getExposedInput();
    if(!isset($exposed_input['field_partner_address_country_code']) || $exposed_input['field_partner_address_country_code'] == 'All') {
      $query->addWhere(NULL, 'node_field_data.nid', 0);
    }
}

```

---
Tags: 8, views
---


# Question
Title: Bootstrap Views Grid Unable to specify Medium and Small device classes
I am currently using https://www.drupal.org/project/views\_bootstrap and successfully created a Bootstrap Grid

For each grid item I get the following output as the root most div tag

```
<div class="col col-lg-4">

```

But I need to add more class names as follows

```
<div class="col-lg-4 col-md-4 col-sm-12">

```

is there a facility to provide additional classes which needs to be added in the root component of each rendered view content?

# Answer
I had a similar issue some months ago. It seems Bootstrap Views allows this possibility, but only in the `dev` release, not in the latest stable release.

In order to do what I wanted in the stable release of the module, I ended up with the following solution:

```
/**
 * Implements preprocess_views_view__VIEW().
 */
function scicnet_preprocess_views_view__MY_VIEW(&$vars) {
  $display_id = $vars['display_id'];
  switch ($display_id) {
    case 'MY_DISPLAY':
      $vars['rows'] = str_replace('col-lg-4', 'col-lg-4 col-md-4 col-sm-12', $vars['rows']);
      break;
  }
}

```

Not the most elegant solution, I admit, but it does the job...
> 0 votes

---
Tags: 7, views
---


# Question
Title: How can I limit the number of email sent per hour in a rule?
I have installed Mime mail and Mail System modules. I use an action in a rule:

> Send HTML mail to all users of a role

to send an email to a set of users.

Is there anyway I could limit the number of email sent per hour? For example, if the execution of this rule has to send 100 emails, It will be sent in blocks of 50 emails per hour.

I think It should be queue in cron.

# Answer
> 1 votes
Below is a summary of how you can get this to work:

1. Use the Flag module and introduce a flag to allow "flagging" all those "*users of a role*" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
2. Adapt the rule you already have, like so:
3. Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged users (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first 50 users only (50 is the value that seems to fit your needs).
4. Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

* Send HTML mail to each of the users in that VBO list.
    * Unflag (using flag from step 1) the user for which you just produced an eMail. This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the execution of the same rule within 1 hour (1 hour is the value that seems to fit your needs).
5. Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every hour, Rules will notify 50 users "as requested".

---
Tags: 7, rules, emails
---


title: t() strings can't able to translate

text:
# Question
Title: t() strings can't able to translate
I'm wondering that Drupal **t()** strings are not available for the translation.

Let me explain what I did. I'm going to make my site as multilingual (English & Dutch). English is my source language.

For this, I have added locale module and enabled English and Dutch language.

Then I installed Entity Translation && i18n module on my site.

And then I wanted to show some multilingual text in the user profile edit form. Hence I put form alter and given some string inside t('My topics').

Then I went to **/admin/config/regional/translate/translate** this page to add a translation for my custom string "My topics". But it not available there.

Where did I'm going wrong?

I'm using \- Drupal 7.54 \- Enabled Drupal's core **locale** module \- Entity Translation(7.x-1.0-beta6) \- Internalization (7.x-1.17)

# Answer
> 0 votes
I have found the solution.

Initially, my site is in English(source language).

We have to switch the language to other languages on the site(in my case it is Dutch) using this path **admin/config/regional/language**. Then, we have to view the page which is consists of t(). Then only the t() strings would register for translation.

Now go to **admin/config/regional/translate/translate** and search your t() string, it will be available and add translation !!!

---
Tags: i18n-l10n
---


# Question
Title: How can I pass parameters to allowed_values_function for a field?
Tried these 3 ways... none of them work.

```
->setSettings(array(
    'allowed_values' => array(),
    'allowed_values_function' => '\Drupal\xrm_core\Util\DefinedValuesListUtil::getRegionValues',
    'allowed_values_function_arguments' => '["country_id", 0]',
  ))

  ->setSettings(array(
    'allowed_values' => array(),
    'allowed_values_function' => '\Drupal\xrm_core\Util\DefinedValuesListUtil::getRegionValues(1)',
  ))

  ->setSettings(array(
    'allowed_values' => array(),
    'allowed_values_function' => '\Drupal\xrm_core\Util\DefinedValuesListUtil::getRegionValues\1',
  ))

```

This particular feature seems totaly undocumented in existing drupal docs. Any ideas to point me in the right direction please?

# Answer
> 2 votes
It's undocumented because it's not possible with core classes.

The options.api.php file refers to that callback as follows:

> That function will be called:
>
> * either in the context of a specific entity, which is then provided as the $entity parameter,
> * or for the field generally without the context of any specific entity or entity bundle (typically, Views needing a list of values for an exposed filter), in which case the $entity parameter is NULL.

There's no mention of being able to pass arbitrary parameters along to it. Indeed if you look at the invocation in `options_allowed_values`

```
$function = $definition->getSetting('allowed_values_function');
...
$values = $function($definition, $entity, $cacheable);

```

You can see that there's no scope for passing extra params at all.

Hopefully you'll be able to get the required context from the entity, otherwise you'll need to find another way to make it available to your callback function.

---
Tags: entities
---


# Question
Title: Can view HTML and PHP I wrote but install.php returns error
I installed Drupal8 for the first time to try things out. I used nginx and mySQL on FreeBSD with php-fpm for fastcgi. I have the nginx root set to `/usr/local/www/drupal8` cause that's where the `install.php` file is. If I put a HTML file in there, I can view it with `localhost/index.html`. If I write a little `info.php` file, it runs and shows the expected `phpinfo()` data but if I try to do `localhost/install.php`, the address bar changes to `localhost/core/install.php` and nginx returns a `502 Bad Gateway` and the nginx error log shows this:

> Call to undefined function Doctrine\Common\Annotations\token\_get\_all() in /usr/local/www/drupal8/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php on line 56" while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /core/install.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm.sock:", host: "localhost"

I see this error in a few Google searches but the solutions are related to special programs or programmer errors. I followed directions on setting up php.ini and copied settings.php. I don't know what to do or where to look to fix this.

# Answer
> 0 votes
I installed Drupal8 from FreeBSD ports. I don't normally use PHP for anything so PHP version 5.6.30 is what is on my computer so either that is what Drupal used or that's what the port installed. I don't know why PHP7 was not installed instead.

In FreeBSD, the tokenizer extension is not automatically installed so I added php56-tokenizer and now Drupal8 works.

---
Tags: installation, configuration, 8
---


# Question
Title: How can I find all the listeners or subscribers to the KernelEvents:REQUEST event?
More specifically, how could I find the subscribers performing the routing system for Drupal?

We tried using `ddebug_backtrace()`, but I couldn't get anything.

# Answer
Instead of ddebug use the Symfony Webprofiler, that is included in the D8 version of the module Devel:

https://www.drupal.org/project/devel

**WebProfiler (D8+)**

Add a powerful footer to all pages of your site. There, admins can review resource utilization, cache effectiveness, database queries, Views, and so much more.
> 0 votes

---
Tags: routes, debugging
---


title: Attach library to a specific page

text:
# Question
Title: Attach library to a specific page
I am developing a custom module in Drupal 8. My custom module include many JavaScript and CSS files which make the site really slow and I don't want them in all pages. I have developed some custom blocks and each JavaScript and CSS library correspond to a block. I want those files on those pages of the site where my custom blocks are visible.

In my last Drupal 8 project, I have done something like the following.

```
function HOOK_page_attachments(array &$attachments) {
    $user = \Drupal::currentUser()->getRoles();

    if(in_array("administrator", $user)){
        $attachments['#attached']['library'][] = 'module/library';
    }
}

```

I am not sure how to check which blocks are visible in the page.

# Answer
> 5 votes
You have to attach the library to block content, hopefully code below should help

```
$build['#attached']['library'][] = 'module/library';

```

# Answer
> 7 votes
If you're using a twig template, you can add it there.

```
{{ attach_library('module/library') }}

```

Which is helpful when you want to control whether the library loads before or after the content.

https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

# Answer
> -1 votes
Resolving this doubt: I am not sure how to check which blocks are visible in the page.

block.module have a service that you can invoke:

```
getVisibleBlocksPerRegion()

```

https://api.drupal.org/api/drupal/core%21modules%21block%21src%21BlockRepository.php/function/BlockRepository%3A%3AgetVisibleBlocksPerRegion/8.2.x

I think that you can use it to resolve your case.

And in other hands is not the best practice check the use role, maybe will be better check the permissions that you want to check. If you want in the future, that another role can see the block, you cannot do it without grant the administrator role to this user.

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


# Question
Title: How to implement template file that would reside in database?
I was wondering if it would be possible to have a template "file" that would be stored only in DB and would not exist physically?

Twig tempaltes are parsed from files only once and they are processed and stored in DB anyway so would it be possible to have such DB entry from the get-go?

# Answer
You can register a loader, see `Drupal\Core\Template\Loader` for the implementations that drupal core uses and their parent classes/interfaces.

See also how they're registered in core.services.yml, for example:

```
twig.loader.filesystem:
    class: Drupal\Core\Template\Loader\FilesystemLoader
    arguments: ['@app.root', '@module_handler', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 100 }

```

So, it's certainly possible to do it, if it's a good idea is another question ;)
> 3 votes

# Answer
Based on @Berdir suggestion I have created my implementation like this(just finished so probably som fine-tuning will take place):

```
/**
 * Twig loader that uses the database as backend for templates.
 */
class DatabaseLoader implements \Twig_LoaderInterface {

  /**
   * The name of the template collection in the backend storage.
   */
  CONST COLLECTION = 'twig_templates';

  /**
   * The key value backend service.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $key_value;

  /**
   * The list of all templates stored in the database backend
   * for the currently active theme. Each key is the template name
   * and each value is the UNIX timestamp of last change made to the template.
   *
   * @var array
   */
  protected static $registry = NULL;

  /**
   * Static cache for loaded templates keyed by their name.
   *
   * @var array
   */
  protected static $templates = [];

  /**
   * Constructs a new DatabaseLoader object.
   *
   * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value
   *   The key_value storage backend service.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler service.
   */
  public function __construct(KeyValueFactoryInterface $key_value, ThemeHandlerInterface $theme_handler) {
    $this->key_value = $key_value->get(static::COLLECTION);
    $this->theme = $theme_handler->getDefault();
    $this->registryLoad();
  }

  /**
   * Helper method to load the registry from the storage.
   */
  protected function registryLoad() {
    if (is_null(static::$registry)) {
      static::$registry = $this->key_value->get('registry_' . $this->theme, []);
    }
  }

  /**
   * Helper method to write registry into the storage.
   */
  protected function registryUpdate() {
    $this->key_value->set('registry_' . $this->theme, static::$registry);
  }

  /**
   * Helper method to flush the registry.
   * This method is called when the site cache is being flushed
   * and it will set timestamps for all templates to current time
   * so all templates will indicate they need to be rebuilt.
   *
   * @see foo_rebuild()
   */
  public function registryRebuild() {
    static::$registry = array_fill_keys(array_keys(static::$registry), REQUEST_TIME);
    $this->registryUpdate();
  }

  /**
   * Helper method to normalize the template name.
   * For example "profiles/foo/themes/bar/templates/system/html.html.twig"
   * will get transformed into "html".
   *
   * @param string $name
   *   The full template name.
   *
   * @return string
   *   Normalized template name.
   *
   * @throws \Twig_Error_Loader
   *   If inline template is provided.
   */
  public function normalize($name) {
    if (stripos($name, '{') !== FALSE) {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }

    $split = explode('/', $name);
    return explode('.', end($split))[0];
  }

  /**
   * Helper method to get the storage key for provided template.
   *
   * @param string $name
   *   The template name.
   *
   * @return string
   *   The key-value storage collection key for the provided template.
   */
  protected function getKey($name) {
    return $this->theme . '.' . $name;
  }

  /**
   * Upserts a template into the storage.
   *
   * @param string $name
   *   The template name.
   * @param string $template
   *   The content of the template.
   */
  public function saveTemplate($name, $template) {
    $this->key_value->set($this->getKey($name), $template);
    static::$templates[$name] = $template;

    static::$registry[$name] = time();
    $this->registryUpdate();
  }

  /**
   * Deletes provided template.
   *
   * @param string $name
   *   Template name.
   */
  public function deleteTemplate($name) {
    if (isset(static::$registry[$name])) {
      $this->key_value->delete($this->getKey($name));
      unset(static::$templates[$name]);

      unset(static::$registry[$name]);
      $this->registryUpdate();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getSource($name) {
    $name = $this->normalize($name);

    if (isset(static::$registry[$name])) {
      if (!isset(static::$templates[$name])) {
        static::$templates[$name] = $this->key_value->get($this->getKey($name), '');
      }
      return static::$templates[$name];
    } else {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheKey($name) {
    $name = $this->normalize($name);

    if (isset(static::$registry[$name])) {
      return $name;
    } else {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function isFresh($name, $time) {
    $name = $this->normalize($name);

    if (isset(static::$registry[$name])) {
      return static::$registry[$name] <= $time;
    } else {
      throw new \Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
    }
  }

}

```

The service:

```
foo_twig_db_loader:
    class: Drupal\foo\Template\Loader\DatabaseLoader
    arguments: ['@keyvalue', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 101 }

```

The module file:

```
/**
 * Implements hook_rebuild().
 */
function foo_rebuild() {
  \Drupal::service('foo_twig_db_loader')->registryRebuild();
}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to create a block of links shared by a user?
I am using oembed to convert url to embedded content. I have enabled the oembed input filter in a text format. Now I want to create a block using views to only show the posts which have these links. How to do that?

Note: I want to use it on a custom form. Is there something which can detect embedded content in a view. By this I will be able to create a separate view/block containing the embedded content.

# Answer
Just wanted to make sure you've tried this simple approach. Create a check-box field for the all posts (whatever content-type it is) you were referring to with options embedded or non-embedded and create a view with a filter to only display embedded content.

Edit: Have a checkbox for the content-type (responsible for posts) which asks anyone creating posts if they are using the oembed text filter, give a description to check "embedded content" if they are. Then create a view and pull all the posts by setting the filter- "CheckboxName (isOneOf) Embedded content".
> 1 votes

---
Tags: 7, views, navigation, media
---


# Question
Title: How do I list modules on my site that are not covered by the Drupal security advisory policy?
We have a number of contributed modules installed on a Drupal 7 site, but there doesn't seem to be an easy way to see those covered by the Drupal security advisory policy, without copy-pasting each module name into the address bar and manually checking the page.

Is there a way to do this with Drush?

# Answer
> 1 votes
I'm not aware of a report (a good home for such a thing might be the Site Audit project? (#2882555)

Here's a *very* quick report for D7 that shows:

* Custom modules
* Modules without a release covered by Security Policy

You can download this and use it with `drush scr`, or copy it for `drush eval` directly. Feel free to improve on it!

```
<?php
$projects = update_get_available(true);
$uncovered = [];
foreach ($projects as $name => $project) {
  if (!isset($project["releases"])) {
    $uncovered[$name] = "No releases found";
  }
  else {
    $latest_release = reset($project["releases"]);
    if (!empty($latest_release["security"])) {
      $uncovered[$name] = $latest_release["security"];
    }
  }
};
print_r($uncovered);

```

---
Tags: 7, drush
---


# Question
Title: Getting configurePhpcs is not callable after update drupal to 8.3.2
I updated drupal with composer `composer update`

Drupal is updated to 8.3.2 but when I install modules I get anytime this message

`Method Drupal\Core\Composer\Composer::configurePhpcs is not callable, can not call post-auto load-dump script`

how to make configurePhpcs callable again?

Website is still working,

# Answer
I assume, that after the Drupal core update, you've overwritten composer.json with your previous settings.

However, in Drupal 8.3.2, configurePhpcs has been deleted. This part of composer.json (around line 69 has to be changed:

```
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
        "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "Drupal\\Core\\Composer\\Composer::configurePhpcs"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},

```

You have to delete configurePhpcs line (and the comma at the end of the line above, so it should look like this:

```
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
        "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},

```

Then, you won't see the message anymore.
> 1 votes

---
Tags: 8, updating, composer
---


# Question
Title: Getting the value of taxonomy field in a node.html.twig template (Drupal 8.x)
I'm currently trying to figure out how to get the value of a field of a node in node.html.twig template. The field (machine\_name: news) is linked to a taxonomy and multiple values can be selected. I see a lot of threads here on Drupal StackExchange - tried all the solutions, but not a single one fixes my problem.

I'm currently trying:

> {{ node.field\_news\[0\].value }}

But then nothing is printed. When I try:

> {{ node.hasField('news') }}

... the value '1' is printed. So the field is available. I tried dumping the whole 'node' object using the Twig dump() method, but then I get a white-screen-of-dead due to memory restrictions.

Any idea's what is the correct way? I'm using Drupal 8.3.2

# Answer
I found the problem. The 'news' field is a multi-value selectable field. The correct way to access the field would be:

```
{{ content.news.0 }}

```

Of course, this will only print the first value in the collection, so I created a for loop in the twig template to loop over the different values.

I needed the 'title' and the 'url' of the taxonomy term. This could be retrieved by:

```
{{ content.news.0['#title'] }}
{{ content.news.0['#url'] }}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: how can i define a maintenance template within a custom module?
i have done this within a module for defining custom templates when having status error

```
function custom_module_preprocess_region(&$vars) {

  $header = drupal_get_http_header('status');

  if( $vars['region'] == 'content' ) {
if ($header == '404 Not Found') {
  $vars['theme_hook_suggestions'][] = 'content__404';
}
if ($header == '403 Forbidden')  {
  $vars['theme_hook_suggestions'][] = 'content__403';
}
 }
 }

 function custom_module_theme() {
   return array(
'content__404' => array(
  'template' => 'region--content--404',
  'variables' => array('xxx' => null),
  'path' => drupal_get_path('module', 'custom_module').'/templates'
),
'content__403' => array(
  'template' => 'region--content--403',
  'variables' => array('xxx' => null),
  'path' => drupal_get_path('module', 'custom_module').'/templates'
),
'maintenance' => array(
  'template' => 'region--content--maintenance',
  'variables' => array('xxx' => null),
  'path' => drupal_get_path('module', 'custom_module').'/templates'
),
 );
 }

```

How can i implement it just the same to override the theme maintenance tpl ?

# Answer
> 1 votes
**drupal\_get\_http\_header()** *should be treated as deprecated.*

See https://www.drupal.org/node/1969270#comment-7609337

I think your approach is good, but for a little more coverage of 404/403 pages we came up with a more extendable approach, also theres a bit more room for customization in the backend within the modules settings page.

We did this by using the **customerror module** in conjunction with a theme function and a few overriding template files.

https://www.drupal.org/project/customerror

After installing, add this to your **template.php** file's *theme\_preprocess\_page* function. Example;

```
function YOURTHEME_preprocess_page(&$variables) {

  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'customerror') {
    if ($alias_parts[1] == '403') {
      $variables['theme_hook_suggestions'][] = 'page__forbidden';
    }
    if ($alias_parts[1] == '404') {
      $variables['theme_hook_suggestions'][] = 'page__not_found';
    }
  }

  <other code goes here>

}

```

Then in your **templates** folder add your custom templates (just like your page.tpl.php file);

* **page--forbidden.tpl.php**
* **page--not-found.tpl.php**

Clear your cache, hit one of those pages (you can test them by going to);

* **\[yoursite\]/customerror/403**
* **\[yoursite\]/customerror/404**

As for your maintenance page, all you need to do is create a **maintenance-page.tpl.php** file and toss that in your templates folder.

---
Tags: 7, theming
---


# Question
Title: <a> and <img> links not generated as https:
I am new to Drupal and having an issue relating to SSL. The view I'm working with is using the jcarousel module to display images with links.

The data contains a link and image source. All of the links are entered using relative paths to the root of the site.

The home page has 5 links on it. When the you look at the source from the generated page, 2 of the links are `https` and the other 3 `http` even though none have the base URL in the link data.

I have added `$_SERVER['HTTPS'] = 'on';` to settings.php but that hasn't corrected the issue.

What is the proper way to force both tags to be generated with https: links?

# Answer
Take a look at this answer, I believe it goes into great detail about enabling SSL support on pages and image assets for Drupal 7;

How to force drupal 7 to load HTTPS assets?

Also if your still having problems, take a look at this documentation on drupal.org;

https://www.drupal.org/https-information

Hope that helps!
> 0 votes

---
Tags: 7, views
---


# Question
Title: how to get the NodeID into views-view-field--field-image.tpl.php to create an <a href> redirect
this is my code:

```
<div class="img-wrapper">
  <div class="content">

  <?php $nodeurl = url('articles/' . $node->nid); krumo($node->nid); ?>
  <a href="<?php echo $nodeurl ?>"

    <div class="img-container <?php print $imageClass; ?>">

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

```

my code is not fetching a proper nodeID and when i krumo it (inspect passed elements) it brings back a null value. My code seems correct, can i get some help :)?

# Answer
This is in a view correct? I believe you need to use `node_load($nid)` to load the node data first in order to fetch it. I would try something like this

```
$node = node_load($nid);
$nodeurl = url('articles/' . $node->nid);

```
> 0 votes

---
Tags: views
---


# Question
Title: Checking site performance on remote vs. locally
I had read a blog article recently describing how to set the settings on your local host to be a reasonable comparison to a remote host in order to test Drupal configurations and performance issues before pushing code up to the remote.

What settings should I change? Is it true that the performance should be about the same if the settings are comparable?

# Answer
> 1 votes
a: Make your settings the same as your production system.

b: Performance measurements are only meaningful if you compare apples to apples. Your test environment needs to match your production environment - same cpus, same ram, same everything. A dev workstation rarely performs the same way as a web server. It's better to have a duplicate of your production system to use for testing / staging. i.e. if you were using amazon, you'd want second ec2 instance that matches your production system.

---
Tags: performance
---


# Question
Title: How to get error messages to display on the form, rather than after the page is refreshed?
I have a form that has radio buttons and the user needs to select at least one option. If they do, a modal window will pop-up. If they don't, I need to redisplay the form with the saved values and the message "Please select one item" in the message area. Right now, if they don't select one item nothing happens and then the message is displayed after the page is refreshed.

```
public function buildForm(array $form, FormStateInterface $form_state, $form_config = NULL)
{
    if (!empty($form_state->getBuildInfo()['args']['form_ajax'])) {
        $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
        $form['actions']['submit']['#ajax'] = [
            'callback' => '::crmform_ajax_submit',
        ];
    }
    return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state)
{
    $selected = $this->crmform_validate_element_selected($form_state, 'radio');
    if (!$selected) {
        $form_state->setErrorByName('form', t('Please select one item'));
    }
}
public function crmform_ajax_submit(&$form, FormStateInterface $form_state)
{
    $errors = $form_state->getErrors();
    $response = new AjaxResponse();
    if (!empty($errors)) {
       $form_state->setRebuild();
       return $response;
    }
    $response->addCommand(new OpenModalDialogCommand($dialog_title, $form_data, $options));
    return $response;
}

```

# Answer
> 1 votes
You can use contributed module Clientside Validation which is very close to your requirement.

> This module adds clientside validation (aka "Ajax form validation") for all forms and webforms using jquery.validate. The included jquery.validate.js file is patched because we needed to be able to hide empty messages.

---
Tags: forms, debugging
---


# Question
Title: Where can you change the #type of a checkbox?
I have content type with a taxonomy attached to it (since it is Drupal 8, it ends up being an Entity Reference field). The form is configured to render out this field input as checkboxes.

I have run into a situation where I need to change some of the checkboxes into plain text when the form is rendered (node create, note edit etc). I tried to push a `#process` function onto the field,

```
function MYMODULE_form_node_job_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['field_foo']['widget']['#process'][] = 'MYMODULE_foo';
}

function MYMODULE_foo(&$element, FormStateInterface $form_state, &$complete_form) {
  // do stuff
}

```

but when I inspect the `$element` with XDebug, the `#options` haven't been processed yet.

So, where in the form / render pipeline can this be changed?

# Answer
Beside preprocess you can add code to the rendering of form elements in `#pre_render`, `#theme`, `#theme_wrappers` and `#post_render`. Part of the rendering pipeline of checkboxes is for example `CompositeFormElementTrait::preRenderCompositeFormElement`:

```
  public static function preRenderCompositeFormElement($element) {
    // Set the element's title attribute to show #title as a tooltip, if needed.
    if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
      $element['#attributes']['title'] = $element['#title'];
      if (!empty($element['#required'])) {
        // Append an indication that this field is required.
        $element['#attributes']['title'] .= ' (' . t('Required') . ')';
      }
    }

    if (isset($element['#title']) || isset($element['#description'])) {
      // @see #type 'fieldgroup'
      $element['#attributes']['id'] = $element['#id'] . '--wrapper';
      $element['#theme_wrappers'][] = 'fieldset';
      $element['#attributes']['class'][] = 'fieldgroup';
      $element['#attributes']['class'][] = 'form-composite';
    }
    return $element;

```
> 3 votes

---
Tags: forms
---


# Question
Title: After deleting all nodes, how do I reset the node ID to start from 1 again?
I generated tons of dummy content for testing, and then deleted them all. As nid is auto-increment, newly created node will have a nid of last created nid +1.

How can I make nid start from 1 again?

# Answer
Plase don't truncate the node table just like that, there are some other tables connected to the node table, like node\_revisions, sequences, fields tables, taxonomy tables, and many more.

There is no secure way to do this, it really depends on your site, you'll have to truncate and adjust all tables that have an nid including the sequences table. Remember, it is highly probable that your site become unusable, so don't start without a backup first.
> 12 votes

# Answer
```
ALTER TABLE `node` AUTO_INCREMENT = 1;

```

P.S - Others who have replied on this question: I just did a small check after deleting content and the associated content is indeed deleted, node\_revisions and field\_\* tables are empty. node\_delete says the same - http://api.drupal.org/api/drupal/modules--node--node.module/function/node\_delete\_multiple/7

Sometimes on migrations projects when you migrate from other platforms (ex. ASP + MSSQL), sometimes it becomes unavoidable to reset the nid due to lot of factors. I am sure it could be avoided but time/code tradeoff is always there.
> 16 votes

# Answer
You can use the module Delete all with the following drush commands:

**Drupal 7**

Delete nodes of all types, and reset node, revision and comment counters.

```
drush delete-all --reset

```

**Drupal 8**

see here

Deletes all content of all types.

```
drush delete-all-delete-content

```

And then:

```
ALTER TABLE `node` AUTO_INCREMENT=1;
ALTER TABLE `node_revision` AUTO_INCREMENT=1;
ALTER TABLE `node_field_data` AUTO_INCREMENT=1;
ALTER TABLE `node_field_revision` AUTO_INCREMENT=1;

```
> 3 votes

# Answer
SQL Query: `ALTER TABLE 'node' AUTO_INCREMENT=1;`

Make sure you have deleted all nodes before doing this.
> 2 votes

# Answer
you can truncate node table but, pay attention you must truncate relational field table, if you just want to start increment id from 1 you can use of

```
ALTER TABLE  `node` AUTO_INCREMENT=1

```
> 0 votes

---
Tags: 7
---


# Question
Title: Should a hook_form_alter be firing both on render and when an additional submit handler is fired?
I am trying to add an additional submit handler to the user login form, to simply redirect users to the page they were on before landing on the login page (/user/login).

I have the following code attempting to store the current path/destination in the $form\_state storage which is working as I expected when the original form\_alter is run on render as it alters the redirect property of form\_state to the previous page.

However, when the form is submitted, the form\_alter is fired *again*, but this time the form\_state storage is empty, thus the current\_path/destination is now set to /user/login which is not where the user should be redirected to.

Here is the code I have at the moment, any help would be appreciated as to why the form\_alter is run again on form submit:

```
function MODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = '_module_custom_user_login_form_submit';
  if (is_null($form_state->get('redirect_dest'))) {
    $destination = $_SERVER['HTTP_REFERER'];
    $form_state->set('redirect_dest', $destination);
  }
}

function _module_custom_user_login_form_submit($form, FormStateInterface &$form_state) {
  $destination = $form_state->get('redirect_dest');
  $form_state->setRedirect($destination);
}

```

# Answer
I think the chain of events is different. The form gets cached with no or the wrong redirect\_dest set. Then the form is submitted and redirected to the form itself. This is now a new form build, because you didn't request a rebuild. Only in a rebuild you keep the form\_state.

Solution:

Drupal has the feature to redirect built in. Add the destination on the page linking to the user login:

```
Url::fromRoute('user.login', [], ['query' => $destination])

```

**Edit (new module):**

To add the destination automatically you can use this module:

https://www.drupal.org/sandbox/gnuget/2824414

This is a js solution, so it doesn't interfere with caching. I think in this case you can use a sandbox module, because the site won't break if the js code stops working.
> 1 votes

---
Tags: 8, forms, users
---


# Question
Title: How to make an upsert query with two keys?
I have a custom table with a primary key made from two fields (route, uid) and I want to use the upsert() method to insert or edit a record. The problem is that the key() method only accept one key which will be used to identify the existing row. But I have two (route and uid)

> Sets the unique / primary key field to be used as condition for this query.

```
public function key($field) {
  $this->key = $field;

  return $this;
}

```

Maybe I'm missing something or I misunderstand the `upsert()` method. So, Can I make an upsert query with two keys?

**Edit:** I'm using mysql.

# Answer
At this moment I don't know why but if I use only one key the query works as expected (using the two database keys as a key in the upsert, when I only says `$query->key('route');`):

```
$route = \Drupal::routeMatch()->getRouteName();
$uid = $this->currentUser->id();

$query = $this->connection->upsert('forcontu_database_counter')
          ->fields([
    'route' => $route,
    'uid' => $uid,
    'user_count' => 1,
    'lastcount' => time(),
  ]);
$query->key('route');
$query->execute();

```

If I change the `uid` (using a diferent user in the site) in the same `route` (page) Drupal insert a new record (don't make an update in the existing route) and I only use one key, in this case `route`.

**EDIT:**

This always will work because if you see the code inside the \__toString() function the key property is never used:

```
public function __toString() {
    // Create a sanitized comment string to prepend to the query.
    $comments = $this->connection->makeComment($this->comments);

    // Default fields are always placed first for consistency.
    $insert_fields = array_merge($this->defaultFields, $this->insertFields);

    $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';

    $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
    $query .= implode(', ', $values);

    // Updating the unique / primary key is not necessary.
    unset($insert_fields[$this->key]);

    $update = [];
    foreach ($insert_fields as $field) {
      $update[] = "$field = VALUES($field)";
    }

    $query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);

    return $query;
  }

}

```

But always you need to set the key, if you don't set the key property you will get an exception:

```
protected function preExecute() {
  // Confirm that the user set the unique/primary key of the table.
  if (!$this->key) {
    throw new NoUniqueFieldException('There is no unique field specified.');
  }
...

```

***Read more about this at:*** Why we need the key property in the Upsert class if it is never used?
> 4 votes

# Answer
Upsert - This class can only be used with a table with a single unique index. To be able to use several keys, you need to use Merge. Like this :

```
$query = \Drupal::database()->merge('question');
$query->keys([
  'quizid' => $this->quizid,
  'question' => $number,
])
->fields([
  'quizid' => $this->quizid,
  'question' => $number,
  'nid' => $nid,
  'time_asked' => $log_time,
  'correct' => $correct,
])
->execute();

```
> 5 votes

---
Tags: 8, database
---


title: How do I rebuild table data on submit?

text:
# Question
Title: How do I rebuild table data on submit?
I am using Drupal 7, I am using form API to generate a table with select option filters. The data from the table is from an external API.

The table loads as it should, the drop down selection loads as should. When I select an option from the drop down section I am trying to pass the selected value into the URL of the external API and rebuild the table using the new URL but the table does not get rebuilt, instead the page just refreshes, the selected option is updated in the drop down selection. I have tested and think that the URL variable is updated to include the select option but the table does not get rebuilt.

This is the module

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

$form['type_options'] = array(
  '#type' => 'value',
  '#value' => $options
);

$form['Title'] = array(
  '#title' => $title,
  '#type' => 'select',
  '#options' => $form['type_options']['#value'],
  '#default_value' => isset($form_state['storage']['Title']) ? $form_state['storage']['Title'] : '',
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t(“Filter”),
);

//Get fromtable data from API
if (!empty($form_state['storage']['Title'])) {
 $filter = preg_replace('/\s+/', '+', $form_state['storage']['Title']);
  $url  = $api.'&filter='.$filter;
} else {
  $url = $api;
}
$json = file_get_contents($url);
$data = json_decode($json,true);
$rows = $data[data];

//Set paging items for formtable
$per_page = 30;
$current_page = pager_default_initialize(count($rows),$per_page);
$chunks = array_chunk($rows, $per_page, TRUE);
$form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $chunks[$current_page],
  '#empty' => $empty,
  '#pager' => array('quantity' => 12)
);

$form['pager'] = array(
  '#theme' => 'pager',
);

return $form;
}

function mymodule_form_submit($form, &$form_state) {
  $form_state['storage']['Title'] = $form_state['values']['Title'];
  $form_state['rebuild'] = TRUE;
}

```

Thanks for any help

# Answer
Your code should work fine from what I see. You can print the $url value to see what really is passed to API. Please note that $form\_state\['storage'\]\['Title'\] will contain the key, not value - maybe that's the problem?

Plus, you don't need to use storage in this case. When using $form\_state\['rebuild'\] you can just use $form\_state to pass variables, like this:

```
function mymodule_form($form, &$form_state) {
  $storage_val = isset($form_state['values']['title']) ? $form_state['values']['title'] : 'nothing stored yet';

  $form['message'] = array(
    '#markup' => t('Stored value: %storage_val', array('%storage_val' => $storage_val)),
  );

  $options = array(
    'opt1' => 'option1',
    'opt2' => 'option2',
    'opt3' => 'another option',
  );

  $form['title'] = array(
    '#title' => 'Select option',
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => isset($form_state['values']['title']) ? $form_state['values']['title'] : '',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Filter'),
  );

  return $form;
}

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

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to render media shortcodes e.g [[fid:1234]]
I've written a custom database query to pull out taxonomy data in a specific way, the problem is embedded media shortcodes are outputting the shortcode strings as they stand in the database, rather than the content they represent.

e.g: `[["fid:"1234"]]` instead of `<a href="/link-to-pdf/file.pdf">pdf</a>`.

**The taxonomy body field can contain:**

* Embedded nodes (`[[nid:1]]`)
* links to other content (`node/nid`)
* **embedded media etc: pdfs** (`[["fid":"6247" "other_props":....]]`)

I've written regex to parse out the first 2 bullet points, and call `_node_embed_replacements()` & `drupal_get_path_alias()` respectively to insert the correct content for them, but i'm having a hard time working out where media module renders embedded shortcodes such as `[["fid":"6247"]]`.

# Answer
> 0 votes
I found the following `load_file()` and `field_view_file()` functions which worked a treat for me. I bundled them with a regex search and replace.

Rough abstract taken from my code not tested but the theory remains the same.

```
preg_match_all('/\[\[{"fid": ?"([0-9]+)".*?\]\]/', $tax_body, $matches);
foreach ($matches[1] as $index = > $fid) {
  $file = file_load($fid); //load the file
  $content = file_view_file($file); // turn it into a render arrray
  $replacement= drupal_render($content); // render it into html string
  str_replace($matches[0][$index], $replacement, $tax_body);
}

```

Perform a regex for `[[{"fid":(???) ..]` where the ??? is the file id that is captured in the `$matches[1]`.

Loop through all found instances, lookup the file markup, and then do a search and replace on the entire string replacing the full shortcodes (matches\[0\]) with the replacement markup.

---
Tags: 7, taxonomy-terms, database, media
---


# Question
Title: Access denied for user anonymous while accessing custom table data
I am trying to fetch custom table result anonymously with services but I am getting

```
<?xml version="1.0" encoding="utf-8"?>

```

Access denied for user anonymous

My Code are as follow :

```
    function custom_data_services_resources() {
  return array(
    'getdata' => array(
      'retrieve' => array(
        'help' => 'Retrieves a data',
        'file' => array('file' => 'inc', 'module' => 'custom_data'),
        'callback' => '_get_data',
        'access callback' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the note to get',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'index' => array(
        'help' => 'Retrieves a listing of notes',
        'file' => array('file' => 'inc', 'module' => 'custom_data'),
        'callback' => '_get_data',
        'access callback' => TRUE,
        'args' => array(
          array(
            'name' => 'page',
            'type' => 'int',
            'description' => '',
            'source' => array(
              'param' => 'page',
            ),
            'optional' => TRUE,
            'default value' => 0,
          ),
          array(
            'name' => 'parameters',
            'type' => 'array',
            'description' => '',
            'source' => 'param',
            'optional' => TRUE,
            'default value' => array(),
          ),
        ),
      ),
    ),
  );
}

```

I tried with "X-CSRF-Token" also But no luck :(

Any help appreciated

# Answer
> 2 votes
Following up with an answer from our comments...

Here's an example custom service resource:

**custom\_data.module**

```
function custom_data_services_resources() {
  $resources = array(
    'custom_data_resources' => array(
      'actions' => array(
        'getdata' => array(
          'help' => t('Gets custom data.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'callback' => 'custom_data_getdata',
          'args' => array(
            array(
              'name' => 'data',
              'type' => 'array',
              'description' => 'The data dude.',
              'source' => 'data',
              'optional' => FALSE,
            )
          ),
          'access callback' => 'custom_data_access',
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'access arguments' => array('access user profiles'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );
  return $resources;
}

```

**custom\_data.resource.inc**

```
function custom_data_getdata($data) {
  return array('foo' => $data['bar']);
}

function custom_data_access($permission) {
  return user_access($permission);
}

```

After that, just enable the custom resource under your endpoint's configuration and clear all of Drupal's caches. Then you can make a **POST** to:

`?q=[my-endpoint]/custom_data_resources/getdata.json`

If you need to send along custom arguments, I usually recommend a single `array` parameter, that way you can easily expand upon it and send as many variables/properties you need along with the payload:

`{ "bar": 123 }`

Which will then return to you:

`{ "foo": 123 }`

Don't forget to attach a header to your request with a name of `X-CSRF-Token` and value retrieved from: `?q=services/session/token`

---
Tags: 7, services
---


# Question
Title: How to make a required / not required one field depending on value of second field (Drupal in registration form)
Below is an example of code that makes the first field not required in the form

```
<?php
    function мой_модуль_form_alter(&$form, &$form_state, $form_id){
    $form['field_website']['und'][0]['#required'] = FALSE;
    }
?>

```

---

```
$form['test']['und'][0]['value']=test;

```

But I need to check the content in the second field after sending the form, and if it coincides with the value of "test", then the first field became not required.

```
if($form['test']['und'][0]['value']=='test'){
    $form['field_website']['und'][0]['#required'] = FALSE;
}

```

# Answer
> 1 votes
Use Conditional Fields module.

---
Tags: forms
---


title: Get web image url from real path

text:
# Question
Title: Get web image url from real path
As part of some other functionality I am generating an image in temp folder and But unforunately I'm not able get the web url of image.

```
$path = \Drupal::service('file_system')->realpath(file_default_scheme() . "://");
$image_path = $path . rand() . '.png';
echo $image_path;

```

I am getting following as path

```
C:\wamp\www\www_d8test1_com\sites\default\files30605.png

```

How can I add slash before image name and get actual weburl of image like below?

```
http://www.d8test1.com/sites/default/files/30605.png

```

# Answer
> 0 votes
You can check out the `file_create_url()` function that creates a URL for your file.

So, based on the code in your question, it would look like:

```
// Generate or get the image uri.
$image_uri = file_default_scheme() . "://";
// Create the url from the uri.
$image_path = file_create_url($image_uri);

```

# Answer
> 0 votes
Try the following explained here:

```
$handle = fopen('<path to local file>', 'r');
$file = file_save_data($handle, file_default_scheme() . '<filename>');
fclose($handle);

```

and then try:

```
file_create_url(file_default_scheme() . '<filename>');

```

---
Tags: uri
---


# Question
Title: Is it possible to pass dynamic values in tokens in Drupal 7?
When using tokens, I would like to be able to use a format similar to the following notation so I can provide the needed flexibility in how a content author can invoke these modals with minimal code experience.

`[modal:view:<term_id>:<text_string>]`

An example of this token in use would be:

`For more information, [modal:view:33:"click here"].`

What should happen from here is that I can grab the `<term_id>` and `<text_string>` and incorporate them in the output of the token replacement.

An example for the expected output would be something along the lines of:

`For more information, <a href="#" data-modal-id="33">click here</a>.`

Is this possible, and if so, how would I construct the `hook_tokens` function to handle these dynamic values?

# Answer
Might have worked myself into the solution via trial-and-error.

```
function hook_tokens( $type, $tokens, array $data = array(), array $options = array() ) {

    // Returnable markup...
    $replacements = array();

    // Handle Tokens...
    if( $type == 'modal' ) :
        foreach( $tokens as $name => $original ) :

            $name_parts = explode( ':', $name );
            switch( $name_parts[ 0 ] ) {

                case 'view':

                    // Handle modal:view tokens...
                    if( !empty( $name_parts[ 1 ] ) && !empty( $name_parts[ 2 ] ) ) :
                        $value =
                        '<a href="#" data-modal-id="'.$name_parts[ 1 ].'">'.
                            '<span>'.trim( trim( $name_parts[ 2 ], '"' ), "'" ).'</span>'.
                        '</a>';
                        $replacements[ $original ] = $value;
                    endif;

                    break;

            }

        endforeach;
    endif;

    return $replacements;

}

```

There's a lot of fail-safes missing from this code, but I just want to make sure this falls under best practice and that I'm not doing anything that would be considered taboo by community standards.
> 1 votes

---
Tags: 7, tokens
---


# Question
Title: Sort by weight using \Drupal::entityQuery()
I want to get all taxonomy term in `$lang` language, following snippet works correctly and return all terms of `$lang` code.

```
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

```

Then I want get results in order that in the taxonomy list they are, try to sort them with `$query->sort('weight','ASC');` but with following snippet the results are the same before adding sort.

```
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $query->sort('weight','ASC');
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

```

Does anybody know where the problem is? How can I get terms in order they are in taxonomy list?

# Answer
> 5 votes
Taxonomy overview list uses something like:

```
  ->sort('weight', 'ASC')
  ->sort('name', 'ASC')

```

If that doesn't work for you, take a look at `\Drupal\taxonomy\TermStorage::loadTree`

# Answer
> 3 votes
As was previously suggested, taking a look at `\Drupal\taxonomy\TermStorage::loadTree` is helpful. Entity Query only provides access to properties of the entity and its Field API values. Since the weight of the term is available in the `taxonomy_term_field_data` table, it will be available to entityQuery as well. However, any nesting of terms, aka hierarchy, will require access to the `taxonomy_term_hierarchy` table. That would require a database query.

You can access it via a database query, as seen in `loadTree`, line 204:

```
    $query = \Drupal::database()->select('taxonomy_term_field_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $result = $query
      ->addTag('taxonomy_term_access')
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->condition('t.default_langcode', 1)
      ->orderBy('t.weight')
      ->orderBy('t.name')
      ->execute();

```

I have updated the query to use Drupal's container, rather than the dependency injection so it can be used more readily. You should be able to modify this to fit your needs if Entity Query is not working as you desire it to.

---
Tags: 8, database
---