# Question
Title: How would you implement an automatic way of the images loading in a pop-up (lightbox/colorbox) window by a click?
What I mean is, can we achieve the blogspot.com/Blogger experience where we can add photos to the content (node in Drupal speak) and without any ado (adding `class="colorbox"`, or enclosing the `<img>` element into an `<a>` ), clicking the photo in the post will make it enlarged in a pop-up window, similar to how colorbox functions.

I have visited this question Configuring Lightbox2 to Pop-Up Images embedded in nodes and it seems ambiguous to me.

I have a current Drupal 7 site and it's quite annoying that I have to manually enclose the images in a

```
<a class="colorbox colorbox-insert-image" href="..." title=..."> ... </a>

```

every effing time.

# Answer
> 0 votes
You can. As always, there are several ways.

You can implement a Drupal behavior (jQuery script) that finds all images within the content and adds according classes / click callbacks.

Another way would be writing a little custom module implementing a content filter that does the same on your server.

I'm not at a PC right now. But I think you have two viable ideas now to search for. Let me know, if you need further help.

---
Tags: javascript
---


# Question
Title: How to use both #anchor and ?destination parameter in a node/edit url?
I have a long page containing a node edit form and I wish to direct the user to a specific part of the page.

My URL is `/node/12364/edit?destination=node/12360`.

Where in the URL should I add the anchor?

I tried `/node/12364/edit#anchor?destination=node/12360` but it doesn't work. The anchor is not used, the user isn't directed to a specific part of the page.

If I enter `/node/12364/edit#anchor`, it works but I need the destination parameter.

# Answer
> 5 votes
Page fragment is always passed after the query string. Otherwise, the browser will recognize the query string as part of the fragment.

Here's how your URL should look like:

```
/node/12364/edit?destination=node/12360#anchor

```

However, if you were asking how to pass anchor to the *destination* page, you simply need to use encoded hashtag instead. Here's how the URL should look like in this case:

```
/node/12364/edit?destination=node/12360%23anchor

```

`%23` is encoded `#` character. See this page for more info.

---
Tags: 7, uri
---


# Question
Title: How to set the values of some fields depending on the value of a list box?
Remember the create password page of Drupal! while you are entering characters it tells you how string is your password!

now I want to have something like this in a list box but a bit different. I want to show an image and a text depend on the item which is selected in the list box! How can I do it?

My first try was using conditional field but I have to add 120 image and text field to my content type and but lots of conditions to handle it. It doesn't make sense!

My second try was using markup module but I didn't know how to fetch the value of list box with ajax!

My third try was using entity referenced auto fill but when I select an item from the list box for the first time it fills the other fields correctly. but the next times it does not change any thing.

in addition, I need the image and text field to appear read only (non editable)

Do you know any other way to do that?

# Answer
> 0 votes
Below is a sample of a rule (in Rules export format) that you can use as a prototype to answer your question by using the Rules module:

```
{ "rules_set_field_value_based_on_value_of_selection_list_field" : {
    "LABEL" : "Set field value based on value of selection list field",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
    ],
    "DO" : [
      { "SWITCH" : {
          "USING" : { "data" : [ "node:field-optionlist" ] },
          "DO" : [
            { "CASE" : {
                "USING" : { "value" : "B" },
                "DO" : [
                  { "data_set" : { "data" : [ "node:field-free-format-text" ], "value" : "B.A.S.I.C." } }
                ]
              }
            },
            { "CASE" : {
                "USING" : { "value" : "A" },
                "DO" : [
                  { "data_set" : { "data" : [ "node:field-free-format-text" ], "value" : "A.D.V.A.N.C.E.D." } }
                ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules event I'm using is "before saving content".
* In my case I have these fields:

+ a selection list field with machine name `field_optionlist`.
    + a text field with machine name `field_free_format_text`.
* The selection list field actually has 3 possible values, like so:

+ A (=Advanced).
    + B (=Basic).
    + C (=Custom).
* As a sample, I decided to set the values of the text field like so:

+ B.A.S.I.C. if "The selection list field's value is `Basic`".
    + A.D.V.A.N.C.E.D. if "The selection list field's value is `Advanced`".
    + Leave it unchanged if "The selection list field's value is `Custom`"

Part of the "clue" to make this rule work is the condition `Entity has field`. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". I wouldn't be surprised if that is what you are missing in the rules conditions you tried so far ...

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

However, to make the above work, and to be able to get this to work with only 1 rule (instead of writing 2 rules, ie one for "Basic", and one for "Advanced"), I also used the "Conditional Rules module. That way you could expand the above prototype to say dozens of different possible values. For a sample using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

**Note**: the Field Permissions module should help you to make such text field read only.

---
Tags: ajax, entities, theming
---


# Question
Title: How to decide to create a content type or two if there are both common and uncommon fields?
I have a content type that has about **80** fields.

It has a select list field at top and there are two options: `Yes` or `No`.

If **Yes** is selected all the 80 fields are used and if the **No** is selected, the last 30 fields are not used. For both two options, 50 fields are **common**.

I wonder, if I should go for creating **two content types** for this structure, or if continuing with "**one**" (only) is better. If I continue with this "one" content type, 30 fields will be empty for the "No" options and can it be a "bad" thing for the database (waste of space etc.)?

*(If I continue with one content type I will use some modules such as Conditional Fields etc).*

## Is there anybody faced with a similar situation and is there a "better" way?

*(Additional information: this content type is used for an academic resource. If the resource is in English I will only fill the 50 fields. If the resource is in another language I will fill the 50 fields and also fill the other 30 fields.)*

# Answer
I would use only 1 content type, and use the Conditional Fields module to hide those 30 extra fields for your select list field with value **No**.

This excerpt from this module's project page seems to perfectly fit as a possible solution for this approach:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
>
> You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

# Possible alternative

True, you might also go for 2 content types instead. But in that case you're using an approach as described in the (illuminating, I think) article "Relativity model for Drupal". For more details on that, and the typical modules involved in that approach, refer to my answer to "How do I model content (types) from a database-centric point of view?".

In the long run, I bet the overall implementation of your entire site would be much better (eg: you'd need way less contributed modules). But that also implies you're willing to do a way higher effort/investment then just adding the Conditional Fields module.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Status message "The changes have been saved" displays when updating user data using AJAX and Services module
I am using `navigator.geolocation.getCurrentPosition` to get the user's current location, and then using the Services module to update the user's location (part of the user object) via AJAX.

Here is the AJAX call to the service:

```
jQuery.ajax({
  type: "PUT",
  url: "/api/internal/user/" + uid,
  data: JSON.stringify(geolocation),
  dataType: "json",
  contentType: "application/json",
  success: function(r) {
    console.log(r);
  }
});

```

The update works just fine, but when I navigate to another page afterwards, I get the status message: "The changes have been saved". After some digging, I found that this status message gets displayed any time user data is updated, which is fine usually, but will be confusing in this scenario since data is being updated behind the scenes. I'm assuming that since the user update is taking place via AJAX, the status message doesn't get displayed until next page load.

Is there any way to prevent Drupal from displaying this status message only when user data is updated using Services?

# Answer
On your menu callback function ( at */api/internal/user/%user* ) you can call `drupal_get_messages('status');`. This will clear the status messages displayed to the user. A better approach would be to check the message first:

```
$message = drupal_get_messages('status', false);
if( $message == t('The changes have been saved.') ) {
  drupal_get_messages('status');
}

```

If this is not a custom module, you should build one and use hook\_page\_alter() like this:

```
function yourmodule_page_alter(&$page){
  if(arg(0) == 'api' && arg(1) == 'internal' && arg(2) == 'user') {
    $message = drupal_get_messages('status', false);
    if( $message == t('The changes have been saved.') ) {
      drupal_get_messages('status');
    }
  }
}

```
> 0 votes

# Answer
If you want to use JavaScript/ jQuery then simply use it:

```
$(document).ready(function(){
 if($("h2.element-invisible").text() === "Status message") {
    $("h2.element-invisible").parent().css('display','none');
 }
});

```
> 0 votes

# Answer
In one of our recent projects, the client wanted to block users from changing some of their own profile values based on some run-time logic. However, even if nothing was changed, the user core module would send the message "The changes have been saved." which would be confusing for the user.

The accepted answer here will delete ALL pending Drupal messages if a match is found for one of the messages--perhaps not a desired outcome.

We decided to implement a more general-case message interception scheme. Given the restrictions not to upset the Drupal 7 core, it ends up being somewhat convoluted, but the run-time performance hit is mitigated given the extra conditionals.

Given that this code is accessing only the $\_SESSION variable, it can be placed in a template or module, and the '...clear...' function should be called from within a late-stage preprocess-page hook/theme/template function (e.g., template\_preprocess\_page(), hook\_page\_build(), etc.).

Anyway, here's the code we used, in case it helps others:

```
 /**
 * Adds message to intercept and delete upon next page load.
 *
 * intercepts system message so that it's not displayed to users
 * (usually to avoid confusing Drupal messages)
 *
 * @param string $message
 * The exact text that will be intercepted.
 *
 * @param string $type
 * The Drupal message type that will be intercepted.
 */
function mymodule_intercept_system_message($message = NULL, $type = 'status') {
    if (NULL !== $message) {
       $_SESSION['mymodule_intercepted_message'][$type][] = $message;
    }
}

/**
 * Clears system messages that have been flagged for interception.
 *
 * See: mymodule_intercept_system_message()
 * Admin will still see the intercepted message with added prefix.
 *
 * @param bool $clear_flagged_messages
 * boolean: true = All flagged messages are cleared for next page load, defaults
 * to true
 *
 * @return
 * bool TRUE if message was intercepted, FALSE otherwise
 */
function _mymodule_clear_intercepted_system_messages($clear_flagged_messages = true) {
/**
 * Interact directly with $_SESSION since drupal core function drupal_get_messages()
 * only allows for all or no messages to be deleted, not specific messages
 *
 * drupal messages:
 *      $_SESSION['messages'][type][idx] = message-text
 * intercept messages:
 *      $_SESSION['mymodule_intercepted_message'][type][idx] = message-text;
 */
    $retval = false;
    if (isset($_SESSION['messages'])) {
        if (isset($_SESSION['mymodule_intercepted_message'])) {

            foreach ($_SESSION['messages'] as $type => $message_array) {
                foreach ($message_array as $key => $message) {

                    if (isset($_SESSION['mymodule_intercepted_message'][$type])) {
                        foreach ($_SESSION['mymodule_intercepted_message'][$type] as $int_key => $int_message) {

                            if ($int_message === $message) {
                                //message found, clear it so it doesn't display
                                unset($_SESSION['messages'][$type][$key]);

                                //unset entire type if empty, so Drupal doesn't ouput blank message block
                                if (0 == count($_SESSION['messages'][$type])) {
                                    unset($_SESSION['messages'][$type]);
                                    // unset messages if empty,
                                    // because Drupal core expects array not to exist if empty
                                    if (0 == count($_SESSION['messages'])) {
                                        unset($_SESSION['messages']);
                                    }
                                }

                                $retval = true;
                                if (user_access('administer users')) {
                                    //let admin know of message
                                    drupal_set_message('Intercepted message was: ' . $message, $type);
                                }
                            }
                        }
                    }

                }

            }
        }
    }

    if ($clear_flagged_messages) {
        //clear out all flagged messages for next page load
        unset($_SESSION['mymodule_intercepted_message']);
    }

    return $retval;
}

```
> 0 votes

---
Tags: ajax, javascript, services, status-messages
---


title: Adding Poll to Blog Content Type

text:
# Question
Title: Adding Poll to Blog Content Type
I'm using D7, and I've created the Content Type 'Poll'. That said, I want to add a specific Poll I've created to a published Blog Entry. Is this possible? I thought about creating a poll block, but this would just publish the same poll on all of my Blog Entries? I also can't seem to add a specific Poll field to my Content Type 'Blog'...

# Answer
You need to install Entity reference module

Then in your blogs content type, add a new field

* Name: \[what ever you like\] I named mine aaaa
* Type: entity reference
* Widget: auto complete.
* Then on the settings page for Target Bundle select poll.

Then edit your block, and in entity reference field (aaaa), type your poll name and save changes.

---

In Views, create a block view of poll.

Under Advanced, RELATIONSHIPS add Entity Reference: Referec**ing** entity NOT referenc**ed**.

**Checkmark require this relationship**.

Then add a CONTEXTUAL FILTER of Content: Nid

For Relationship, select your referecing

Provide default value, Content ID from URL.

Note: your view preview will be blank, but it will show up when you view the blog.

Lastly, in blocks, assign your view block to a region.

Now this will automatically show the poll that you reference in your blog.
> 0 votes

---
Tags: 7, polls
---


title: Show only "Read more" link

text:
# Question
Title: Show only "Read more" link
How can show only "**read more**" link in node's teaser, and remove or unset other links like "add new comments" or "2 Comments" at the end of a node teaser?

# Answer
> 4 votes
There are two ways to do this:

1. Through PHP. This is the correct way. The code below would go in your theme's `.theme` file.

```
function YOUR_THEME_preprocess_links(&$variables) {
  // Determine which links should be removed. These are CSS classes, because
  // they are used as keys in the $variables['links'] array.
  $links_to_remove = array(
    // X comments link.
    'comment-comments',
    // X new comments.
    'comment-new-comments',
    // Add new comment.
    'comment-add',
  );
  // Loop through the links and remove them.
  foreach ($variables['links'] as $css_class => $link) {
    if (in_array($css_class, $links_to_remove)) {
      unset($variables['links'][$css_class]);
    }
  }
}

```
2. Through CSS. This is not the best way, but is faster:

```
.your-node-selector .node__links li.comment-comments,
.your-node-selector .node__links li.comment-new-comments,
.your-node-selector .node__links li.comment-add {
  display: none;
}

```

# Answer
> 1 votes
If I remember correctly, Drupal 8 uses views to display teasers.

If that is the case, all you have to do is edit the teaser view and change `Content: Teaser` to `Content: Fields` and then just add the fields you want. Basically, you can create your own custom teaser.

---
Tags: 8, nodes, navigation
---


# Question
Title: Allow user to use entity reference to nodes they own?
I have a Doodad content type that has a couple of Entity Reference fields, for example, parentDoodad. Those fields point to other Doodad nodes. When I'm logged in as an Admin, I'm able to use the auto-complete field to set any doodad in the parentDoodad field.

However, if I switch to a different user and create Doodad1 and Doodad 2 (so that I have multiple nodes owned by this user), when I try to use the entity reference field, it won't show me any of my other Doodads.

If I give my non-admin-user the "Bypass content access control" permission, then I'm able to see and choose those other Doodads in the parentDoodad field.

I want users to be able to choose any of their own Doodad nodes. Is it just a matter of configuring certain permissions? How do I let UserA be able to choose from UserA's nodes in that entity reference field?

# Answer
> 4 votes
You can do it this way.

1. Create a view to list the nodes of particular type.

1a. Add a contextual filter of `Content: Author Uid` and provide default values as `USER ID from logged in user`

1b. Add a `Entity Reference` display to the view.
2. Now go to the `Entity Reference` field you have created in your content type and edit it.

2a. Under `Entity selection` select the `Mode` to **Views: Filter by an entity reference view** then you will get the view you have created above and select it.

2b. Save the changes.

This way the user will see only the node they created in the reference field. Read More

There is a second way also, you can implement `hook_query_entityreference_alter()` and alter the query. Read More

# Answer
> 1 votes
Wolverine's solution will break if an admin is editing the node. The field will then show only nodes the current user (admin) has created.

A better solution is to use "User ID from URL" and check "Also look for a node and use the node author"; that way when content managers are reviewing nodes, the entity reference field will reflect the original author's nodes, rather than the managers' own.

# Answer
> 0 votes
if I select {"User ID from URL" and "Also look for a node and use the node author"}: This solution will break if an user is adding a new node. The field will not show any nodes

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


# Question
Title: How to Implement Modal AJAX Form Pagination
With the new Drupal8 Modal API I've been able to get a pretty powerful form going.

The form essentially does a POST to an API and displays some search results, which the user can filter. I want to paginate these results.

I'm having a lot of trouble wrapping my head around how this could be done, whether it's with custom ajax requests to increment some kind of counter that is used in the buildForm() function that does the API call, or something else. I've attempted to use Drupal's built in pagination but that doesn't seem like a feasible option as it doesn't even take route parameters.

A full example of the form can be seen at https://github.com/acbramley/embridge/blob/master/src/Form/EmbridgeSearchForm.php

Pagination seems to be broken in core through modals as well, when using a modal window to display (for example) the admin/content screen, pagination doesn't work.

# Answer
To implement this I went down a similar route as the "Add another item" functionality on field api fields. For reference, this is done in WidgetBase.php.

Firstly, I copied over a couple of static functions to get and set values inside storage:

```
/**
 * {@inheritdoc}
 */
public static function getModalState(FormStateInterface $form_state) {
  return NestedArray::getValue($form_state->getStorage(), ['search_results']);
}

/**
 * {@inheritdoc}
 */
public static function setModalState(FormStateInterface $form_state, array $field_state) {
  NestedArray::setValue($form_state->getStorage(), ['search_results'], $field_state);
}

```

Then in buildForm() I added this to intialise the storage if it wasn't set yet.

```
if (!static::getModalState($form_state)) {
  $field_state = array(
    'page' => 1,
  );
  static::setModalState($form_state, $field_state);
}

```

And then use the storage to get the page parameter for my search:

```
$modal_state = static::getModalState($form_state);
$page = $modal_state['page'];
$search_response = $this->getSearchResults($page);

```

The crucial part of the implementation was separating the increment in the page variable from the ajax handler and putting it into the submit handler. So for the "Next" button:

```
// Add "next page" pager.
$form['next'] = [
  '#type' => 'submit',
  '#value' => $this->t('Next'),
  '#submit' => ['::nextPageSubmit'],
  '#ajax' => array(
    'callback' => '::searchAjax',
    'wrapper' => self::AJAX_WRAPPER_ID,
    'effect' => 'fade',
  ),
];

```

And the submit handler

```
/**
 * Submission handler for the "Next page" button.
 *
 * @param array $form
 *   The form.
 * @param FormStateInterface $form_state
 *   The form state.
 */
public function nextPageSubmit(array $form, FormStateInterface $form_state) {
  // Increment the page count.
  $modal_state = self::getModalState($form_state);
  $modal_state['page']++;
  self::setModalState($form_state, $modal_state);

  $form_state->setRebuild();
}

```

My ajax callback is then the same for searching, and paginating.

I also added a submit handler to the search button to reset the page back to 1.

The full source code for the form in this state can be found at https://github.com/acbramley/embridge/blob/2a561c9c388ccf715f93727cf136e50fc02163c9/src/Form/EmbridgeSearchForm.php

These code snippets are essentially the guts of what I needed to get the pagination working.
> 0 votes

---
Tags: forms, ajax, 8
---


# Question
Title: views pass argument for number of records to display to pager contextual filter?
Drupal 7.

Is it possible to pass an argument to the contextual filter to limit number of items to display in a View from the UI?

IOW: can you pass an argument that replicates the Number Of Items portion of the Pager?

I have a node form which uses View Fields to display a view of related items. I want to pass an argument via the Field Display which limits the # of records.

If this must be done programmatically, how do I hook into the view 'contextually'... ie. so that the hook overrides the Number Of Items when the visitor is on a particular page (a Node of a certain Content Type.)

# Answer
> 1 votes
I don't think it's possible through the Views interface. But I think you could probably do it through a small custom module.

```
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_name') {
    $limit = $arg(1) //where $arg is the argument from your url
    $view->items_per_page = $limit;
  }
}

```

# Answer
> 1 votes
In depth you can do something like this:

```
/**
 * Implementation of hook_views_pre_build().
 */
function modulename_views_pre_build(&$view) {
  // Offset: starting point (position) of the subset of nodes
  if (!empty($_REQUEST['offset'])) {
    $offset = (int) $_REQUEST['offset'];
    if ($offset >= 0) {
      $view->set_offset($offset);
    }
  }
  // Limit: is the number of nodes to return
  if (!empty($_REQUEST['limit'])) {
    $limit = (int) $_REQUEST['limit'];
    if ($limit >= 0) {
      $view->set_items_per_page($limit);
    }
  }
}

```

Now when you'll execute your view the URL should be something like this:

http://an-awesome-drupal-site/your-view-path?limit=25&offset=5 and its done ;-)

---
Tags: views, paging
---


# Question
Title: allow user to choose from his own referenced nodes
I have two content types: business listing, product listing. "Product listing" has an Entity Reference field. This field points to the nodes of "business listing". I want to allow user to choose from his own "business listing" nodes (during adding a "product listing" node). I have created a view to list the nodes of "business listing" type and have Added a Entity Reference display to the view. Then have selected the view Under "Entity selection". Now, I have a problem in adding proper contextual filter. I have added a contextual filter of "Content: Author Uid" and selected "provide default value".

a) if I select "USER ID from logged in user" as default value:

This solution will break if an admin is editing the node. The field will then show only nodes the current user (admin) has created.

b) if I select {"User ID from URL" and "Also look for a node and use the node author"}: This solution will break if an user is adding a new node. The field will not show any nodes!

How can I achieve this?

# Answer
For type: select PHP Code

and put this code in there.

```
$url = $_SERVER['HTTP_HOST'] . request_uri();
$getnid = explode("/", $url);
$var = $getnid[2];

if (is_numeric($var)) {

  $node = node_load($var);
  return $node->uid;

} else {

  global $user;
  return $user->uid;

}

```

**Explanation of code**

Line 1 gets the current page url

Line 2 implements the explode php function

Line 3 grabs the 2nd `/` from the url

Then we use an if statement to check if line 3 is a number or not:

* If it is a number then it has to be the `node/2/edit` form. The `2` is the nid, which we then use to grab the author (uid).
* Else, if it's not a number, then we know that it is the `node/add` form. So since it doesn't have a number in the url, we use the logged in user uid instead.
> 0 votes

# Answer
No need to write any code for this. Use reference\_option\_limit module properly in your content types & when you create view and provide default value 'User ID from URL' - Please mark the checkbox 'Also look for a node and use the node author' to true.

Enjoy !!!
> 1 votes

# Answer
You could add the author uid to the url for creation and editing.

node/add/contenttype/123 and node/#/edit/123 where 123 is the current user during creation and is the author during edit.

Make your entity reference view pick the raw value from url.
> 0 votes

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


# Question
Title: How to show a map of the User's Location in the User's profile with Address Field and Geofield
So, the location + Gmap module showed a map of the User's address in the user's profile once it was geocoded. Is there an equivalent widget that will show a map of the user's address in the profile itself?

# Answer
> 0 votes
Use module getlocations. It also supports paths like "/getlocations/user/xxx" and "/getlocations/users" for location-enabled users

---
Tags: google-maps, entities, location
---


# Question
Title: How to control the display of a user account connected via entity reference
My searches have turned up nothing, I'm sure it is something simple but I can't figure it out.

To give a simple version of my set up: I have a content type for publications, that publication has a paragraph field for authors. That paragraph field accepts either a user linked by entity reference, or a non-user author (a set of text fields). My end goal is to display them in proper order like so:

**Authors:** Staff Author 1, Non-Staff Author 1, Non-Staff Author 2, Staff Author 2, Staff Author 3

Replacing the text there with actual author names. The order needs to be the order in which they were entered, which is the reason I am using paragraphs (I can mix types and keep the order)

Unfortunately the view options for the entity reference that work for the Users seem to be: Entity ID or Rendered Entity. Entity ID just gives me a number (which I'm sure I could then use in a preprocess function to load the user info and display it as desired -- if that is the best approach, please give me some guidance on where to start), Rendered Entity gives me a User Account full display including photo. I only want the name linked.

In How can I change a rendered user display to a combination of fields linking to the user? I got the answer about how to change user links, but how can I get this reference to show as a user link?

# Answer
> 1 votes
> how can I get this reference to show as a user link?

Go to your paragraph bundle and click on manage display. Find your entity reference field and click on the gear icon.

**Note:**

* The label on the left it's the actual field label.
* The label on the right, refers to the fields contents

Check-mark Link label to referenced entity.

---
Tags: 7, users, entities
---


# Question
Title: Remove site name from template using twig function
I try to get rid of the site name which come with the twig expresseion `{{ page.header }}`.

To get further details of that variable I enabled twig debug mode and printed it `{{ kint(page.header) }}`.

It seems that `block--system-branding-block.html.twig` is used within `{{ page.header }}`. At the end of file it shows.

```
{% if site_name %}
   <div class="site-name">
      <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>
    </div>
{% endif %}

```

The question is how to use a twig function to remove that item from `{{ page.header }}`. There is a filter which is called `without` and I already applied it to `page.header|without('site_name')`. But that didnt work.

Additional question, how to establish a connection between the printed variables from `{{ kint(...) }}` and the template file. Iam looking for that specific div which displays the site name but I can't find it in the printed variables from debug in order to remove it.

# Answer
You can remove the block in the block layout.

If you don't want to do it in the ui, you have to look for the block name. This is probably `sitebranding`.

For example to remove the block with the name `sitebranding` from the region `header` in the page template:

```
{{ page.header|without('sitebranding') }}

```

If you are looking for the site name in the kint print out, it is not always possible to find the actual content early in the templates. Often it is processed at a later stage.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How to render views inside page-front.tpl.php?
I have a view named 'Updates' which displays latest article. How to render this view directly in my tpl.php ?

# Answer
```
<?php
print views_embed_view('my_view', 'block_1', $arg1);
?>

```
* replace **view\_name** with your view name
* replace **block\_1** with your machine name
* replace **$arg1** with an argument (if want to manually pass a value to your contextual filter) This is optional, if you're not going to use it, you can delete it.
> 0 votes

# Answer
For this, there are two options that you can use.

1. Make the view as block and assign this block in any region as per your need.
2. You can use views\_embed\_view function.
> 0 votes

---
Tags: views
---


# Question
Title: How to get the value for public:// from the database
I'm in the process of exporting a gallery from Drupal to Wordpress. I'm trying to create an SQL query on the drupal DB that will return to me the URIs of the files. (for automated import on the other side)

This seems like the easiest and non-intrusive way of getting the images. However, at the end I get `public://some_file_name.jpg` type of strings. When I look at the current live site, it's also clear that the value of `public://` is vastly different for different images / galleries.

This is my Query so far:

```
SELECT n.nid, td.description 'category', n.title 'album_title', n.created, img_title.field_photos_title 'img_title', f.uri
FROM bcb_old.node n
  JOIN bcb_old.field_data_field_photos img_title on n.nid = img_title.entity_id
    JOIN bcb_old.taxonomy_index ti on ti.nid = n.nid
    JOIN bcb_old.taxonomy_term_data td on ti.tid = td.tid
    JOIN bcb_old.file_managed f on f.fid = img_title.field_photos_fid
WHERE n.type ='gallery_2'
 AND n.status = 1

```

Can someone point me in the direction of how to translate public:// into either a url? (relative or absolute doesn't matter)

edit: This is not a duplicate of this. I'm asking for a SQL solution. Not a PHP one. I don't want to add code to the live environment and it is not my place to do so. That's why I want a DB only solution.

# Answer
> 0 votes
You can't do that through SQL directly; you will have to use Drupal to generate those paths for you.

Since you seem to be doing this manually (i.e. without an importing tools), and one time only, here's what I would do:

1. Create a new table where you will store formatted information. This table would have `nid`, `category`, `album_title`, `created`, `img_title` and `uri` columns.
2. Install Devel module and then navigate to `/devel/php`.
3. Execute the following code:

```
$results = db_query("SELECT
                      n.nid,
                      td.description 'category',
                      n.title 'album_title',
                      n.created,
                      img_title.field_photos_title 'img_title',
                      f.uri
                    FROM bcb_old.node n
                    JOIN bcb_old.field_data_field_photos img_title on n.nid = img_title.entity_id
                    JOIN bcb_old.taxonomy_index ti on ti.nid = n.nid
                    JOIN bcb_old.taxonomy_term_data td on ti.tid = td.tid
                    JOIN bcb_old.file_managed f on f.fid = img_title.field_photos_fid
                    WHERE
                      n.type ='gallery_2' AND
                      n.status = 1")->fetchAll();
foreach ($results as $result) {
  // Generate the full URL for this file.
  $image_url = file_create_url($result->uri);
  // Insert this in the new table.
  db_insert('YOUR_NEW_TABLE')
    ->fields(array(
      'nid'                => $result->nid,
      'description'        => $result->description,
      'title'              => $result->title,
      'created'            => $result->created,
      'field_photos_title' => $result->field_photos_title,
      'uri'                => $image_url,
    ))
    ->execute();
}

```

Then you can migrate the data from this new table to wherever you need it.

---
Tags: nodes, database
---


title: Change date format in Advanced Forum

text:
# Question
Title: Change date format in Advanced Forum
I have changed date formats in Views and in Drupal core Date settings, but I'm still seeing wrong date format on forum (for example in node where conversation is) at class *.forum-posted-on*.

In template file advanced-forum.myforumtemplate.post.tpl.php:

```
<?php print $date ?>

```

How to change date format?

# Answer
You need to alter the date through `template_preprocess_node()` and `template_preprocess_comment()` in your theme. The first preprocess is used for the forum nodes (initial forum post) and the latter for comments (replies).

Add the following code to your theme's `template.php` file:

```
function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['node']->type=='forum') {
    // Custom date.
    $variables['date'] = format_date($variables['node']->created, 'custom', 'M d Y, H:i:s');
    // Use date format provided by Drupal:
    // $variables['date'] = format_date($variables['node']->created, 'short');
  }
}

function YOUR_THEME_preprocess_comment(&$variables) {
  if ($variables['node']->type=='forum') {
    // Custom date.
    $variables['date'] = format_date($variables['node']->created, 'custom', 'M d Y, H:i:s');
    // Use date format provided by Drupal:
    // $variables['date'] = format_date($variables['node']->created, 'short');
  }
}

```
> 3 votes

---
Tags: 7, datetime, nodes
---


# Question
Title: After saving a new comment How to fetch all comments for a given node?
Is it possible to fetch a list of comments for a given node by using the rule After saving a new comment? After this I would like to change a taxonomy term for a certain comment having a certain term.

# Answer
> 2 votes
If your rule reacts on event `"After saving a new comment"`, add a `Loop` in actions section and select `comment:node:comments` as a selector.

The loop will go through an array of comments from commented node. There you can specify additional actions/conditions that you wish to perform on each comment.

**PS:** You will run in the issue of not being able to modify comment fields via Rules

> "Unable to modify data "field-taxonomy-term": Entity property comments doesn't support writing."

Here is more information about the issue:

---
Tags: taxonomy-terms, rules, comments
---


# Question
Title: How to get country code using Smart IP Module?
How do I get the country code of the current visitor of the site and just simply display it in a block? I am using Smart IP module. I tried following the instructions from the module's page but I think it only points to the IP of the server. Here is my code:

```

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

```

# Answer
Just set some value to "Frequency of user's geolocation checking", clear cache and that's it!

And if you're in a reverse proxy server, don't forget to insert the following in your site's settings.php

```

  // Tell Drupal that we are behind a reverse proxy server
  $conf['reverse_proxy'] = TRUE;

  // List of trusted IPs (IP numbers of our reverse proxies)
  $conf['reverse_proxy_addresses'] = array(
    '127.0.0.1',
  );

```
> 0 votes

---
Tags: 7
---


title: Programmatically create a menu

text:
# Question
Title: Programmatically create a menu
How can I programmatically create a menu? I have 3 different menus I want to create: The first menu will be placed in the top left of the header; the second menu will be placed below the first menu; the third menu will be the main navigation.

# Answer
If you are trying to do this in an update script, this should work:

```
$menus = array(
  array(
    'menu_name' => 'menu_test_one',
    'title' => 'My Menu One',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_two',
    'title' => 'My Menu Two',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_three',
    'title' => 'My Menu Three',
    'description' => 'Lorem Ipsum',
  ),
);

$links = array(
  array(
    array(
      'link_title' => 'Link1',
      'link_path' => 'http://yourdomain.com/link1',
      'menu_name' => 'menu_test_one',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link2',
      'link_path' => 'http://yourdomain.com/link2',
      'menu_name' => 'menu_test_one',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link3',
      'link_path' => 'http://yourdomain.com/link3',
      'menu_name' => 'menu_test_two',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link4',
      'link_path' => 'http://yourdomain.com/link4',
      'menu_name' => 'menu_test_two',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link5',
      'link_path' => 'http://yourdomain.com/link5',
      'menu_name' => 'menu_test_three',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link6',
      'link_path' => 'http://yourdomain.com/link6',
      'menu_name' => 'menu_test_three',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
);

// Save menu group into menu_custom table
foreach ($menus as $menu) {
  // Look the table first if the data does exist
  $exists = db_query("SELECT title FROM {menu_custom} WHERE menu_name=:menu_name", array(':menu_name' => $menu['menu_name']))->fetchField();
  // Save the record if the data does not exist
  if (!$exists) {
    menu_save($menu);
  }
}

$item = '';
foreach ($links as $layer1) {
  foreach ($layer1 as $link) {
    // Build an array of menu link
    $item = array(
      'link_path' => $link['link_path'],
      'link_title' => $link['link_title'],
      'menu_name' => $link['menu_name'],
      'weight' => $link['weight'],
      'expanded' => $link['expanded'],
    );
    // Look the table first if the data does exist
    $exists = db_query("SELECT mlid from {menu_links} WHERE link_title=:link_title AND link_path=:link_path", array(':link_title' =>  $link['link_title'], ':link_path' => $link['link_path']))->fetchField();
    // Save the record if the data does not exist
    if (!$exists) {
      menu_link_save($item);
    }
  }
}

```

Comments are welcome if my approach is wrong. Thanks.
> 25 votes

# Answer
Here's a way to easily populate a menu from an array :

```
<?php
function populate_menu($links, $menu_name, $plid = 0) {
  foreach ($links as $link) {
    $ls = array(
      'menu_name' => $menu_name,
      'link_title' => $link['link_title'],
      'link_path' => $link['link_path'],
      'plid' => $plid,
    );
    $newpid = menu_link_save($ls);
    if (!empty($link['childs'])) {
      populate_menu($link['childs'], $menu_name, $newpid);
    }
  }
}

$items = array(
  array(
    'link_title' => 'Menu1',
    'link_path' => '<front>',
    'childs' => array(
      array(
        'link_title' => 'Sub Item 1',
        'link_path' => '<front>',
        'childs' => array(
          array(
            'link_title' => 'Link item 1',
            'link_path' => '<front>',
          ),
          array(
            'link_title' => 'Link item 2',
            'link_path' => '<front>',
          ),
        ),
      ),
      array(
        'link_title' => 'Sub Item 2',
        'link_path' => '<front>',
        'childs' => array(
          array(
            'link_title' => 'Link item',
            'link_path' => '<front>',
          ),
        ),
      ),
    ),
  ),
);
populate_menu($items, 'main-menu');

```
> 4 votes

# Answer
`hook_menu()` is all you need to implement in you custom module. For creation of custom module, refer to this documentation.

```
//Define the menus in the function which goes in your MYMODULE.module file

function MYMODULE_menu() {
  //the menu which will point to http://yoursite/first-menu
  $items['first-menu'] = array(
    'title' => 'First menu',  // will appear as the name of the link
    // Page callback, etc. need to be added here.
  );

  //the menu which will point to http://yoursite/second-menu
  $items['second-menu'] = array(
    'title' => 'Second menu',  // will appear as the name of the link
    // Page callback, etc. need to be added here.
  );

  //the menu which will point to http://yoursite/third-menu
  $items['third-menu'] = array(
    'title' => 'third menu',  // will appear as the name of the link
    // Page callback, etc. need to be added here.
  );

  return $items;
}

```

You could print the menu in any region by adding the following code to the `page.tpl.php` file of you theme.

```
// Add this line in <div id="header"></div> to print it in header.
<?php
$menu1 = menu_navigation_links('first-menu');
print theme('links__first_menu', array('links' => $menu1));

//Print the second menu right after the first menu.
$menu2 = menu_navigation_links('second-menu');
print theme('links__second_menu', array('links' => $menu1));
?>

```

You don't need to print the third menu because by default it will appear on the navigation menu.

### Note

This is not the best practice for creating a navigation menu and adding it to a page. `hook_menu()` is for creating page callbacks and not for creating navigation menus. Please read Menu system, which explains the differences. I answered this when I had started to learn Drupal and I don't recommend this answer anymore.
> 2 votes

# Answer
You can also try the Menu Import module. It's very cool and easy for menu deployment. You can create menu by hands on your website and use generated JSON. Also you can create nodes for non-existing pages.

Here is example of export script:

```
$menu_name = 'menu-footer-secondary-menu';

// Create menu if doesn't exist.
if (!menu_load($menu_name)) {
  $menu = array(
    'menu_name' => $menu_name,
    'title' => t('Footer secondary menu'),
    'description' => '',
  );
  menu_save($menu);
}

// Import menu links from JSON.
$menu_string = 'Impressum {"url":"node\/1","options":{"attributes":[]}}
Datenschutzbestimmungen {"url":"node\/2","options":{"attributes":[]}}
Nutzungsbedingungen {"url":"node\/3","options":{"attributes":[]}}
';

$options = array(
  //'link_to_content' => TRUE, // Look for existing nodes and link to them.
  'create_content' => TRUE, // Create new content (also if link_to_content not set).
  'remove_menu_items' => TRUE, // Removes current menu items.
  'node_type' => 'page',
  'node_body' => 'Page is in development...',
  'node_author' => 1,
  'node_status' => 1,
);

menu_import_string($menu_string, $menu_name, $options);

```

You can run this script with hook\_update\_N() or Update script processor
> 1 votes

# Answer
For creating a menu block, in your .install file add the following code. (Replace *mymodule* with the module machine name.)

```
function mymodule_enable() {
  $t = get_t();

  if (module_exists('menu')) {
    menu_save(array(
      'menu_name' => 'my-new-menu',
      'title' => $t('My New Menu'),
      'description' => $t('My Menu description'),
    ));
  }
}

function mymodule_uninstall() {
  if (module_exists('menu')) {
    if ($my_menu = menu_load('my-new-menu')) {
     menu_delete($my_menu);
    }
  }
}

```

In the .module file, add this code.

```
function mymodule_menu() {
  return array(
   'mypage' => array(
   'title' => 'My Page',
   'description' => 'My Page description',
   'page callback' => 'my_page_callback_func',
   'page arguments' => array(arg(0)),
   'access arguments' => array('access content'),
   'menu_name' => 'my-new-menu',
   'file' => 'my.new.page.inc',
   'file path' => drupal_get_path('module', 'mymodule') . '/includes',
  ),
 );
}

```
> 0 votes

---
Tags: navigation
---


# Question
Title: Need full Taxonomy URL to be valid else redirect 404
I have two taxonomy term pages with the following details:

1. Term id : 1 , url alias : fruits
2. Term id : 2 , url alias : fruits/apple

When I am typing url `http://www.example.com/fruits/apple` then content related to term id 2 is getting loaded which is correct

But the problem is when I am typing `http://www.example.com/fruits/apple1` which is not a valid url then the content of Term id 1 is getting loaded since it is matching till "fruits". In such scenario I want the site to be getting redirected to a 404 page instead of matching termid of "fruits".

I need the full taxonomy url to be valid or redirect to 404.

I am using views taxonomy term page (Default one which by default remains inactive) where a wild card character is there taxonomy/terms/%.

Please help. I cant find a suitable solution for the same.

# Answer
> 1 votes
If you are using contextual filter, then there is validation criteria in settings of taxonomy term name you have selected.  Then add filter value type as taxonomy term name and add action as page not found.

You will get the result.

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


title: How to override content_type "Article"?

text:
# Question
Title: How to override content_type "Article"?
I want to add some fields (programmatically from my module) to the content\_type "Article".

Is that possible ?

# Answer
> 0 votes
Use hook\_entity\_bundle\_field\_info()

Copying from the api docs

```
function mymodule_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $fields = array();
    $fields['mymodule_text_more'] = BaseFieldDefinition::create('string')
      ->setLabel(t('More text'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedMoreText');
    return $fields;
  }
}

```

---
Tags: nodes, entities
---


title: Drupal 8 RESTful POST 400 Bad Request

text:
# Question
Title: Drupal 8 RESTful POST 400 Bad Request
I'm trying to use the RESTful service for creating a node with Javascript using the script below, but I only receive a 400 (Bad Request) error. I have enabled all the formats and set permissions for authenticated users.

The reports shows the following error:

```
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: No route found for "GET /entity/node": Method Not Allowed (Allow: POST) in Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest() (line 163 of /Applications/MAMP/htdocs/comedinewithme/vendor/symfony/http-kernel/EventListener/RouterListener.php).

```

Do I need to set an authorization in the header? Isn't this what the csrf token is for though? And how should this be formatted? I'm completely lost!

```
function getCsrfToken(callback) {
  jQuery
    .get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

function postNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://example.com/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

var newNode = {
  _links: {
    type: {
      href: 'http://example.com/rest/type/node/article'
    }
  },
  type: {
    target_id: 'article'
  },
  title: {
    value: 'Example node title'
  }
};

getCsrfToken(function (csrfToken) {
  postNode(csrfToken, newNode);
});

```

# Answer
> 1 votes
Figured it out: for the \_links href I was using a relative URL instead of absolute.

---
Tags: 8
---


# Question
Title: Hide Block on Particular Page with Bootstrap
I have a block called 'calendar' that I display on all events pages. events\* such as events/today/, events/all/ etc.

A constraint that I have is that the block must be displayed on all events pages but on one particular page. The block must be hidden when the user is using a mobile device.

My thought process was to simply apply the bootstrap 'hidden-xs' class to the block. But the constraint is not satisfied as it would trigger on all the events pages.

What would be the easiest way to implement this?

Thanks in advance.

# Answer
I used a media query and the node-type-event class generated in the body element to target and hide the views-event-block.

```
@media only screen and (max-width: $screen-md) {
  .node-type--event{
    .views-event-block{
      display: none;
    }
  }
}

```
> 0 votes

# Answer
You can use combination of media query to achieve this.Using media query hide the block under mobile resolutions . For example

```
@media screen and (min-width: 480px) {
.block-class {
    display: none;
  }
}

```
> 0 votes

---
Tags: theming, blocks, hooks, bootstrap-theme
---


# Question
Title: How to loop through comments using the Rules module?
I have created a rule (using the Rules module) using *Rules Event* "After updating existing comment" and some comment fields must be changed.

Loop `node:comments` is used but nothing happens when component is used to change a field (`list_item` is considered as Any entity (parameter) to use it in the component). `node:comments` doesn't work in that case. What can be done?

# Answer
# How to loop through comments using Rules

Have a look at this rule (in Rules export format, you should be able to import it in your own site if you have the Rules UI enabled):

```
{ "rules_change_a_comment_field" : {
    "LABEL" : "Change a comment field",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_update" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "An update to some comment has been discovered ... Some more details about this updated comment:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment body (before) = [comment-unchanged:comment-body:value]\u003Cbr \/\u003E\r\nComment body (after) = [comment:comment-body:value]\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment author (before) = [comment-unchanged:author]\u003Cbr \/\u003E\r\nComment author (after) = [comment:author]\u003Cbr \/\u003E\r\n" } },
      { "LOOP" : {
          "USING" : { "list" : [ "comment-unchanged:node:comments" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "drupal_message" : { "message" : "Now processing comment with cid=[list-item:cid] and body = [list-item:comment-body:value] ..." } },
            { "entity_fetch" : {
                "USING" : { "type" : "comment", "id" : [ "list-item:cid" ] },
                "PROVIDE" : { "entity_fetched" : { "comment_fetched" : "Fetched comment" } }
              }
            },
            { "data_set" : {
                "data" : [ "comment-fetched:author" ],
                "value" : [ "site:current-user" ]
              }
            },
            { "entity_save" : { "data" : [ "comment-fetched" ], "immediate" : "1" } }
          ]
        }
      }
    ]
  }
}

```

In this rule, for the sake of simplicity, I intentionally did not use a Rules Component (I just included my entire Rules logic in a single rule). Here is a summary of what the above rule does:

* Rules Event: After updating an existing comment.
* Rules Actions: Loop over each of the comments, and perform these actions for each of them:
    + ***Show a message on the site*** (just for demo purpose, to know what the rule is processing).
    + ***Fetch entity by id***, to retrieve all data about the comment entity being processed in the loop.
    + ***Set a data value***, to change the author of the comment being processed to the current user (this may seem a bit bizarre, I know, but consider it as just a demo sample, to illustrate you can update EACH comment processed in the loop).
    + ***Save entity***, for the comment entity being processed in the loop. If you don't perform this action, then I'm pretty sure the updated value won't have been saved in the end (which is probably also what you experienced in your ***nothing happens***).

Disclaimer: there may be more refined (optimized) solutions to get such rule to work, but using the above Rules actions (and meaningful variables ...) should help to understand what's happening if you're not experienced enough with Rules (yet).

Attention: be careful if you import the above rule (and leave it active) ... because this rule really works (and will change all comment authors to the last user who updated any comment).

# Plan B

If what's above doesn't help, then something that will help you find the answer to your question, is to have a look at Rules **debugging** ... Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your `node:comments`).

Refer to the (great!) video "Debugging rules configuration" for way more details about these 2 variations.
> 1 votes

---
Tags: rules, comments
---


# Question
Title: Filtering list of nodes with attached views by taxonomy of node
I have a single article (page) which has an attached view thats displays a load of nodes (in a content called 'courses').

These nodes have a term reference field called 'language' which assigns them to a specific language the course is taught in.

Each of these nodes have an attached view which lists a load of related nodes (in this case 'products'), and these are also assigned with the same taxonomy called 'language'.

What i am attempting to do is to list these nodes, with the attached view filtered by the same taxonomy 'language'.

I've attempted to set up the view using contextual filters with the notion of getting the parent nodes id (When filter is not available use taxonomy term id from URL) but this only gets me the id of the top level node. What i'm looking to get is to pass the language tid from each course to its attached view.

I've used hook\_views\_query\_alter to add on the join table for the languages table which i'd like to then fill with the tid from the passed taxonomy term to do the filtering.

Anyone done such a thing? seems pretty straightforward as it feels like i'm doing something in the wrong order (ie its rendering the view before attaching to the node).

# Answer
I would pursue the hook\_views\_query\_alter() way, and using arg(1) and node\_load() to load the node you are viewing and get the 'language' value from the node field. Add that value as a filter for your view programmatically.

Is this enough for you to continue on your own?
> 0 votes

# Answer
Here is my take on this. I am not using the hook\_views\_query\_alter approach and therefore I find @dmsmidt's answer to be closer to the original question. However, this answer solves the problem and avoids using an additional custom module.

Here are the key points of my approach:

* Existing setup: A view is attached to node via DS Dynamic Field and Views content panes. This setup allows to pass contextual arguments to the view. Unfortunately it does not allow to pass the specific value of the "term reference" field that the parent Course node has, to use as filter for the "children" Product nodes. There is a workaround for that from inside the View's configuration (see below).
* View's contextual arguments: The attached view is listing Products and has two contextual arguments:
    + Nid (this is expected to be the parent Course, and will be used to display only the Products that have a relation (entity reference) to the parent Course node).
    + Term (this is the language term, set on Courses and Parents, we want to display only the Products that have the same language term as the given parent Course node).
* DS Dynamic's field configuration: The dynamic field is configured to pass only the current Node's NID as a value to the first contextual argument; the Content: Language Term parameter must be set to "No context"
* Workaround: The view's second contextual filter is configured for the case "When the filter value is NOT available" and it uses PHP Code in the following way:
    1. Retrieves the NID passed from the Dynamic Field's configuration.
    2. Loads the node and retrieves the value of the node's language term TID
    3. Finaly, it returns that value to be used as the language term id

The php code that does the trick is:

```
$n = node_load($view->args[0]);
if( isset($n->field_LANGUAGE_TERM_REFERENCE[LANGUAGE_NONE]) && isset($n->field_LANGUAGE_TERM_REFERENCE[LANGUAGE_NONE][0]['tid']) ) {
  return $n->field_LANGUAGE_TERM_REFERENCE[LANGUAGE_NONE][0]['tid'];
}

```

Node's language property: A tiny remark about your general design: Had you used the core language functionality of drupal, e.g. with Content Translation, you wouldn't even need the PHP workaround inside views, the Course's language is available as an contextual argument parameter in the Dynamic Field's configuration. Then the condition Course:language == Product:language would have been a lot easier to configure in the view.

Finally, a screenshot that shows a view of all Articles (Courses) and their related Pages (Products) filtered by the parent's Course language:
> 0 votes

---
Tags: hooks, views, display-suite
---


# Question
Title: field_attach_form with user picture and user mail?
I'm trying to build a custom "edit profile" page and use a lot the field\_attach\_form function in order to build it :

```
field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'field_user_firstname'));
field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'field_user_lastname'));
field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'field_user_organisation'));

```

I'm trying to insert input for user mail and user picture, but as they are properties and not fields, the following snippet is not working.

```
field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'mail'));

```

Is it possible to insert user's properties form with this function ? or is there another way ?

# Answer
Thanks to kkalaskar i managed to do what I was looking for :

```
function _my_module_edit_profile() {
  global $user;
  $user_entity = user_load($user->uid);
  $var['form'] = drupal_get_form('_my_module_edit_profile_form',$user_entity);
  return render($var['form']);
}

function _my_module_edit_profile_form($form, &$form_state) {
  $account = $form_state['build_info']['args'][0];
  if (!isset($form_state['user'])) {
    $form_state['user'] = $account;
  }
  else {
    $account = $form_state['user'];
  }
  $form['#user'] = $account;
  $form['#user_category'] = 'account';
  user_account_form($form, $form_state);
  $langcode = entity_language('user', $account);
  field_attach_form('user', $account, $form, $form_state, $langcode);

  $form['account']['#access'] = false;
  $form['field_user_initialized']['#access'] = false;

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Done !'),
    '#weight' => 100
  );
  $form['#validate'][] = 'user_profile_form_validate';
  $form['#submit'][] = 'user_profile_form_submit';
  return $form;
}

```
> 0 votes

# Answer
I was working on a similar task; my task was to put the address field into the popup and I used the following code to accomplish it. I looked at modules/user/user.page.inc for it.

```
    function MYMODULE_init() {
         //To avoid user_profile_form_validate function not found
         module_load_include('inc', 'user', 'user.pages');
         } //end init function

        //Custom form for fields
        function MYMODULE_form($form, &$form_state) {

        $form = array();
        global $user;
        $account = user_load($user->uid);

        if (!isset($form_state['user'])) {
            $form_state['user'] = $account;
          }
          else {
            $account = $form_state['user'];
          }

        $form['#user'] = $account;
        user_account_form($form, $form_state);
        // Attach field widgets.
            $langcode = entity_language('user', $account);
            field_attach_form('user', $account, $form, $form_state, $langcode);
        //All fields get attached so removing unnecessary fields.
            unset($form['account']['pass']);
            unset($form['account']['roles']);
 $key = array_search('user_validate_current_pass', form['#validate']);
    if ($key !== FALSE) {
      unset($form['#validate'][$key]);
    }
    // hide the current password fields
    $form['account']['current_pass_required_value']['#access'] = FALSE;
    $form['account']['current_pass']['#access'] = FALSE;

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

          $form['actions']['cancel'] = array(
            '#type' => 'submit',
            '#value' => t('Cancel'),
            '#submit' => array('MYMODULE_form_cancel'),
            '#limit_validation_errors' => array(),
          );
          $form['#validate'][] = 'user_profile_form_validate';
          // Add the final user profile form submit handler.
          $form['#submit'][] = 'user_profile_form_submit';

          return $form;
        }

        // Add function for CANCEL button.
        function MYMODULE_form_cancel(&$form_state) {
        $url = $_GET['destination'] ? $_GET['destination'] : 'choose/your/path';
          drupal_goto($url);
        }

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Why does Rules event 'After updating existing content' not result in 'Create a new comment'?
I've used `Create a new entity` for the Rules event `After updating existing content`, but nothing happens.

Is it a bug?

**Update**:

Here is an export of my rule:

```
{ "rules_update_order" : {
    "LABEL" : "Update Order",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "Something",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : { "value" : "Something", "format" : "filtered_html" } }
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

```

It is a very simple rule. And I have a lot of rules which are easily fired apart from this one.

Some more Debugging information (contained in my Rules Logging):

```
0 ms Rule Update Order fires.
0.873 ms Evaluating the action entity_create.
33.717 ms Unable to create entity comment": Invalid data value given.
          Be sure it matches the required data type and format.
36.05 ms Unable to evaluate action entity_create.
36.099 ms Rule Update Order has fired.

```

# Answer
### Part 1: Understanding the problem

It takes a little time/effort to get used (and become experienced) in using the Rules module.

My experience is that it is rare to find a **bug** in the Rules module. Most of the cases where I experience something in Rules that deviates from what I expected, I can find out what "my" problem is by using **debug**-facilities available for the Rules module.

So within the Rules **settings**, experiment a bit with the debugging facilities that come with the Rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

For more suggestions about Rules debugging, refer to "How can I display the value of a variable inside a condition?"

### Part 2: Examples of creating comments after updating existing content

Sorry to say, but I disagree with this comment that was posted below this answer:

> It seems that it cannot work in this way and it is not possible to create a comment with this event.

Have a look at these answers, which are about questions that are variations of the question here:

### Part 3: Experiment with other text formats

Even though your question doesn't provide any details about the text formats you are using, IMO it could well be that your actual issue is caused by the **`Text format`** that you're using for the comment body: your rule shows you're using `filtered_html`, but you should definitely give it a try to experiment with other text formats, such as `plain_text`.

PS: this answer is about D7 ...
> 2 votes

---
Tags: rules, comments, debugging
---


# Question
Title: Date Popup does not translate date format
I am using date popup for a Italian site. In edit/node when in my\_data\_field I select the date it shows in English format mm/dd/YY and not in dd/mm/YYYY.

Instead if I use the date popup in a exposed filter in the display view works as I expected.

The problem occour only in edit/node .

Can you help me to solve this?

# Answer
Salve!
You only need to configure this in the field's settings, under MORE SETTINGS AND VALUES.

Here is a screenshot that shows that the option you are looking for is available in the drop down list:

Hope this helps.
> 2 votes

---
Tags: entities, datetime, i18n-l10n
---


# Question
Title: How to bulk delete selected content/nodes?
I want to bulk delete data and along with it I need check-box where I should able to "select all" data to delete. I tried the Delete all module, which is helpful to delete all the content, but it's all or nothing.

Sometimes I may not want to delete all the content/nodes. Therefore, I would also like to be able to select which specific content/nodes gets deleted only.

Can anyone help me on this?

# Answer
Using the VBO module as suggested in the prior answer is indeed the way to go, BUT ... if you add the Rules module to that also the possibilities for what you can do are virtually only limited by your own imagination. Read on for more details on that ...

# Step 1: Create a Rules Component

Have a look at this example of a **Rules Component** (in Rules export format):

```
{ "rules_delete_nodes_containing_a_specific_value_in_a_text_field" : {
    "LABEL" : "Delete nodes containing a specific value in a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "text_field_value" : { "label" : "Text Field Value", "type" : "text" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "data_is" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[text-field-value:value]"
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "node" ] } },
      { "drupal_message" : { "message" : "Deleted node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022 (which contained the string \u0022[text-field-value:value]\u0022 in field \u0022field_free_format_text\u0022)." } }
    ]
  }
}

```

Some more details to further explain the above above example:

* This Rules Component will be used in the subsequent step.
* In my case I have a text field with machine name `field_free_format_text`.

Note that I also added the Rules Condition `Entity has field` to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the `Entity has field` condition should be sufficient already.

If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of that field to match the machine name of your field, and then you can simply import this Rules Component in your own environment.

After you did this, you can navigate to `admin/config/workflow/rules/components` in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***Node identifier*** and hit the ***`Execute`*** mode. Depending on the node id you selected (if it has that field, and if the Rules Condition is satisfied), your node will be updated.

After you're confident your rule works perfect for all variations of your nodes, move on to the next step below.

Here is an example of the (2) Drupal messages I got when executing this Rules component for a node with ID = 48, in which I used the string "GetRidOfThisNode":

> * Deleted node with id "48" and title "Demo field\_free\_format\_text replacement" (which contained the string "GetRidOfThisNode" in field "field\_free\_format\_text").
> * Component rule: Delete nodes containing a specific value in a text field has been executed.

Variation of the display of that message could be that you use Rules to create a (similar) log record ...

**Attention**: you always get the 2nd message. But the first one only shows up if you have an actual match ... and hence the update gets performed also.

# Step 2: Let VBO do the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your **nodes** to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

**Attention**: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!
> 1 votes

# Answer
The VBO answers are perfect and are likely what you need but my favoured approach for end users is an entity form with an entity reference field with the "check all" module and rules..

Simply because i can have other fields in the form passed to rules more easily if it's something more complicated than delete. Like moving nodes from one organic group to another for example.

> Updated with more details and an example.

https://www.drupal.org/project/checkall I had to patch it a bit (can't remember which ones right now) and use form alters because it's still a bit glitchy.

https://i.stack.imgur.com/Ikwyv.png This is an entity form (with entity form block) on an admin page for an OG with multiple options that control conditional fields. Enabling "preview" in the entity form settings gives a conformation step like VBO.

The benefit is that you can give users whatever list of actions you want whereas with VBO, I think the parameter for the rules component is an autocomplete and sitewide which wasn't an option for me. The downside is that you can't have a table like VBO so you have to join fields in an entity reference view. In this example, it's the username and email together.

There are benefits to both but this was a great option for node and user management where the admin wouldn't be a part of the groups. I use this set up for OG management, OG content, bulk flagging, allowing privileged users assign other privileged users and moving / deleting regular users.
> 1 votes

# Answer
You can bulk delete stuff using:

### Views Bulk Operations (VBO)

> Views Bulk Operations (VBO) This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

Video Tutorial
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Change content location in node template
My content is normally displayed in a specific region that takes up 75% of the screen width, which is usually desired. However on 'User Profile' pages (and a few others) I want it to take 100% of the width.

I created a user-profile.tpl.php file, which contains the content wrapped in a div that takes up the full screen width using bootstrap like so:

```
<div class="row">
    <div class="col-md-12">
        <?php print render($user_profile); ?>
    </div>
</div>

```

The content is rendered, but it's wrapped in the normal content region that is only 75% of the width. This is a simplified version of the content that is rendered:

```
<div class="col-md-9 content-region">
    <div class="row">
        <div class="col-md-12">
            <?php print render($user_profile); ?>
        </div>
    </div>
</div>

```

# Answer
> 1 votes
you need to change the page-user.tpl.php to be able to remove the class from the content region. see here How can I create page.tpl for user’s profile page?

# Answer
> 1 votes
You could set the classes in hook\_preprocess, and switch them based on if there is sidebar content or not.

Here is an example I do in a theme that I made which accomplishes this:

```
/**
 * Implements template_preprocess_html().
 * @param array $variables
 */
function STARTER_preprocess_html(&$variables) {
  if (!empty($variables['page']['sidebar_first'])) {
    $sidebar_left = $variables['page']['sidebar_first'];
  }

  if (!empty($variables['page']['sidebar_second'])) {
    $sidebar_right = $variables['page']['sidebar_second'];
  }

  // Dynamic sidebars.
  if (!empty($sidebar_left) && !empty($sidebar_right)) {
    $variables['attributes']['class'][] = 'two-sidebars';
  }
  elseif (empty($sidebar_left) && !empty($sidebar_right)) {
    $variables['attributes']['class'][] = 'one-sidebar';
    $variables['attributes']['class'][] = 'sidebar-second';
  }
  elseif (!empty($sidebar_left) && empty($sidebar_right)) {
    $variables['attributes']['class'][] = 'one-sidebar';
    $variables['attributes']['class'][] = 'sidebar-first';
  }
  else {
    $variables['attributes']['class'][] = 'no-sidebars';
  }
}

```

These sidebar classes map back to grid widths in the SCSS, the same could be done with Bootstrap by just throwing in col- classes.

When set as no-sidebars, the grid is full width. You could also add in more classes based on the page type, but I would opt to go this route in case you actually want something on the sidebar in the future on a user profile. You won't have to change any code, it will just react to content being present.

---
Tags: theming, users
---


title: User and Content tracking and analytics

text:
# Question
Title: User and Content tracking and analytics
I have a fairly active Drupal 7 environment and I would like to track and log certain things about my users and their behaviour.

What are some of the approaches people tend to take to this? Ideally I'd love to graph some kpi's for reporting etc.

For example I if wanted to track (and log for comparison) things like:

Number of new users this day/week/month Number of new nodes of 'content type' created this day/week/month Number of new comments this day/week/month Most active users (not just in terms of content created but also number of logins, number of comments etc...)

On a per user basis I love to know things everything I can reasonably find about behaviour.

Danny.

# Answer
> 0 votes
For most part, you can achieve this using contrib modules. Here are some of them:

1. Views will allow you to fetch most of the information in your database and create pages, blocks and subpages.
2. Administration Views will override default admin pages (e.g. `/admin/content/node` and `/admin/people`) and even more importantly, allow you to change the output of those pages.
3. Views Data Export allows you to export information from Views to a variety of formats, from `txt` to `csv`.
4. Google Analytics with custom
5. Messages module. I've used Messages module many times when I needed to track an action of a user somewhere. It integrates with Views and Rules, and in combination with the two you can log most actions on the site.
6. Total Control gives you a central administrative page from where you can manage different sections. It's also coming with certain panes that you might find useful.
7. Panels will allow you to create more complex pages that contain blocks and information in a different layout than what is provided by default in your admin theme (e.g. 3 columns and multiple different rows).
8. Forena reports module allows you to create custom reports from the database.

For additional information, see this response by Pierre Vriens.

Lastly, I just realized that this question might not be really suited for this website as it's opinion based and asks for module suggestions. If that's the case, I guess mods will remove both the question and answer.

---
Tags: nodes
---


title: Add field date to views tpl

text:
# Question
Title: Add field date to views tpl
I had this issue before which I solved: Add field date to node tpl

Now I need to add the date field in the views.tpl.php

Here's the code:

I want to replace "$date-\>node\_created" with the field\_date.

Here's what I know: I can't use $content\['field\_date'\] because the $content array doesn't exist in this template file.

Thank you

# Answer
To know what fields you have available to your View, you can use a custom module, and there you write the following:

```
function hook_views_pre_render(&$view) {
     if($view->name == "YOUR_VIEW_NAME"){
         foreach($view->result as $key => $r){
             echo "<pre>"; print_r($view->result[$key]); echo "</pre>";
     ....
         } // foreach
      } // if view->name
} // function

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Possible to build Relation Type between two specific Content Types?
I have created Content Types: Person, Story, Company, Series, Article, Basic Page, plus other content types in the Node bundle.

I want the Relation Type between Person and Story only (i.e. "is author of", "authored by") but all online instructions I read say that the Relation Type should be between bundles. However, that scope is too wide.

The display page shows Entity Collector Relation Type "is author of" Select an entity "" (is null)

# Answer
> 0 votes
This was a question of interpretation of what I could see. What I couldn't see was that the Relation Type had been created, and I did not know how the "relations" were populated. Watching Johann Falk's screencast another time showed me how to do this.

---
Tags: entities
---


# Question
Title: How can I fix this "syntax error or access violation" error?
I am using the following code, but it throws an error.

```
$query = db_select('sdk_country', 'f');
$query->fields('f', array('id','group'));
$query->condition(array(
  'f.status', 1, '=',
  'f.country_value', 'Afghanistan', '=',
));
$result = $query->execute();

```

The error I get is the following.

> Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near `FROM sdk_country f WHERE (Array IS NULL )` at line 1: `SELECT FROM {sdk_country} f WHERE (Array IS NULL ) ; Array ( )` in retreiveEMEAList() (line 458 of C:\Repository\code\beta\sites\all\modules\nhdp\_register\nhdp\_register.module).

How can I fix this error?

# Answer
> 0 votes
`condition()` doesn't take an array as argument.

You need to replace `$query->condition(array('f.status', 1, '=', 'f.country_value', 'Afghanistan', '='));` with the following lines.

```
// The third argument isn't necessary as `=` is the dafault operator, in this case.
$query->condition('f.status', 1);
$query->condition('f.country_value', 'Afghanistan');

```

The query is using the value of the `status` field, but that isn't added to the list of fields passed to `$query->fields()`.
`group` is a reserved word in MySQL 5.5; it cannot be used as identifier for a table field.

---
Tags: 7, database
---


# Question
Title: How to restrict node access based on viewer use role and node author user role?
I have two Profile2 profile types, and each one automatically applies a specific user role to the user account:

1. Man
2. Woman

All users have the ability to add a specific type of node... let's call it "Event".

Man users should never see other Man-user-created events. They should only see Woman-user-created events

Woman users should never see other Woman-user-created events. They should only see Man-user-created events.

I already have the permissions set up where Man users cannot view other Man user profile pages, and likewise for Woman users. How can I apply that same logic/permission restriction to the content those user types create?

# Answer
> 2 votes
Just tried this in my sandbox. You can do this by using Content Access together with Rules. The configuration would go like this:

* Activate the following modules: Rules, Content Access and Content Access Rules Integrations (a submodule of Content Access)
* On your content type - Event - under Access Control, activate "Enable per content node access control settings"
* Create two new Rules:
    1. For content created by a member of the Men role:
        + Event: After saving new content of type Event
        + Condition: User has role(s), Parameter: `User: [node:author]`, Roles: men
        + Action: Revokes Access to the newly created node for the role men. To do that check all but "women" in the "Role-based access control `settings" > "View any content"` acl group
    2. For content created by a member of the Women role:
        + Event: After saving new content of type Event
        + Condition: User has role(s), Parameter: `User: [node:author]`, Roles: women
        + Action: Revokes Access to the newly created node for the role women. To do that check all but "men" in the "Role-based access control settings" \> "View any content" acl group

Once these Rules are in place, any new content of type Event will have an ACL configuration (per node) that will block members of the same role and allow members of the opposite role to view it. You would probably need to tweak this more to match your goals but this should get you going.

Hope it helps!

# Answer
> 1 votes
Have a look at my answer to the (= ***your*** ...) question about "How to control content access based on value of a List (text) field in user profile?".

Replace the roles in that answer like so:

* Change `Woman` to `NoWomanAllowed`.
* Change `Man` to `NoManAllowed`.

With that you should be close to an answer for your question here.

---
Tags: 7, users
---


# Question
Title: How to create a name-surname structure for taxonomy terms?
I have a content type **book** and it has a taxonomy term reference field: `author`

I want to enter **name** and **surname** separately for each author on **node add/edit** page. Name and surname together will be the taxonomy term.

If I enter John for the name and Smith for the surname the taxonomy term will be John Smith.

I want to display the author name as `surname, name` in somewhere and in some other place I want to display as full name `[name + surname]`.

I know I can add custom fields to taxonomy terms and use the Automatic Entity Label module to combine name and surname for term name but I want to create this structure for node form without editing the taxonomy term on taxonomy term edit page.

I was using a method like this but it is useless for this case.

## How can I create a name-surname structure for taxonomy terms on node form?

---

**Note**: This question is not a duplicate of "How to reference existing term if it exists or create new one if not exist via Inline Entity Form module?" ... even though they use the same image. In this question the main point is how to create a name-surname structure on node form, in the other question "how to combine creating new term and choosing existing one options" is asked.

# Answer
This definitely worked for me:

Inline Entity Form \+ Automatic Entity Label \+ Token.
I added an entity reference field to my content type, pointing to a Taxonomy Term entity and selected "Inline entity form - Single value" as the widget.
What works great is that every time you edit the term from the node edit form, the term's label changes automatigally.

Here are some snapshots.

Add/Edit Node:

Newly created term (vocabulary list):

Node view:

Hope it works for you too!
> 1 votes

---
Tags: 7, entities, taxonomy-terms
---


# Question
Title: Create contextually filtered view of shared fields across multiple content types
I have a content type "Construction Job" with the title field renamed "Job #". When we create a new job, we assign it a unique job number in the title field.

I have two additional content types, "Update team 1" and "Update team 2". These content types have different fields because the work being done is different, but they share a field called "pictures". Each content type also has an entity reference field to the "Construction Job" content type so we can tie them together.

I'm trying to create a dashboard type display with various different views so management can review jobs with all of the information in one location. I'd like to create a slideshow off all of the pictures uploaded from either of the two update content types, and contextually filter that slideshow so that only the images from the updates for that particular "Construction Job" are shown.

I can create a separate slideshow view for the pictures from each respective Update type, but then I'm left with two separate slideshows on the same page. I'm trying to combine this into one slideshow as we're looking at adding a third different Update content type.

I've tried adding a contextual filter for each entity reference field from the two independent content type, but that doesn't work. That is I can create a contextual filter for the entity reference field for the first content type, but the view then eliminates all images from the second update content type. When I add the second contextual filter, the view returns no results when I enter a value in the filter preview.

# Answer
> 0 votes
Thanks for the help.

I found this module, https://www.drupal.org/project/views\_contextual\_filters\_or which worked perfectly.

I added two relationships, one for each entity reference in the respective Update types. I added two contextual filters filtering on the Content NID -\> Provided in URL, each using one of the relationships I created.

With the module installed and activated, there is a check box under Advanced -\> Query Settings. This checkbox modifies the query so all conditional filters are OR instead of AND.

# Answer
> 0 votes
I haven't tried anything exactly like this buts it sounds like it is very possible if you mess with your AND, OR settings. Since they share the same field and that is what you are filtering on there should be no issue with that being your contextual filter.

Look at your regular filters under 'Filter Criteria'. Filter on the content type in an OR group using 'And/Or, Rearrange' (the arrow next to 'Add'). And it should work.

# Answer
> 0 votes
1. That error shouldn't be there so fixing that would be an option.
2. A likely Solution: Install https://www.drupal.org/project/views\_argument\_substitutions Add a "Global: Null" contextual filter and Provide default \> Content ID. Then add regular OR filters using the replacement * * * ! 1 * * * (no spaces) for the entity reference fields.

Advice: Skip the multiple content types and use the conditional fields module to display different fields depending on a taxonomy field. So a taxonomy vocabulary with the terms Update Team 1, Update Team 2 etc.

If you don't want people to be able to choose, you can have an entity reference to a taxonomy and prepopulate and hide it with the url.

In views then, you filter by that term instead of by content type.

I trimmed like 10 content types down to one doing this. Much much easier to manage.

---
Tags: entities, views
---


title: Webform capability issue with Chosen

text:
# Question
Title: Webform capability issue with Chosen
The Chosen module no longer get applied to Webform select fields with the most recent updates to a Drupal Commerce 2.0 site that I am working on. I am using Chosen version 7.x-2.0-beta4+1-dev (part of Commerce Core) and Webform version 7.x-4.0-beta1. After further investigation, I noticed that the library for Chosen is not being loaded on pages with webform selects. I did some research and found the article below suggesting that, "...there is a bug in \[the\] Webform \[Module\] that removes all the #pre\_render callbacks from select elements when used in Webforms..."

https://www.drupal.org/node/2122061\[1\]

Looking through the Webform module's source code I found the following method which should render select components. Although it doesn't appear that anything is missing.

```
/**
* Implements _webform_render_component().
*/
function _webform_render_select($component, $value = NULL, $filter = TRUE)

```

I did come across another post that mentioned CKeditor causing issues, but after updating to 4.4.4 (from 3.6.7) , the results were the same. I have also configured Chosen to apply to ALL select selectors for testing purposes. Has anyone found a solution or work around to this issue?

# Answer
> 0 votes
I had a similar issue with a recent OpenAtrium update (2.50). Apparently Chosen changed how it gets applied to fields, and this caused it to be turned off for select fields. In my case, it was as simple as visiting `admin/structure/types/manage/<content-type>/fields/<field-name>` and setting the option "Apply Chosen to the select fields in this widget?" to "Apply." This is done on a field-by-field basis.

---
Tags: webforms, views
---


# Question
Title: How to add file extensions to list of acceptable in IMCE
I am using Ckeditor editor/IMCE file upload. How do I get to the config settings where I can add more extensions which are accepted?

# Answer
For adding additional **buttons and plug-ins** to add more extra functionalities,just follow these steps:-

1. Go to the **CONFIGURATION** (`admin/config`) option which is displayed on the menu bar.
2. Then select **WYSIWYG PROFILES** which is part of Content Authoring section.
3. For the **three text formats** available (i.e FULL HTML, FILTERED HTML, PLAIN TEXT), configure the **CK EDITOR** for the format you wish to configure for.
4. Then select **EDIT** which is displayed in the operations's section.
5. Go to **BUTTONS AND PLUG-INS** link.
6. **Check the checkboxes** for the functionality you want to enable in your ck editor.
7. **Save** the settings.
> 1 votes

# Answer
Go to **admin/config/content/wysiwyg**. Under the textformat table if CKEditor is choosen on full html for example under the operations column, select edit. And you should see buttons and plugins, and you should find the Imce checkbox listed as one of the last checkboxes
> 1 votes

# Answer
I found this question in trying to add to the list of permitted file extensions for uploaded files using IMCE. Following the accepted answer didn't get me where I needed to go. Instead I had to go to Admin \> Configuration \> Media \> IMCE, then click to edit the profile I needed to adjust (Admin, in my case).

From there (`example.com/admin/config/media/imce/profile/edit/3`), I was able to add to the list under "Permitted file extensions". I hope this helps for other folks who land on this thread.

FYI, I'm using Wysiwyg version 7.x-2.2+63-dev, IMCE Wysiwyg API bridge version 7.x-1.0, and IMCE version 7.x-1.9.
> 0 votes

---
Tags: files
---


title: Dynamic filters based on another filter

text:
# Question
Title: Dynamic filters based on another filter
I am looking to create something similar to this http://www.smartoplug.com/partsearch I need my view to sort based off of multiple parameters. So if you select ford in the make, the models dynamically change to only show models that are referenced in ford i.e. F150, F250 etc.

I've looked into hierarchical select, and simple hierarchical select, but it doesn't look like what i am wanting to accomplish

# Answer
> 0 votes
### Views Dependent Filters

> Allows the presence of exposed filters on a view to be controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.

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