# Question
Title: What is the simplest, most drupalish, way to restrict access to some content to authenticated users or a certain role?
I am creating a publications database that is used by staff to input their publications. Some of these publications are available to the public, and some are not. Additionally, the publications have files associated with them, some being public and some not. I have a number of content types for different types of publications with a boolean public field, and two seperate file fields, one for public and one for internal files. I currently have one user role (Staff member) though the number of roles is likely to increase slightly to allow for administrators and a content approval workflow.

* Content Type a
    + Public?
    + Public Files
    + Internal Files
* Content Type b
    + Public?
    + Public Files
    + Internal Files

The idea is that all the publications lists should show a list of public documents to non-authenticated users, and a list of all documents to authenticated users of the right role.

My initial thought is to create two different views for each page with different access settings on each. The first being a page that doesn't check the public field and includes the non-public files field, and a second, available to anyone, that filters to publications where the public field is set to true, and does not include the internal files field, and a few other fields only of interest to staff.

* node list view
    + view a
        - access: staff only
        - filter: Published nodes
* node list view
    + view b
        - access: no restriction
        - filter: Published nodes AND public is true
* node view
    + view a
        - access: staff only
        - filter: Published Nodes
        - fields: All Fields, including internal files
    + view b
        - access: no restriction
        - filter: Published Node AND marked public
        - fields: don't display internal files, some other fields

Is this the simplest, most drupalish approach? Would it make more sense to control the fields used through the view or via view mode (Full Content, Teaser, etc.) I'm still somewhat new to working with Drupal, and find that I'm fighting it at every turn, that makes me think, I must be thinking the wrong way for working with a drupal site.

**Further Information:** I'm actually reimplementing this from an existing system, and am using the Migrate module to bring in thousands of entries, so I have to be able to specify as part of the migration in some way, what the permissions should be.

# Answer
> 3 votes
## Content Access

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Video Tutorial

# **Field Permissions**

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

---

Your views approach is fine, assuming everything you need is in the view.

But if you want to restrict access to nodes, then you're better off using Content Access.

For example: If your view was listing links that you don't anonymous to access (eg: premium content) you would want to use the Content Access module because if anonymous users somehow get a hold of the direct link then they could see the premium nodes.

# Answer
> 0 votes
Apart from the previous (valid!) answer, I think there is another *alternative* to address at least this part of your question:

> The idea is that all the publications lists should show a list of public documents to non-authenticated users, and a list of all documents to authenticated users of the right role.

The way I'd try to implement this, is to use the Group module for al documents targeted to authenticated users. For "public" documents you don't have to do anything I think. As per the "***right role***", that's a matter of creating the appropriate "groups" (like 1 for each role maybe?), and/or maybe even sub-groups that this module supports.

This module is like Organic groups "little brother", only started in D7 and with a D8 version at the horizon. Personally I'm more and more considering it as a potential alternative for the Content Access module also. And since it is all Entity based, there are lots of ways it can be used in combination with the Rules module also.

For way more details about this module, refer to my answer to "How to only allow a user to edit his/her own users?".

---
Tags: 7, users, nodes
---


# Question
Title: Node language in views contextual filters
I have a multi-lingual site. On the article page has a block with other articles. How to bring in the article section with the same language as the current node? Interested in is the use of contextual filters. Option of using the language of the current user filter is not suitable.

# Answer
Why isn't the current users language suitable, that's what you want

Have you looked in the filters section of views (Bottom left of the views editing screen) rather than contextual filters? There should be the current users language as a filtering option in there.
> 0 votes

---
Tags: views, i18n-l10n
---


# Question
Title: Corresponding Type and Size of Data Types in Drupal in order to create a table field in PostgreSQL
I was trying to create dynamically a table in Postgres using `db_create_table` function.

```
$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => array(
                     'bigint_column' => array('type' => 'int', 'size' => 'big' )
                ),
);

db_create_table('myid_template_1', $schema);

```

The code above works fine. It creates a table `myid_template_1` in my database with a column field `bigint_column` with a type of `bigint`.

I also wanted to create fields with the following type:

```
bit
boolean
character varying
date
double precision
time with timezone
time without timezone
timestamp with timezone
timestamp without timezone

```

What is its corresponding type and size in Drupal? It is somewhat missing in the documentation I read.

UPDATE 1:

Basing from Sir Mario Steinitz answer, I updated my code above.

```
$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => array(
                    'bigint_column' => array(
                                           'type' => 'datetime',
                                           'size' => 'normal',
                                           'pgsql_type' => 'time with timezone'
                     )
                ),
    );

```

It was not working still. Am I missing something?

# Answer
> 2 votes
The linked documentation is not missing any field types supported by Drupal. For maximum compatibility to all supported database types, the field types of Drupal's database API is limited to the field types you find within the documentation.

This assures that most modules using the default database API will run the same with PostgreSQL as they do with MySQL and almost SQlite.

However, if you need these field types in order to work on database stored information that will be used by other applications, or have another module specific requirement for using them, you can use the 'pgsql\_type' attribute within your schema definition.

This attribute overrides the generic 'type' and 'size' attributes.

Within your module, you may need to query / handle the information of these fields on your own, as the Drupal database driver might not always be able to map / fetch them properly to / from your PHP objects / arrays.

---
Tags: 7, forms, database
---


title: Group by taxonomy headers

text:
# Question
Title: Group by taxonomy headers
Not sure why I can't do this as it sounds simple, I have:

A content type called 'RSS FEEDS'

A vocabulary called 'Publications' within this I have 3 terms which are 1) NY Times 2) BBC 3) National Geographic

I now have a bunch of nodes that are tagged with these 3 terms.

What I want to do is have an accordion with 3 headers:

NY Times, BBC, National Geographic

So when I click a header I see all the nodes of that particular type underneath. I have tried an number of things including aggregation, taxonomy views etc but cannot seem to work this out. For clarity I have mocked up how I want this to look.

Any help greatly appreciated.

# Answer
I had the same problem. You're almost done, but missed some settings ;). You just need to do some Format settings for Views Accordion in your View.

Here are the steps to make your grouping field as the "header" or "trigger" of the accordion action.

1. Go to Format: Views Accordion Settings and select Grouping field.
2. Check "**Use the group header as the Accordion header**"

Save View. That's it. Now your Grouping field will act as Views Accordion Header and avoids duplicate headers too.

Hope this helps.
> 1 votes

---
Tags: views, navigation
---


# Question
Title: How to reorganize drupal sites/all/modules structure without symbolic links?
**Context:**

As the number of modules used increases, I try to reorganize modules in /\***/sites/all into

* sites/all/modules/contrib
* sites/all/modules/custom
* sites/all/modules/dev

subfolders as it is described here (1) and now I use a solution similar to what was answered here (2)

**Question:** Is possible to use path variable or another solution instead of creating symlinks for each contrib module?

I don't want to create so many symbolic links for each of contrib modules separately.

How to explain to Drupal the sites/all/modules structure the way I don't get bootstrap.inc errors such as:

```
Error: require_once(): Failed opening required
'/***/sites/all/modules/entity/includes/entity.inc'
(include_path='.:/usr/local/php5/lib/php') in
/***/includes/bootstrap.inc, line 2935

```

# Answer
> 3 votes
You just move your modules into relevant subdirectories inside `sites/all/modules`, clear caches and everything should work fine as before, Drupal will find them there without any problems. You don't have to create any symbolic links to make it work.

# Answer
> 6 votes
The Registry Rebuild module really is the answer. I struggled to solve this problem for hours, then this module fixed it completely, and with elegance!

# Answer
> 0 votes
After reorganizing module to contrib, custom, features, patched, you need to rebuild Drupal registry. As @kiamlaluno said for this you need Registry Rebuild module/drush script. For me, with multiple websites, **it also required reloading/restarting Apache** to get rid of errors.

---
Tags: 7, files
---


title: Views accordion grouping on taxonomy

text:
# Question
Title: Views accordion grouping on taxonomy
I have a content type: products. This content type use its own taxonomy (type1, Type2, Type3).

My content has 2 fields: Title and baseline (and more, but I don't want to use them on this view).

What I want:

Display a page with my products listed by taxonomy

```
Type1
   [title Product 1] [baseline product 1]
   [title Product 2] [baseline product 2]
   [title Product 3] [baseline product 3]
Type2
   [title Product 4] [baseline product 4]
   [title Product 5] [baseline product 5]
Type3
   [title Product 6] [baseline product 6]

```

I can do this easily, But I want more: I want to use views accordion module to display that. And I want the types being the header tabs.

The problem is: whatever I try, I get the same problem:

the module makes each node a tab

```
Type1
<title Product 1 tab >
   [title Product 1] [baseline product 1]
<title Product 2 tab >
<title Product 3 tab >
Type2
<title Product 4 tab >
<title Product 5 tab >
Type3
<title Product 6 tab >

```

In screenshot: (Don't pay attention of the text, it's some creepy test content):

My objective:

# Answer
> 2 votes
From your question, I'm assuming that you've already created view and set everything.

You just need to do some Format settings for Views Accordion in your View.

Here are the steps to make your grouping field as the "header" or "trigger" of the accordion action.

1. Go to Format: Views Accordion Settings and select Grouping field.
2. Check "**Use the group header as the Accordion header**"

I've tested it myself. It works as you expected.

# Answer
> 1 votes
1. use field display
2. check "Exclude from display" for all fields
3. add "global custom text"
4. now using the replacement pattern you can set markup for all those field in text area.

> note: global custom text should be placed below the fields you are using as replacement pattern otherwise you will not be able to find replacement pattern for that field

# Answer
> 1 votes
Suppose you use the taxonomy for filtering this. Then follow the instructions given below:

1. The field of taxonomy be the first.
2. Later field be the title and later description.
3. Go to settings of views accordion.
4. Grouping field number 1 the first field of view, or taxonomy field, and use rendered output to group rows.
5. In the last option of settings called, disable if only one result select this option, and you see that working.

---
Tags: taxonomy-terms, views, navigation
---


title: Alter product variation view

text:
# Question
Title: Alter product variation view
I want to alter product variation view and want to display a new form which value depends on variation price. I can add the field to the node using hook\_node\_view\_alter() but i want to add it to the product variation right after the price field. I just need to display an integer dependent of the price.

Any help with this?

Thank you

# Answer
> 0 votes
You can try hook\_entity\_view\_alter() API function provided by Drupal Core to alter any entity.

If you want to alter how the entity will look, you can also try using Display Suite or Panels module which are used to override the display.

---
Tags: commerce
---


# Question
Title: How do I map active directory group membership (ldap authorization) to og groups in open atrium?
I can successfully bind to the ldap server, and I have set up authentication successfully - ldap users can log in to my open atrium site. However, the authorization mappings for the groups aren't coming through.

I have this as a mapping under: admin/config/people/ldap/authorization/edit/og\_group

```
CN=Human Resources,OU=Groups,OU=Domain Users,OU=Domain Controllers,DC=domainname,DC=com|node:100:6

```

Where "100" is the node id for the open atrium space (og group), and "6" is a custom group admin role with a set of permissions defined in: admin/config/group/roles/node/oa\_space

However, when I log in with a user that is confirmed to have this "memberof" attribute in active directory, the user does not have the corresponding access to the organic group.

I have tried both "Convert full dn to value of first attribute before mapping" checked and unchecked with the same results.

The mapping is shown to be enabled here: admin/config/people/ldap/authorization

I'm finding the documentation a little lax here. Am I mapping the correct og role id? Does the og role id translate to the role id in admin/config/group/roles/node/oa\_space? Is this set somewhere else? Where? Is there anything else I have to do to bring these mappings over?

# Answer
I had this same problem recently whereby this was originally working:

```
GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

```

During this course of development this stopped working and on alternate logins a user in that LDAP group would either be a member of the organic group, or not (but never an administrator of that group).

I eventually worked out that it had stopped working because I had since overridden the permissions of the space, which meant that the OG role ids were different, even though they had the same name.

Therefore:

```
GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

```

was being automatically converted to

```
GroupA|IT:member (raw: node:3:5)
GroupA_Admins|IT:member (raw: node:3:5)
GroupA_Admins|IT:administrator member (raw: node:3:6)

```

when actually since it was no longer using the default roles, it should have been using 8 and 9 instead of 6 and 7.

Rewriting the mapping to explicitly use the ids for the overriding roles rather than their names worked:

```
GroupA|node:3:8
GroupA_Admins|node:3:8
GroupA_Admins|node:3:9

```

I know this is a very old post to reply to, but I was struggling with this yesterday so hope it helps someone else in future.
> 1 votes

---
Tags: users, organic-groups, distributions, authentication-authorization
---


# Question
Title: Building a full featured gallery with voting system
I'm looking for a way to build a simple gallery node type in Drupal, with vote (*with Votingapi and Fivestar*)per image enabled. (*1 vote per image, per node, per user, and users are able to vote on any image in the node*). As simple as it looks, I'm unable to build a simple proof of concept of what I'm trying to achieve.

Here's a mockup of how I see the thing, and here's how I see the thing in Drupal. A content type 'Gallery' these following fields:

* Title
* Body
* Field Collection (multiple):
    + Image (single)
    + Fivestar rating

I succeeded to do it and now, to compute the results, I would like to get the results per node. However, if you look into the votingapi\_vote table, the only data for a vote are:

```
MariaDB [voting]> SELECT * FROM votingapi_vote;
+---------+-----------------------+-----------+-------+------------+------+-----+------------+-------------+
| vote_id | entity_type           | entity_id | value | value_type | tag  | uid | timestamp  | vote_source |
+---------+-----------------------+-----------+-------+------------+------+-----+------------+-------------+
|      10 | field_collection_item |         2 |    80 | percent    | vote |   1 | 1455270089 | 127.0.0.1   |
|      13 | field_collection_item |         3 |    60 | percent    | vote |   1 | 1455271926 | 127.0.0.1   |
|      15 | field_collection_item |         1 |    80 | percent    | vote |   1 | 1455272041 | 127.0.0.1   |
+---------+-----------------------+-----------+-------+------------+------+-----+------------+-------------+

```

It is impossible to retrieve data from the parent node because it simple doesn't exists in the DB.

It looks like we could change tags dynamically, so I hooked into fivestar to generate dynamic tags, but it gets blocked in \_fivestar\_cast\_vote(), especially in fivestar\_validate\_target(), and I'm unable to generate tags dynamically.

I also tried to hook into Votingapi using hook\_votingapi\_preset\_votes\_alter() but if you're using Fivestar with the AJAX widget, it's impossible to get information on the current node using menu\_get\_object(). So I'm still stuck.

Now I'm trying to look for another solution, if you have ideas, please let me know.

# Answer
> 1 vote per image, per node, per user, and users are able to vote on any image in the node

I don't fully understand the use case here; it might be easier to visualise the scenario with a fuller explanation?

At a guess, the issue might revolve around the use of `field collection` module here? I'm not a wizard at the internals of that, but personally in this situation I usually manage this with a container/item setup:

* Gallery (node/entity)
    + Image (node/entity)
    + Image
* Gallery
    + Image
    + Image

I then relate these either with `entity_reference` or I guess you could use `inline entity form`, depends. I don't know if there is anything that precludes you from doing it this way, but I think you're more likely to have better data from votingapi et al like this? Probably using two content types is going to give more joy than entities for that reason.

This is all from a site builder perspective, where using this kind of setup generally means I have to write as near to zero code as possible!
> 0 votes

---
Tags: 7, entities, rating
---


# Question
Title: DOMPDF not showing images and writing empty tmp files via print module
I recently moved a Drupal 7 website from my development server to my pre-production server, and the rendering of the images from both the Body field and various images fields stopped working.

I now see "Image not found" and the URL of the image (which is working when I click on it by the way) on the generated PDFs.

The URLs from the Body field look like this "/mywebsite/sites/default/files/myimage.jpg" and the URLs of the "Image" fields are complete URLs with "http://mydomainname.com/mywebsite/……".

www-data has access to the images files and can also write in /tmp. And it does, actually, every time I generate a PDF with images. But the files are empty:

```
$> find /tmp -name "*dompdf*" -ctime -1 | xargs ls -lArth
-rw------- 1 www-data www-data 0 janv.  4 15:30 /tmp/ca_dompdf_img_0DlQ4V
-rw------- 1 www-data www-data 0 janv.  4 16:01 /tmp/ca_dompdf_img_Tyvv8w
-rw------- 1 www-data www-data 0 janv.  4 16:27 /tmp/ca_dompdf_img_pa4m4V
-rw------- 1 www-data www-data 0 janv.  4 16:27 /tmp/ca_dompdf_img_5RzNHk
-rw------- 1 www-data www-data 0 janv.  4 16:28 /tmp/ca_dompdf_img_T21gUJ
-rw------- 1 www-data www-data 0 janv.  4 16:29 /tmp/ca_dompdf_img_OmWxt2
-rw------- 1 www-data www-data 0 janv.  4 16:33 /tmp/ca_dompdf_img_SmA57m

```

I tried checking "Access images via local file access" in the "print" configuration page, but with no luck.

This may be an issue related to the server configuration, since it was working before on the development server, but I'm running out of ideas…

# Answer
Apache's access log showed me the HTTP request originating from my server and trying to retrieve the images resulted in 401 errors. This was because of the htaccess authentication I had put up.
> 0 votes

# Answer
It's because your permission is `-rw-------` which only has read and write, there is **no execute**.

Use `chmod -R 0775 sites/default/files`
> 0 votes

---
Tags: 7, files
---


# Question
Title: hook_menu_get_item_alter() needs to give a 404
How can I throw a 404 error from within hook\_menu\_get\_item\_alter()?

If I call drupal\_not\_found() then it keeps calling itself, and I don't know an other way to do this.

# Answer
> 1 votes
I was able to do this in hook\_menu\_get\_item() by getting the status of the node from a simple query, and, when status isn't NODE\_PUBLISHED, I change the router item's load function from node\_load() to is\_null(), which will always return FALSE when a node ID is passed to it. A FALSE from a load function will result in a 404 response from Drupal. This is a bit dirty, but it uses the Drupal API properly, and it seems to work!

```
/**
 * Implements hook_menu_get_item_alter().
 */
function mymodule_menu_get_item_alter(&$router_item, $path, $map) {
  if ($path == $_GET['q']) {
    if (isset($map[0]) && $map[0] == 'node' && isset($map[1]) && is_numeric($map[1])) {
      $status = db_query('SELECT n.status FROM {node} n WHERE n.nid = :nid', array(':nid' => $map[1]))->fetchField();
      if ($status != NODE_PUBLISHED) {
        // Replace node_load() with is_null() as load function, to ensure the
        // output of the load function is FALSE, so we get a 404 response.
        $router_item['load_functions'] = array('is_null');
      }
    }
  }
}

```

# Answer
> 0 votes
You can't directly - data from `hook_menu()` and `hook_menu_alter()` are cached, so the decision can't be made there for individual page requests.

Instead, you need to override the page callback, e.g.

```
function MYMODULE_menu_alter(&$items) {
  $items['foo']['page callback'] = 'MYMODULE_foo';
}

function MYMODULE_foo() {
  drupal_not_found();
}

```

---
Tags: http-request
---


# Question
Title: How can I output aliases in a print function, so I can render links using aliases instead of nid?
I have a theme using a views tpl file that is making it impossible for a View to link to node content using the node’s aliases' that i’ve set up. For example it is linking to the default node/36 instead of projects/projectname.

the view contains a grid of ‘thumbnail like content’ wherein each image links to it’s corresponding node. the views template file is renderering links as shown below:

```
<a style=" background-image: url('<?php print $thumbnail;?>'); "
class="w-inline-block portfolio-photo portfolio-1"
href="<?php print drupal_get_path_alias('node/').$row->nid;?>">

```

It’s hardcoding /node/ as a directory and use the function $row-\>nid

Is there an alias equivalent to nid? Instead of node/36 it the url should be project/projectname

To rewrite the above code using pseudo code it would be…

```
<a style=" background-image: url('<?php print $thumbnail;?>');"
class="w-inline-block portfolio-photo portfolio-1"
href="<?php print drupal_get_path_alias(‘projects/‘).$row->alias;?>”>

```

# Answer
You should use the l() function:

> Formats an internal or external URL link as an HTML anchor tag.
>
> This function correctly handles aliased paths and adds an 'active' class attribute to links that point to the current page (for theming), so all internal links output by modules should be generated by this function if possible.

So:

```
<?php print l('Link text',
              'node/' . $row->nid,
               array(
                 'attributes' => array(
                   'class' => array(
                     'w-inline-block',
                     'portfolio-photo',
                     'portfolio-1')))); ?>

```

You have to supply classes and any other attributes to the l() function.

Note that the first l() parameter (the 'Link text') can be HTML. For this you have to pass in the options array an element HTML set to TRUE. The above example can be:

```
<?php print l('<img src="/someimg">Some text</img>',
              'node/' . $row->nid,
               array(
                 'attributes' => array(
                   'class' => array(
                     'w-inline-block',
                     'portfolio-photo',
                     'portfolio-1')
                   )
                 'html' => TRUE,
                 )
             ); ?>

```

Also, as noted by the documentation fragmento above, the l() functions handles the aliases. This is because internally drupal\_get\_path\_alias() function is used.
> 2 votes

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


title: Wildcards for matching path

text:
# Question
Title: Wildcards for matching path
I am using the Parsely module and I want Parsely to ignore certain paths. I achieve this by setting the paths to be ignored field in parsely's settings page. I am able to use the * wildcard, and I need to know if there are other wildcards I can use to match paths. Where I can find a list with wildcards used to match paths?

I ended up looking at the function drupal\_match\_path which is described here: https://api.drupal.org/api/drupal/includes!path.inc/function/drupal\_match\_path/7 ; it seems that it only replaces newlines, and asterisks. Am I wrong? Are these the only "wildcards" available?

# Answer
Unfortunately, the short answer is: No, you cannot use other wildcards.

The reason is the use of preg\_quote inside drupal\_match\_path, any regex wildcards you add to your pattern will be escaped.

P.S.: Very cool question, had to take a good look at this.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How to use ungrouped date fields as data for Charts Views?
I have a content type with the following date fields:

1. `Start Date`
2. `Deadline Date`
3. `End Date`

Deadline date is programmatically calculated, where as Start and End are based on user input.

There is a page with a table view for open nodes, ones without an `End Date`. In it, I would like to have a graphical representation of nodes alongside a graphical representation of time left from now until `End Date`.

I made a chart block view with serials as labels and dates as data, but the only result I got was a flat line with 0. Then tried every format combination listed under the date field without any luck. Although that, post date as a field seems to return correct results(?).

For a specific node Devel listed the following:

```
created (String, 10 characters ) 1451882207

field_end_date (Array, 1 element)
    und (Array, 1 element)
    $...->field_end_date['und']
        0 (Array, 4 elements)
            value (String, 19 characters ) 2016-10-27 00:00:00
            timezone (String, 11 characters ) Asia/Riyadh
            timezone_db (String, 11 characters ) Asia/Riyadh
            date_type (String, 8 characters ) datetime

```

Creating timestamp fields gave the same flat line. So, I am unsure about what the exact issue is. Help would be appreciated on how to reach the desired outcome or about how to debug this if it is not a feature.

I'm using Charts version 7.x-2.x-dev.

# Answer
> 0 votes
I found a partial workaround for this by using hook\_views\_pre\_render.

```
function hook_views_pre_render(&$view) {
   if($view->name == 'stuff'){
      $results = &$view->result;
      foreach ($results as $key => $result) {
      $now = time();
      $end = strtotime($result->field_field__end_date_[0]['raw']['value']);
      $daysuntil = date("j", $end-$now);
      $result->field_field_end_date[0]['rendered']['#markup'] = $daysuntil;
     }
   }
}

```

The previous function is for a chart that displays node serials as x-axis labels and number of days for yaxis, which is calculated as the difference between now and a end date.

# Answer
> 0 votes
Within the Charts module, there is an interesting "feature request" (not "bug" ...) about Graph node input over time (support date formatting on a continuous axis).

In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.

Have a look at this issue, which I believe is similar to what you're asking here. Maybe also the patch(es) included in this issue.

Disclosure: I'm a co-maintainer of this module.

---
Tags: 7, views, datetime, charts
---


# Question
Title: Using Services, why is the resource name appended to the endpoint?
If I want an operation of GET `api/v1.0/users` and `api/v1.0/pages`:

Using the Services module to create a REST API, if I define a service with an endpoint of `api/v1.0/users` and enable the `user` resource (let's say I enable the Retrieve action), then I have to go to the URI `/api/v1.0/users/user/` to get it to work. If I don't include the `/user` at the end, it returns a 404 error.

However, if I make the endpoint simply `api/v1.0`, and enable the same resources, then the URI is closer to expect and want: `/api/v1.0/user/`, but still not quite right. Also, If I define other endpoints using this style (eg. for `/api/v1.0/node/`), only the last one works; the rest return a 404 error.

Why is it designed this way? And how can I make it not append the resource name to the end?

---

**Update**: Based on @mradcliffe's answer, it seems that it's been designed this way so that you can define a single endpoint as a sort of 'endpoint base', such as `api/v1.0`, then enable multiple resources, which then append their names to the endpoint path.

The problem I see with that is that, if I later create a new version of a resource (eg. the user resource) that does things a little differently, and I thus want to name it with a new version number (eg. users\_1.1) to distinguish it from the old resource, that would create a horrible endpoint path of `api/v1.1/users_1.1`...?

---

**Update**: To answer the question of my previous update, I think a better (more efficient) programming practice would be to simply check the api version within the code (wherever the new code deviates from the old) rather than re-naming the resource. I could define a function that pulls the version out of the path for this checking.

# Answer
> 3 votes
See mradcliffe's comment for a good explanation of the difference between an endpoint and a resource, understanding that will make it clear why the Services module does things the way it does.

Why is the endpoint for the user entity type specifically named `user`?

Conceptually speaking it's a safe bet that the module developer followed common REST patterns, and adopted the name of the entity as defined by the system the code is sitting in (i.e. the `user` entity type defined by Drupal core).

From a technical point of view, the resource is named `user` because the services module explicitly names it as such in `_user_resource_definition()`:

```
$definition = array(
    'user' => array(
      'operations' => array(
        ...

```

Not a fan of this particular convention? Not a problem, Services has you covered.

Go to the "Edit Resources" tab for your endpoint, and look in the right hand column of the table; you'll see a text field that takes an "Alias". Set that to "users" for the User resource.

Set your endpoint to something sensible like 'api/v1.0', and you can now access the `user` resource through its alias at http://example.com/api/v1.0/users. It sounds like you might also want to add a "pages" alias for the "Node" resource, but I'm speculating a bit.

---
Tags: uri, services, 8
---


title: How to re-use text values in a webform?

text:
# Question
Title: How to re-use text values in a webform?
I am using webform and with all the tons of modules available so far there was virtually nothing I had to compromise on.

One thing I am stuck with is re-using user text input. Is this possible without writing a custom webform module on a multi-page form:

1. user initially enters some text in 4 textfields
2. populate form checkboxes with those values?

There is the token module installed but I can't figure out a way to populate the checkboxes dynamically (coming from the user and not from a premade select list). The webform\_ajax module tells me I can't use it on multi-page forms.

Any suggestions how to achieve something like this where the user enters something and this shows up later in the form?

**UPDATE:**

I am trying to use hook\_webform\_select\_options\_info. How can I target the specific webform, text and select field? Devel does not show any webform ID. The screenshot shows textfield and selectlist information

From the link

```
function hook_webform_select_options_info() {
  $items = array();
  $items['customusergroups'] = array(
 'title' => t('Your user groups'),
 'options callback' => 'webform_options_days',
 // 'file' => 'includes/webform.options.inc',
 );
 return $items;
}

```

# Answer
There is a hook in webform called hook\_webform\_select\_options\_info, that allows you to build a dynamic list of $items\[\] (return $items), which will be used as the list of options for your component. What you put into this list can obviously be anything - i.e. how you decide what to put in is up to you.

I used it recently to create a multi-route dynamic web form where the path through the webforms is determined by a decision tree. Ever option on every question is loaded from a JSON file, and depending on the answer, the next question (which could be any one) is shown.
> 0 votes

---
Tags: 7, users, webforms
---


# Question
Title: How to build a simple content approval workflow between an administrator and a user?
I have the following requirement on a Drupal site.

**User interface** (Authenticated user):

1. A simple form with some text fields
2. Radio buttons to select the content type
3. A submit button to submit the form

An authenticated user has to submit a form which will have few text fields and a content type selection.

**User interface** (Administrator):

1. A grid to see all the submissions.
2. A column with two buttons beside every submission "Review" and "Send back".

Once submitted the form, admin will be able to the submission, they may either review the content or send back the content to the user.

When clicked on review button, the page has to take to "Add content" page with title, description, attachment and other fields pre-filled.

When sent back, user will be notified and they may review the content and resubmit the form.

I achieved this requirement using Webform module which captures the user submission and written a custom module to fetch the webform submission content and creates a node based on the submission. I have yet to work on the "sent back to the user" part.

I'm wondering, if there is any simple way of doing this workflow.

P.S: I have already tried Workbench but I'm looking for a simple workflow where a non-technical guy (administrator) could easily get it.

# Answer
> 3 votes
Have a look at my answer to "How to implement a multi step approval with webforms/entityforms based on form components?". It explains how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

Use such approach, it does not require modules like "Webform" or "Workbench".

# Answer
> 2 votes
Another workbench alternative is....

CPS, some details about it (from its project page):

> CPS, or the Content Publishing System, is a radical way of handling revisions for entities. It takes total control over revision management for all supported entities. For CPS-enabled entities, the revision tab is completely replaced and users are not allowed to manually create or move around revisions.

If CPS still very complex for you, you might look into build your custom workflow using Rules.

---
Tags: webforms, workbench
---


title: Hook user login never gets called?

text:
# Question
Title: Hook user login never gets called?
We have an existing application with users and we would like to get our user base to accept the terms and conditions. In this regard I did some research and see that legal module comes the closest to desired functionality however there is one concern:

By default the legal module only shows up on login when a user has accepted terms and conditions on registration and only if the terms have changed. What we want to do is to get every user to see that upon login until they accept them.

I looked at the module code and see there is a hook\_login function. No matter what I do, this function does not get called. I have tried to backtrace the login system and find out that certain modules do get their hook user login called but some do not. Legal module would be one of them. Any thoughts on how to trouble shoot this further?

The hook is as follows:

```
function legal_user_login(&$edit, $account) {
  echo "Legal module hook login called"; <--- never see this
  exit; <-- does not get called

  global $user;
  global $language;

  if ($user->uid == 1) {
    return;
  }

  // Get last accepted version for this account
  $legal_account = legal_get_accept($user->uid);

  // If no version has been accepted yet, get version with current language revision.
  if (empty($legal_account['version'])) {
    $conditions = legal_get_conditions($language->language);
    // No conditions set yet.
    if (empty($conditions['conditions'])) {
      return;
    }
  }
  // Get version / revision of last accepted language.
  else {
    $conditions = legal_get_conditions($legal_account['language']);
    // No conditions set yet.
    if (empty($conditions['conditions'])) {
      return;
    }

    // Check latest version of T&C has been accepted.
    $accepted = legal_version_check($user->uid, $conditions['version'], $conditions['revision'], $legal_account);

    if ($accepted) {
      return;
    }
  }

  $uid = $user->uid;

  // Log the user out and regenerate the Drupal session.
  module_invoke_all('user_logout', $user);
  drupal_session_regenerate();

  // We have to use $GLOBALS to unset a global variable.
  $user = drupal_anonymous_user();

  $query = NULL;

  // Deal with destination from password reset one time login link,
  // by creating a new one time login link and setting it as the destination
  // after the T&Cs have been accepted.
  if (arg(0) == 'user' && arg(1) == 'reset') {
    $token = drupal_hash_base64(drupal_random_bytes(55));
    // This is a new, anonymous-user session.
    $_SESSION['pass_reset_' . $uid] = $token;
    $query = array('destination' => "user/$uid/edit?pass-reset-token=$token");
  }

  if (!empty($_REQUEST['destination'])) {
    $query = array('destination' => $_REQUEST['destination']);
  }

  unset($_GET['destination']);

  $result    = db_select('users', 'u')
    ->fields('u')
    ->condition('uid', $uid)
    ->range(0, 1)
    ->execute()
    ->fetchAllAssoc('uid');
  $signatory = array_pop($result);

  drupal_goto('legal_accept/' . $signatory->uid . '/' . md5($signatory->name . $signatory->pass . $signatory->login), array('query' => $query));
}

```

# Answer
> 2 votes
Just add a (boolean) field to the user.

> For new Drupal 7 site you can use:
>
> Admin \> Configuration \> People \> Account settings \> Manage fields Another method is using Profile2 module, a successor of Content Profile Drupal 6 module If you have started with a minimal install profile you will need to enable the Field UI module to access Manage fields via the Account settings.

Then, in a custom module, invoke hook\_user\_load and there, check if it's set. If not redirect to a page where the user needs to accept the terms and this field get updated.

Or, have a look at EU cookie compliance, it does more or less what you want.

---
Tags: nodes, users
---


title: Show Node fields on Drupal Form

text:
# Question
Title: Show Node fields on Drupal Form
I'm working on a form where I have added Company field as entity reference and which is type of auto complete. Is there any way, which can show other attribute of company content type like phone number and email in the form post selecting the company name.

# Answer
> 3 votes
If your question pertains to Drupal 7 then you may want to take a look at the Entity Reference Autofill

> The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.

---
Tags: forms
---


title: Drupal as a RestAPI

text:
# Question
Title: Drupal as a RestAPI
I have been using Drupal for a while to build medium to large CMS systems; love it. From time to time I have to build a RestAPI. Usually I use either Laravel, Lumen or Slim. The only reason why I don't use Drupal is because the bootstrap / overhead is so high in Drupal.

What can be done to make this bootstrap / overhead less. I fully understand that we will never get to the same lean and mean footprint that you get from a dedicated RestAPI framework - but surely we can make the bootstrap faster / smaller / quicker?

# Answer
> 1 votes
In drupal 7 you can use a contrib module called services, this will help you expose json by default for all nodes. You can also output main from hook\_menu.

If you use laravel you may be more comfortable drupal 8, its built on symfony and supports test out of the box

# Answer
> 2 votes
Most of the speed costs to Drupal (beyond php as a language) are from the render layer.

If using Drupal just as a RESTful api, having fewer modules enabled (i.e. Views plugins) will likely cut down on your costs.

Having said that, in non-trivial use cases, I have to imagine the bootstrap is a much smaller performance hit relative to DB queries.

---
Tags: 7, bootstrapping
---


# Question
Title: How to make a page where two content types are combined
It should be a portfolio website. I'm going to place there information about projects I was engaged in and products I designed. The relationships between project and product nodes are those:

```
--Project 1
----Product 1
----Product 2
----Product 3
--Project 2
----Product 4
----Product 5
----Product 6
etc.

```

My question. How to create a page where placed all project articles and under each project article there should be related product article teasers. Like on image.

# Answer
In views you can "Group By" the parent nodes. So if you were using entity references to do the relationship, you would have it as a field in views and group by it.

Are they different content types? How are you relating the children to the parent?

If the default Group By isn't enough, there's a module called Views Field View which can put a view inside a view but that could be a bit unnecessary.
> 0 votes

# Answer
a quick solution could be writing a very simple code. in your .module code in a page call back take all the data that you want and then group them into an array first that is something like this

```
$query = "SELECT
nid,
title,
field_data_first_field_table.first_field_table AS first_filed_table,
field_data_second_filed_table.first_filed_table AS second_filed_table
FROM
node LEFT JOIN first_field_table
ON
field_data_first_field_table.entity_id = node.nid
LEFT JOIN field_data_second_filed_table
ON
field_data_second_filed_table.entity_id = node.nid
 WHERE node.type IN(:type);
 $result = db_query($query, (':type' =>array('type1','type2'));
  while ( $data = $result->fetchObject () ) {
  $portfolio_array[$data -> title][$data ->first_filed_table][second_filed_table] = $data ->nid;
 }

```

in the $portfolio\_array you will have that values grouped .you can push this to a theme function (very best) or return that formatted output in the call back function itself.

second method is views module use rlationships to add the fields and then make your theme changes in the correpsonding views
> -2 votes

---
Tags: views
---


# Question
Title: How to create basic Organic Groups functionality with flags and references?
I've used Organic Groups for the past 6 months and found it to complex for my simple use case. Creating even basic views to show users of a group or content of a group turns quickly into "rocket since".

The module comes with a ton of extra functionality that I didn't need, like access control.

Plus I couldn't migrate my group content and group membership and when I manually inserted into the tables it wouldn't work reliably.

Below is my solution to create basic OG features with flag and reference modules. My requirements were:

2. users can create groups
3. users can join groups (and leave them) without approvals or permissions
4. users can add other nodes to show up as group content
5. use views to display group content and group membership

Please post your comments or alternative solutions.

Btw, Clive encouraged me on meta to post this how-to. Thanks, Clive!

# Answer
> 10 votes
**1. Users can create groups:**

To create groups you just create a new content type "groups" and with permissions for users to create new content. I also added an image field to allow uploading a group logo.

**2. Users can join groups (and leave them) without approvals or permissions**

The Flag module turned out to be an excellent way to allow users to join (and leave) groups. Create a new flag called "groups" and make sure the "global flag" is unchecked and then select your "groups" as "flaggable content". You can also customize the flag links to say "join this group", etc. Btw, just changing the default link text is hard in OG.

**3. Users can add other nodes to show up as group content**

To assign other nodes to the "groups" content type I used node references from the references module. I also looked at (and used before) entity references and DA members seem to prefer entity references.

Node references however has more installs and comes with a nifty "References" feature that allowed me to filter the "available groups" on a node add/edit page to only the groups that have been flagged by the user.

To allow my photo nodes to be assigned to the groups type I add a "group\_content" field to the photo type and select "node reference" as the field type. You can specify the widget type (autocomplete, checkbox, select list), I picked checkbox and 5 as the "number of values". For "content that can be referenced" you simply select your "groups" content type.

With this setting you can create a new photo node and assign it to ANY of the groups that have been created so far. To limit it to a user's groups you create a view for "content of type = group" and then add relationship "Flags: Node flag" with the setting "include only flagged content" checked. Select your "group flag" and select "current user".

Now your view only shows groups flagged by the current user. Click "Add" below "Displays" and select "References", then save.

Now edit your photo content type again and edit the "group\_content" field. At the bottom you there is an option for "The list of nodes that can be referenced can be provided by a view" and you should see your new view as an option. Select that and save.

You can create similar references from other nodes by using "add existing field" in "manage fields" of the content type.

**4. Use views to display group content and group membership**

Now all that is left is creating some views. For example, I want to show a list of users and a list of group content on a group page.

In OG these views are complex, see an example of group content view and users of a group.

With Flags and Node References they are very simple:

List of groups with number of users in each group":

* content type = group
* add relationship "flags: node counter" with "groups" selected and "include flagged content" not selected
* add field "Flags: Flag counter", that shows the number of users
* display in a table and enable default sort by title or number of users. Done

List of members that belong to a group:

* create a view of users
* add relationship "Flags: User's flagged content" with "include only users who have flagged content" checked and "group" as "flagged"
* add contextual filter for "Flags: content id" and provide a default value of "content ID from URL"
* create a block view to show the first 5 users with a more link to show all users on a page. Select that block to show up for your "group" content type

Show list of nodes that are assigned to a group:

* create a view with content type = photo for example
* add contextual filter "Content: Groups (field\_group\_content) - that's the node reference field we created above. Select "content from URL" as the default value and now you'll only see photos assigned to the current group.
* create a block to show the most recent 5 with a "more" link to a page showing all. Then enable the block to show for type "group".

That's it. As an additional benefit I could import my legacy group membership and group content with a couple of basic SQL INSERT statements.

# Answer
> 0 votes
There is a new kid in town these days (starting from D7), which offers a potential alternative to the **Organic groups** module, i.e. the **Group** module (current maintainance of it happens around where Dries started Drupal ...). Here is a quote from its project page:

> This module is designed to be an alternative to Organic groups (OG).

Some more details about it (also from its project page):

> **Organic Groups** allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
>
> **Groups** instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" Organic groups module.

# Additional sub-modules

Extra features can be enabled via these sub-modules:

* **Group Add**: Add members to a group without their consent.
* **Subgroup**: Make group to belong to another group.
* **Group Invite**: Allow group members to invite people into their group.
* **Group Node**: Enables Group functionality for the Node module.
* **Group member profiles**: Create multiple fieldable member profiles, which can be attached to a member.

# Integration with Rules

The Group module also integrate nicely with the Rules module, as explained in comment #2 of issue 2603136, which states the following:

> ... you can already use Rules to:
>
> * Add a new Group
> * Create a new GroupMembership and save it (the equivalent of $group-\>addMember())
> * Add or remove a GroupRole from a GroupType
> * React on new GroupMembership or Group entities
> *
>
> What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.
>
> Useful Rules we may add could be:
>
> * E-mail all members of a Group, optionally filtered by GroupRole
> * Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"
>
> ...

# Integrations with other modules

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

# Example of using the Group module

Refer to How to implement an option for users to limit access to nodes/comments to users with the same role while posting it? for an interesting illustration of how this module can be used.

---
Tags: 7, organic-groups, nodes, flags
---


title: Exporting Taxonomies to code

text:
# Question
Title: Exporting Taxonomies to code
I'm looking for a way to export Taxonomy vocabs and their associated terms. So far I've found and tested:

Taxonomy Export -- Exports to code using features but doesn't import.

http://drupal.org/node/755986 -- My brief testing with this patch showed mixed results.

Does anyone have any other module suggestions or code solutions? I could write it all into a `hook_install` and then use `hook_update` to update but it doesn't seem like an elegant solution especially for 500+ terms.

# Answer
> 5 votes
Also might want to take a look at Taxonomy CSV import/export or Taxonomy import/export via XML

# Answer
> 3 votes
You might also want to look at http://drupal.org/project/uuid and http://drupal.org/project/uuid\_features, which can be used together to export Nodes, Node Revisions, Users and Taxonomy to a Feature.

I haven't done Taxonomy with UUID personally, but it does work quite well with Nodes.

# Answer
> 2 votes
The Feeds module allows the creation of Taxonomy terms from various sources (CSV, XML, etc). That may help.

# Answer
> 0 votes
I have used http://drupal.org/project/exportables with a patch to support exporting the taxonomy and full terms with one tick in features. Have had good success with this

# Answer
> 0 votes
Even though the module is named Taxonomy Export, it is a light-weight module for managing exports and **imports** of vocabularies and terms.

# Answer
> 0 votes
Even though this module is called **Node** Import, it also says it handles importing/exporting Taxonomies.

# Answer
> 0 votes
Firstly you’ll need to install the UUID Features, Features and UUID modules.

Once all those modules are enabled, go to example.com/admin/config/content/uuid\_features (or on your administration menu go to Administration –\> Content Authoring –\> UUID Features Integration, and under “Exportable Taxonomy term bundles” check the boxes for the relevant taxonomy terms.

Go to your features export page at example.com/admin/structure/features/ (or on your administration menu go to Administration –\> Structure –\> Features), create/recreate the feature and you’ll see “Taxonomy Terms” listed.

---
Tags: 6, taxonomy-terms, importing-exporting
---


# Question
Title: How to view to user only the node that referenced to him?
I have a Content Type with a user reference field.

I want that the user can display\access only to the nodes that referenced to him.

Can I do this with Views?

I already tried the modules **Node access user reference** and **Node access node reference** with no success because they have a huge bug. When the module is enabled many View becomes inaccessible ( https://www.drupal.org/node/1311460 ).

# Answer
> 2 votes
Entity Reference and Rules Solution.

1. Install both modules
2. Add an entity reference field with unlimited values to your content type. Make sure it references users.
3. For views, create a content view and add a contextual filter for the field you created. My test contextual filter was called `Content: User Ref Test`. Your contextual filter will have the same name as the field you created.
4. In the contextual filter's settings, click `Provide Default: User ID from logged in User`. This will only show content where the user has been referenced.
5. To make the content safe from typing in the url, create a `Content is Viewed` rule for that content type.
6. In the conditions, choose "list contains item". The list is the entity reference field and the item is the logged in user. At the bottom of the condition, you then negate the rule. It should look like `NOT Item in List "Parameter: List: [node:field-user-ref-test], Item: [site:current-user]`
7. Add a second data comparison condition that allows the admin (or you could do this by user role) to view the content. Negate this condition as well. `NOT Data Comparison > Parameter: Data to compare: [site:current-user:uid], Data value: 1`
8. Add a system redirect to the homepage and a message explaining why the user couldn't view the content.

If it doesn't work, check to make sure the entity reference field is set to unlimited because that's why we use the list in rules.

# Answer
> 1 votes
You can do that using views, following the steps to display only the nodes referencing the current user:

1. Add a **relationship** to your field: **Entity Reference: Referenced Entity** *A bridge to the User entity that is referenced via field\_your\_reference\_field*
2. Add a filter criteria **User: Current** and select as **Relationship** the newly added relationship, which should be automatically selected if you don't have any other relationships in your view. Select the radio button **Yes**.

UPDATE:

As I read your question again, I saw you want to restrict the access, as well. There are many ways to achieve that. You may do that with Rules or using node access grants `hook_node_access_records()` and `hook_node_grants()`. If you need instructions on how to use node access grants, I can improve my answer. Otherwise, the solution with rules is already described by Niall Murphy.

### UPDATE 2: Using node access grants

If you choose to use node access grants, then you don't need to do above filter on views. Since, views already respects the node access grants and filters the nodes readily.

You need to implement two functions in your custom module: `hook_node_access_records()` and `hook_node_grants()`.

```
/**
 * Implements hook_node_access_records().
 */
function YOURMODULE_node_access_records($node) {
  $grants = array();
  if ($node->type == 'YOUR_CONTENT_TYPE') {
    $referenced_uid = $node->field_your_reference_field['und'][0]['target_id'];
    $grants[] = array(
      'realm' => 'YOUR_CONTENT_TYPE_referenced_user', // The naming of the realm is up to you.
      'gid' => $referenced_uid,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
    );
  }

  return $grants;
}

/**
 * Implements hook_node_grants().
 */
function YOURMODULE_node_grants($account, $op) {
  $grants['YOUR_CONTENT_TYPE_referenced_user'] = array($account->uid);

  return $grants;
}

```
Explanation of the above code:

The first function is called on saving the node and puts the node into a realm named `YOUR_CONTENT_TYPE_referenced_user` and gives it a Grant Id as the referenced user's uid.

Second function is called on every page call, so it is important not to do any heavy calculations on this part. This function gives the user the grant Id same as his user Id on the same realm. So that this user can view all nodes in that realm with a Grant Id equals to his user Id.

# Answer
> 0 votes
Just add contextualy filter in it. Select option 'provide default value' and check the option, user id from logged in url. This view will give only the content uploaded by him/her.

---
Tags: views, users, entities, nodes
---


# Question
Title: login destination redirect to previous page adding #
The following code works for me to redirect the user back to the previous current page after he/she logs in.

```
 <?php
    print l(t('Please Log in'),'/user/login', array(
    'attributes' => array('title' => t('Log in page')),
    'query' => drupal_get_destination()));
    ?>

```

However, how can I add `#` to the previous current page?

For example, if the user was on /node/1 and go to the login page. Then How can I redirect this user to /node/1#article\_1 ?

(How can I add this #article\_1? )

# Answer
This can be done via

```
<?php
  print l(t('Please Log in'),'/user/login', array(
    'attributes' => array('title' => t('Log in page')),
    'query' => drupal_get_destination(),
    'fragment' => 'article_1'));
?>

```
> 1 votes

---
Tags: 6, users, redirection
---


title: verify operations through email

text:
# Question
Title: verify operations through email
I need to ensure that the user is the one who is acting on the website by sending hash code generated to his emial or sms message before complete an operation.

we have implemented account balance so we need to prevent others use his balance by verify the account owner.

## Scenario wanted to achieve:

```
User add items to his cart
Send hash code to his email
verify the code
Complete to checkout

```

What is the best practice to achieve?

using commerce framework -- commerce account balance

# Answer
> 1 votes
You should force user registration before checkout and allow Drupal to handle this. There are a couple of things you can do to make it very tough for non-humans to get through:

1. Require user verification for registration. This is out of the box functionality with Drupal and is accessible in the system configuration area.
2. Consider using a module such as Captcha or Honeypot to expose traps for bots so that they cannot continue.

Don't work against Drupal's user and form system on this one. Let them do the work for you.

---
Tags: users, emails, commerce
---


# Question
Title: FileField Paths works bad when upload image - the wrong way comes?
I have my VPS with two sites: in first i have FileField Paths and it works bad. In second i have no FileFiled Paths and everything ok.

The error is this:

When I choose photo in the Image field and press "upload" it shows me blank image and when I open url address of this thumbnail - it shows 404. the thumbnail url is correct.

But the original image url is not corect. FileFiled paths make the original image url like this:

/system/temporary/filefield\_paths/coctail-gold.jpg

but the pattern in Image field FileField paths settings is this:

blog\_images/u\[node:author:uid\]/\[current-date:custom:Y\]

so this is the reasen why i see the blank image.

But when I save the post thumbnail shows correctly, so file creates.

Please what is wrong with FileField Paths?

# Answer
***Updated***

Assuming your installation code is not altered, I would suggest:

A.

1. Clear log messages at /admin/reports/dblog \> "Clear log messages"
2. Try and re-upload your picture
3. Check your log messages reloading /admin/reports/dblog You should find here some diagnostic about your issue.

B.

1. Check your Status is nice and clear \[ admin/reports/status \]

If nothing wrong so far, you should check FileField Paths Issues for similar issues, and eventually submit your experience. Drupal community will appreciate!

Hope will help.
> 0 votes

---
Tags: 7, files
---


# Question
Title: How to get CSS to target new nodes being inserted?
I am customizing nodes for a blog entree's so they have a certain aesthetic look to it. However, I ran into a problem.

I can enter custom CSS code to style the nodes for already existing ones and set them with classes, but if someone is going to create a new node on the site, the blog CSS doesn't appear because I have to go in to each one and constantly hand-code it.

Obviously this is time-consuming and not the right way to go about it, because anyone who creates a blog would have to wait for me to style it for them. Is there a way where I can make a CSS code that will keep the look and feel every time someone creates a new blog entree?

# Answer
I'm not sure I get the scenario. What if you apply your css to both old and new classes?

Example

```
.old_nodes .content, .new_nodes .content {
   color:red;
}

```

This will give same style to both new and old nodes.
> 1 votes

---
Tags: theming
---


# Question
Title: Show a list of my product with my coupon discount
I have 50 products. I used ubercart module and uc\_coupon for my e-commence website. I have many different type of coupons for different products and I always make human mistakes and confuse.

Here is my question: Is there anyway to show a list of products with price and discount as well?

# Answer
> 1 votes
==UPDATED==

Looks like you need views integration for the UC Coupon Module, not fully supported yet.

Maybe you want to try and port this patch to Drupal 7?

---
Tags: 7, ubercart
---


title: Remote Drush Commands Not Found

text:
# Question
Title: Remote Drush Commands Not Found
I'm using a new host for my website and I requested drush access to my site. They said it's all set and told me to run drush commands as such $ ../drush/drush command

I test it out with $ ../drush/drush status and everything works as it should.

The problem comes when I try to run drush commands remotely via my alias file. Everytime time I drush @remote I get drush: not found

I even set path-aliases to point specifically at %drush and %drush-script.

Is there something I'm missing?

# Answer
If you use, '%path-aliases', either specify the full path to Drush, or ensure that the Drush that you are calling (e.g. `drush`) is on your PATH.

**Example:**

```
$aliases["mysite"] = array (
  'uri' => 'mysite.org',
  'root' => '/path/to/drupalroot',
  'remote-host' => 'myisp.com',
  'remote-user' => 'www-admin',
  'path-aliases' =>
  array (
    '%drush-script' => '/home/myuser/drush/drush',
  ),
);

```

If setting the PATH in your .bashrc, always do so at the very top of the file. It is common for boilerplate (host-provided) .bashrc files to have a line somewhere in the middle that exits prematurely when not in interactive mode -- and Drush makes remote Drush calls non-interactively in most instances.
> 1 votes

---
Tags: drush
---


# Question
Title: Change page title of a module generated page
I'm using the Tagclouds module to generate a list of items grouped by taxonomy. The URL looks like this:

http://example.com/tagclouds/list/2

This works fine. However the automatic generated title of this page is 'Labels'. Any ideas how I can substitute 'Labels' by something else?

# Answer
The module is using its own menu definition. The title of the menu item is used for displaying the page title of the page in question (which is 'Tags' in English and 'Labels' in your Dutch version):

```
/**
 * Implements hook_menu().
 */
function tagclouds_menu() {
  $items = array();

  // [...]

  $items['tagclouds/list/%tagclouds_vocs'] = array(
    'title' => 'Tags',
    'page callback' => 'tagclouds_page_list',
    'page arguments' => array(2),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  // [...]

  return $items;
}

```

As you are using a localized version of Drupal, you have several options to change the page title.

**The first and most easy solution** is to change the translation of 'Tags' to your desired string. You can use the localization interface which is located at /admin/config/regional/translate/translate.

However, the above solution will change the translation for 'Tags' within your whole site. Which means that the new translation might appear somewhere else as well, and on an English page the title would still be 'Tags'.

**The second solution** is changing the menu item's title. You can do so without side-effects as the menu item of question is a menu callback. Its title will not be shown within your menu structure, but as page title only. As you should never touch the sources of a contributed module (for your customizations), writing a small custom module is the way to go here.

Follow this guide to get started with custom modules and create the required files. Within your custom module's MYMODULE.module file you can implement hook\_menu\_alter(), which allows you to change the menu items of other modules. In this case, we'll change the menu item of the tagclouds tag overview page:

```
/**
 * Implements hook_menu_alter()
 */
function MYMODULE_menu_alter(&$items) {
  // Whether the tagclouds menu item is defined.
  if (isset($items['tagclouds/list/%tagclouds_vocs'])) {
    // Change the menu item's title.
    $items['tagclouds/list/%tagclouds_vocs']['title'] = 'Your New English Title';
  }

  // For translation extractors, you may also implement
  // this little function call.
  t('Your New English Title');
}

```

Change MYMODULE to your module's name, activate the module and/or clear your Drupal caches. You might have to visit the page once, so that the translatable string will be known to Drupal's localization system. Afterwards you can head to the translation interface as described within the first solution and add a translation for 'Your New English Title'.

**The third solution** is to hook into the page pre-processing within your theme. Locate your theme's template.php file. If your theme is implementing the theme hook THEME\_preprocess\_page() already (which is very likely), you may just add the lines from the following function's body. If your theme does not implement this hook, you may add the whole function, renaming THEME to your theme's name. This little code checks, whether you are at the tagclouds listing page and - if so - changes the page title using drupal\_set\_title():

```
/**
 * Implements THEME_preprocess_page()
 */
function THEME_preprocess_page(&$variables) {
  // Load the current path into a variable.
  $current_path = current_path();
  // Whether the current path is the tagclouds listing path.
  if (strpos($current_path, 'tagclouds/list/') === 0) {
    // Set the page title. We use drupal_set_title here, as
    // the static page title will be evaluated within the
    // process_page function, which follows the pre-processing.
    drupal_set_title(t('Your New English Title'));
  }
}

```

Once again, following Drupal standards you set the English title here, so after you cleared the Drupal caches and visited the page once, you should follow the steps of the first solution to add an appropriate Dutch translation to your localization.

**The last solution** is suggesting the module maintainer to allow editing the page labels within the module settings. This change however might take a little longer as most module maintainers are contributing to the modules within their spare time.
> 0 votes

---
Tags: 7
---


title: Display site UUID from module

text:
# Question
Title: Display site UUID from module
Is it possible to display the site UUID on a Drupal 8 module?

# Answer
> 3 votes
"display" is pretty ambiguous, but you can get the site UUID like so:

```
$uuid = \Drupal::config('system.site')->get('uuid');

```

(depending on context, injecting the config.factory service would be preferable)

It's a string so rendering it will be easy.

# Answer
> 1 votes
for you Drupal 8 site

```
drush config-get "system.site" uuid

```

or if you need to change it

```
drush config-get "system.site" uuid "number you want"

```

---
Tags: 8, entities
---


title: add comment form in views

text:
# Question
Title: add comment form in views
I've created a views from comments. I want to have add comment form at the button of my views (in footer). so I installed "views\_php" module and add "Global: PHP" to footer and write this code to print add comment form in footer.

```
$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);

```

but the problem is that I don't have comment\_body or any other custom field in the printed form. actually just author, subject and save button.

I tried this code too:

```
print drupal_render(drupal_get_form("comment_form", (object) array('nid' => $data->nid)));

```

or

```
print drupal_render(drupal_get_form("comment_node_news_form", (object) array('nid' => $results[0]->nid)));

```

but none of them worked properly!

# Answer
```
<?php
$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);
?>

```

Works for me. Make sure that your **Content: Nid** field is **ABOVE** the **Global: PHP** field, otherwise (when it's below it) `$row->nid` is not available as a variable.

# Update

After reading your Q more carefully, **since you want it in the footer** then you need to specify the node id of the form. (Under what node this comment will be stored) **For Example**: /node/1

```
<?php
$comment = new stdClass;
$comment->nid = 1;
$form = drupal_get_form('comment_form', $comment);
print render($form);
?>

```

If you want /node/5 you change this line to `$comment->nid = 5;`

**OR**

If you want this to be dynamic, the nid to be based on the page you're viewing. Then use

```
<?php
if ($node = menu_get_object()) {
$comment = new stdClass;
$comment->nid = $node->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);
}
?>

```

**Note**: The form will not render/show on views preview, but it will show up when you visit the node.
> 5 votes

---
Tags: views, forms, comments
---


title: hook_block_view_alter() is not invoked

text:
# Question
Title: hook_block_view_alter() is not invoked
I am trying to change the way "Search results" header is rendered in D8. Unfortunately HTML is hardcoded in SearchController and not themeable. I figured I could use hook\_block\_view\_alter to change the $build\['search\_results\_title'\], but the hook implementation from my theme never gets called:

```
function labweb_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  if (isset($build['search_results_title'])) {
    unset($build['search_results_title']);
  }
  kpr($build);
}

```

Any ideas? It seems that this hook never gets called...

# Answer
> ...but the hook implementation from my **theme** never gets called:

`hook_block_view_alter()` will not be called for themes; it is invoked only for modules. This is why your hook is never invoked.

To implement this hook, you need to create a custom module. If you need help to create a module you can check here to start.

I strongly suggest to read block\_view\_alter docs too.

Look at Theme Hooks to see what you can 'hook' in your theme.
For more information about hooks look here.
> 3 votes

# Answer
Since you are trying to change the output returned from a page controller, you are implementing the wrong hook. The output of a page controller doesn't normally go in a block, but in a page. The only block the Search module implement is the SearchBlock class, which just outputs the form to search in a Drupal site, and redirect users to the search page. See its SearchBlock::build() method, which contains just a line of code.

```
return \Drupal::formBuilder()->getForm('Drupal\search\Form\SearchBlockForm');

```

In SearchBlockForm::buildForm(), you see the effective form build for that block.

```
  $route = 'search.view_' . $entity_id;
  // Notice the following line that submits the form in the search page showing the results, the one handled by the SearchController.
  $form['#action'] = $this->url($route);
  $form['#method'] = 'get';

  $form['keys'] = array(
    '#type' => 'search',
    '#title' => $this->t('Search'),
    '#title_display' => 'invisible',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('title' => $this->t('Enter the terms you wish to search for.')),
  );

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Search'),
    // Prevent op from showing up in the query string.
    '#name' => '',
  );

```

To achieve what you need, you should alter the controller invoked for the search page.

As for your hook not being involved, that is because Drupal doesn't look for the implementations of that hook contained in a theme. In fact, the code invoking it is the following.

```
  // If an alter hook wants to modify the block contents, it can append
  // another #pre_render hook.
  $module_handler->alter(['block_view', "block_view_$base_id"], $build, $plugin);

```

The module handler is a service that handles modules, not themes.

Compare that code with the code used to invoke the implementations of `hook_js_alter()`.

```
// Allow modules and themes to alter the JavaScript assets.
$this->moduleHandler->alter('js', $javascript, $assets);
$this->themeManager->alter('js', $javascript, $assets);

```

As you see, the code uses the theme manager to invoke the hook implemented by a theme.
> 0 votes

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


# Question
Title: How to use contexual filters for registration events?
I want to create a block on the side of the page that will show registered users to a event. I already have a event type and calendar system + a registration system.

When a user registers for a event, I can get the view to display it. However, it is displaying literally ALL registration users for ALL events. I am trying to get the contextual filter to just narrow it down to the specific event, but cannot get it to work.

Any help?

# Answer
You don't use contextual filter for this, you need to use relationship.

Make sure the Registration Views module is enabled.

In views under Advanced, RELATIONSHIP click add and select User: Registration

* Checkmark require this relationship.
* Checkmark your registration type name.
> 1 votes

---
Tags: views
---


# Question
Title: How to unpublish postings according to the value of a field?
I was able to set rule to unpublished after +30 days. But I would like to tweak my rule to give to my users the possibility to choose between posting for 2 weeks, one month or 3 months.

So, I guess that there would be an "if choice X, than unpublish after Y period of time". Can the field (to choose duration) be a text dropdown?

Can this be done without PHP? If so how?

---

So, I figured out that I can add a condition like this :

```
Parameter: Data to compare: [node:field-time-limit], Data value: 2 weeks

```

But since I have 3 choices for my ads (2 weeks, 1 month, 3 months), does this means that I have to make 3 different rules, one for each time limit? (it seems to make sense, but I'm not shure).

**Note**: I'm aware of the thread about "Tutorial 2: Publish content exactly 24 hours after it was created".

# Answer
> 1 votes
Your question seems to exist of actually 2 questions, so here are 2 parts of an answer to address each of them (I'm assuming this question is about D7).

# Part 1

Refer to my answer to "How to specify a Rules condition related to select list values?" for an example Rule (in Rules export format) that allows for specifying a Rules condition related to a specific value selected via a selection list.

With this (and some minor tuning of that sample to fit your field and values), you have an answer to your "***if choice X, than unpublish after Y period of time***".

# Part 2

Refer to my answer to "Redirect users with specified roles to specified term pages", which shows how you can redirect to ***various URLs*** (depending on some role). It also explains 2 possible approaches for either creating multiple rules (1 for each role) versus just 1 rule (by using the Conditional Rules module).

With this (and some minor tuning of that sample to fit your case here), you have an answer to your "***does this mean that I have to make 3 different rules, one for each time limit***". The actual answer is: either way can work (personally I'd go for just 1 rule, using the Conditional Rules module).

**PS**: So yes this ***can be done without PHP***, it only requires some site building using the Admin UI for Rules.

---
Tags: rules
---


title: Using field values in page.html.twig

text:
# Question
Title: Using field values in page.html.twig
Using Drupal 8.

I want to display the value of a field (field\_date) at the top of my page, in the header, so I need to output it in page.html.twig. I'm having issue with this, though, which I think boil down to the scope of where variables are available.

To clarify - I can print field\_date in node.html.twig no problem by just using content, but since I need it so high on the page, I'm hoping for a way to print it in page.html.twig.

I'm open to any solution, but here's a possible solution I picked up from searching on this same topic:

In THEMENAME.theme

```
/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
    $element = $variables['element'];

    if($element['#field_name'] == 'field_date') {
        $variables['promo_date'] = $element[0]['#markup'];
        dpm($variables['promo_date']);
    }
}

```

In page.html.twig:

```
<div class="theme-date">{{ promo_date }}</div>

```

In this example, the dpm does work, but the promo\_date displays nothing. Doing kint(node) returns a large number of methods, but none seem to be the fields I need. Unfortunately the solution I borrowed from was taking a page-level variable and adding it to field.twig.html, and I think the scope reversal is the problem.

# Answer
If you want to see the result of your code in `THEMENAME_preprocess_field()` you have to put `{{ promo_date }}` in a `field.html.twig`.

But in your question you asked about the `page.html.twig`. To access the field value in this template, you can use the node object, which is preloaded in the page template. But only if there is a node in the url of your page. Otherwise this will return an empty string:

```
{{ node.field_date.value }}

```
> 3 votes

---
Tags: entities, 8
---


title: How to get random query?

text:
# Question
Title: How to get random query?
I use this code in my module for random query:

```
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'client')
->fieldCondition('field_client_enabled', 'value', 1)
->addTag('random')
->range(0, 1)
->execute;

```

with additional function:

```
function mymodule_query_random_alter($query) {
  $query->orderRandom();
}

```

But why I get "undefined method" error when use

```
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'client')
->fieldCondition('field_client_enabled', 'value', 1)
->orderRandom() // why is this wrong?
->range(0, 1)
->execute;

```

?

Update:
**Answer**:
Found that orderRandom() is SelectQuery function, but not EntityFieldQuery

Can I simplify first code to variant without additional function?

# Answer
> 2 votes
> Can I simplify first code to variant without additional function?

Not natively, as you've rightly said EFQ doesn't have a random order method. At a guess that's because field storage is pluggable, and it would be tricky to come up with a cross-compatible method that makes sense for e.g. MySQL and MongoDB. Might be wrong though, it may simply not have been considered important enough to implement/overlooked/etc.

If the extra step is unacceptable, the other option would be to subclass `EntityFieldQuery` to add your own random order method, and override the execute callback with your own version of `field_sql_storage_field_storage_query()` to get it into the final query.

The method you already have is arguably a bit cleaner than that; certainly it's less effort.

---
Tags: 7, database
---


# Question
Title: Configure Videojs to use the local library
Videojs in Drupal 8 gives the following error:

> Missing the Video.js library. Please download Video.js and extract it into the //vjs.zencdn.net/5.0 directory.

How can I configure Videojs to use local files? Where should I put Videojs files?

I think Videojs has not configuration interface.

# Answer
The README.md included with the downloaded module says:

> 2. Download the Video.js library from http://videojs.com. Extract the module to `sites/all/libraries/video-js` and make sure that `sites/all/libraries/video-js/video.js` exists. NOTE: you can skip this step and use the Video.js version from the Video.js Content Delivery Network (CDN).

A comment in the documentation block in the module file suggests that the Libraries API determines where to places libraries.

> Defaults to videojs\_directory when using the local file path location or whatever location the Libraries API determines.

This location is also set by the videojs\_directory configuration variable, which could be set by importing a YAML file via Configuration Management interface or with a tool such as Drush or Drupal Console despite the Video.JS module not having a specific configuration page.
> 2 votes

---
Tags: 8
---


# Question
Title: How do I preserve custom files in my Drupal configuration across minor core upgrades?
When I do a minor upgrade of the core, my custom `.htaccess` and `robots.txt` are overwritten.

How do I prevent that?

# Answer
> 5 votes
You can build a site totally with git to help manage this process. The process is basically

Git clone into your DOCROOT:

```
git clone --branch 7.x http://git.drupal.org/project/drupal.git /var/www/mysite/docroot

```

Rename the remote:

```
git remote rename origin drupal

```

Checkout the latest tag, and make a site branch for your site:

```
git checkout 7.26
git branch -b mysite

```

Now, you can build your site and customize robots.txt and .htaccess to your needs.

When there is a core update, you can:

```
git fetch drupal

```

and then use the normal git methods for merging your changes in, eg:

```
git merge 7.27

```

or you can preview what will happen, check for conflicts, etc.

If you do this, you need to make sure you don't do a plain:

```
drush pm-update drupal

```

as this will then mess things up. I do not think that `drush pm-update --lock=drupal` works to prevent this.

# Answer
> 4 votes
One way to solve this, is as follows:

1. Create a set of patches that patches any altered files (i.e. `.htaccess`, `robots.txt`, and other files where you're have added customization).
2. After downloading the new minor release of the core, apply the patches. Check if there are any conflicts.
3. If there are no conflicts, great - you're done! If there are conflicts, resolve them. Iterate until there are no more conflicts.

You can script this, using *drush* for doing the upgrade and *git* for managing patches and checking for conflicts. This usually makes upgrading quick and painless, even if you've have customized `.htaccess`, `robots.txt`, and other files.

# Answer
> 0 votes
For Apache & configurations without Git, you can alias the root `robots.txt` to another file. For example, in `httpd.conf`:

```
<VirtualHost *:80>
    ServerName mydevsite.example.com
    DocumentRoot /var/www/html/mydevsite
    Alias /robots.txt /var/www/html/mydevsite/robots.disallowed.txt
</VirtualHost>

```

`robots.txt` will still be overwritten with each core update, but will be unused by visitors & crawlers.

---
Tags: version-control, upgrading
---


# Question
Title: Failing to create thumbnail, medium and large images
When using a new installation of Drupal 7.10, I have set the directory for public uploads to `sites/uploads`.

When I then add an image to a content instance, I get the original uploaded to `sites/example.org/files/imagename.png` as expected. However, the other images (thumbnail, medium and large) do not get created at `sites/example.org/styles/*`.

The directory is readable and writeable by the PHP5-FPM user, and so there should be no issue permissions wise.

Why does this happen? How can I fix it?

# Answer
> 13 votes
Right, the answer is in fact a little more subtle than I realised. Turns out that D7's `imagecache` replacement needs some attention in your nginx vhost. Without the 404s being sent to Drupal for the missing files, the images are not created - something I didn't realise initially, as I'd assumed they were created on upload.

```
location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;
}

```

It needs to be added to your server definition, and you should be ready to roll. Clearly, the path may need altering for your setup, but for mine it was.

# Answer
> 2 votes
Be sure to check both the public file system path and the temporary path at admin/config/media/file-system

Once I had both of those folders set with the correct permissions, my subfolders are automatically created when I save a file, the image is saved, and the error message is gone :-)

# Answer
> 2 votes
In my case the issue was causing because the images were fetched using https,

I added the following lines on the secure page settings to ignore https on file paths.

`*/files/*`

Hope this helps someone. :)

# Answer
> 1 votes
While you do say that you have checked permissions, that's still where I would start, as I've had this issue myself, frequently, and it's nearly *always* been a permissions problem.

**General advice:** First of all, go to admin/config/media/file-system, and click "Save configuration". This will cause Drupal to re-evaluate the permissions of the set directories, and will give you error messages if it finds a problem.

Second: I assume that you have a apache, or www-data, or other users, that owns the webserver, as opposed to the php user? On a Linux or Mac system, sudo to that user. Trying to write a file *as the right user*, is the best way to truly ensure that you have the right permissions. Go to sites/domain.com/files/, and call "echo data \> new\_file; cat new\_file;" in a terminal. This will verify that you actually can write to the write directory. Do the same with your tmp dir. Hopefully someone else can suggest how to perform the same actions on a system like windows.

Third: To rule out directory permissions, recursively apply 777 the the files directory. You can restore more sane permissions afterwards with

```
find . -type d -print0 | xargs -0 chmod 755
find . -type f -print0 | xargs -0 chmod 644

```

Fourth: Ensure that the tmp directory that has full permssions.

Fifth: You may need to start debugging the code if you have figured it out by now.

# Answer
> 1 votes
To complete Letharion answer, here is the method I used to get thumbnail, medium... image styles created.

I precise that I first checked all the points listed above, without result.

Then (on a Linux OS), I edited */usr/local/etc/suphp.conf* to **change umask on php**, so that it could create files AND directories with 755 permissions max (it was on 744 max).

And this definitively solved the problem. :)

# Answer
> 0 votes
I'm on Drupal 8.0.3.
On my case this folder is not generated on the installation.

```
sites/default/files/field/image

```

So I put it by copying from the older version of Drupal installation.
All images including thumbnail, medium and large are now show up.

# Answer
> -1 votes
Check you .htaccess file in root and files directory. Replace with the new .htaccess file if required

---
Tags: 7, media
---


# Question
Title: After upgrading, no content types under node/add
I am updating a Drupal/Tripal site on a test system. When I try to add content after migrating core using /#overlay=node/add or /node/add I get:

> You have not created any content types yet. Go to the content type creation page to add a new content type.

However, under content types it lists all my content types (page, article, blog, etc). I notice that this looks very similar to No content types showing under 'Add content'

but the accepted answer doesn't help me, because it is not about the state after a d7 update, and I don't know how to apply the steps in a d7 install.

The Navigation contains: Add content Blog entry Book page Forum topic Page Poll RNAi Story

Sub-type links like node/add/page work, still node/add lists no content types.

# Answer
> 5 votes
I finally managed to fix this by accident while trying to fix a different issue.

Following this post: https://drupal.stackexchange.com/a/82222/25238 Similar to https://www.drupal.org/node/997444

I first tried `drush eval 'menu_rebuild();' drush cc menu` which didn't have an effect, then I found the hint in a comment by nilsun to the above post, that sometimes a complete reset might be necessary. This seems to be caused by a corrupt menu system.

```
$drush sqlc
Password for user user:
psql (8.4.20)
Type "help" for help.
## if you want to try to keep your own menus you could
## first try:

DELETE FROM menu_links WHERE module = 'system';
# edit: typo, it's module, not menu
## Tested, did keep my custom menus

## D_ELETE FROM menu_links # Don't this will delete your custom menus too!
DELETE 748
d7=# DELETE FROM menu_router;
DELETE 909
d7=# \q
$ drush updb
No database updates required                                                          [success]
'all' cache was cleared.                                                              [success]
Finished performing updates.                                                          [ok]
$ drush cc menu
'menu' cache was cleared.                                                             [success]
$ drush eval 'menu_rebuild();'
$ drush cc menu
'menu' cache was cleared.                                                             [success]

```

Maybe one or two steps can be omitted, but that brought back the content types under "Add content", **Edit Warning: while some of my self defined menu entries disappeared, but this should be easy to fix editing them manually**.

# Answer
> 1 votes
If I understand your question correctly, the menu items for your content types are at the same level as the 'Add content' menu item in your menu structure. They should be nested underneath it, like so:

```
Add content
    Blog entry
    Book page
    Forum topic
    Page
    Poll
    RNAi
    Story

```

On a standard Drupal installation, the page where you can rearrange the menu items is `/admin/structure/menu/manage/navigation.`

---
Tags: 7, migrations, updating
---


# Question
Title: Check if the entity is new from the entity insert hook
I have a custom content type, when I create a new content of this type via the admin ui I want be redirect to the edit page of the new node (not to the view page by default)

So, from an alter form hook, it's not possible because I don't know yet the node ID of the future node. From `hook_entity_presave()` it's the same: I don't know yet the node ID of the future node. From `hook_entity_insert()` hook, I have the node ID, but I don't know how can I check the entity is just created.

From `hook_entity_insert()`, is it possible to know if the entity is just created?

# Answer
`hook_entity_insert()` is invoked only when an entity is created, not updated. That is evident from the method invoking it, `EntityStorageBase::doPostSave()`.

```
  // Allow code to run after saving.
  $entity->postSave($this, $update);
  $this->invokeHook($update ? 'update' : 'insert', $entity);

```

`hook_entity_update()` is invoked for an entity being updated; otherwise `hook_entity_insert()` is invoked.

See also the description for the `$update` parameter passed to `EntityStorageBase::doPostSave()`.

> **bool `$update`**: Specifies whether the entity is being updated or created.
> 2 votes

---
Tags: hooks, 8, entities
---


# Question
Title: View author field (image) in a node view
I have created a image field in the user account. How can I add the image of the author to the display of each node?

# Answer
You may do that using a Views Block and place it in the Main Content block region, right after the content block. Also, you'll need to create a relationship between the node and it's author, so only the correct user will be displayed. Below is a screenshot of a work I've done using Views for Drupal 7.42 that I think is close to what you're looking for:

1 - Create a new Block View to view Users (not Content)

2 - Filter Criteria should say User: Active (Yes)

3 - There is a default sort Criteria item. Remove it since it doesn't matter.

4 - Add a Relationship: Choose "User: Content authored"

5 - Add a Contextual Filter: Chose "Content: Nid"

6 - In the configuration options for the newly added Content: Nid, choose these options: WHEN THE FILTER VALUE IS NOT AVAILABLE: Provide default value In the Select box, choose Content ID From URL.

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED Specify validation criteria Validator select box: Content Content Types: choose the content types you want the view to work with. Filter Value Format: Node ID Action to take if the filter value does not validate: Hide View

7 - Save the View.

8 - Go to Structure -\> Blocks and configure the block to show on the types of content you want it to show on and position it wherever you want it to appear.

9 - Done.
> 2 votes

---
Tags: nodes, entities, media
---


# Question
Title: When I am logged-in the page doesn't look the same as when I am logged-off
Do I need to include something in the code or in settings.

I have a problem which is that pages don't look the same when I am login or not. Like on photo down. Some help or suggestion?

This is my code. Does I need to add Edit and view bartik?

Whan I change **base theme: stable** with **base theme: bartik** bug is fixed.

```
<main role="main" class="node-main">
<div class="container">
    <div class="row">
        <a id="main-content" tabindex="-1"></a>{# link is in html.html.twig #}

        <div class="col-md-8 node-page">
            {{ page.content }}
        </div>{# /.layout-content #}

        <div class="col-md-4 node-aside">
            <aside >
            {% if page.sidebar_first %}
                    {{ page.sidebar_first }}
            {% endif %}
            {% if page.sidebar_second %}
                    {{ page.sidebar_second }}
            {% endif %}
            </aside>
        </div>

    </div>
</div>

```

# Answer
> 0 votes
What you see / notice is pretty standard Drupal ... The link like "Add content" is something you typically only want to be shown for logged in user (and maybe even limited to users with roles such as "content editor" (or whatever you'd call it). Also, the small icons in the upper left (above "logo" and "home") are typically also things you only should be able to use if you are logged in.

Should you want to change any of such things (eg: anonymous users should also be able to "add content"), then it's just a matter of finding out which permission it is that actually governs the specific function (such as "add content"), and then indicate in your "permissions" page within admin that is related to it that you want "role" anonymous to have the very same permission.

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