# Question
Title: entity_metadata_wrapper langcode always prints default language
I'm using entity\_metadata\_wrapper with entity translation to print fields in a template, but it always prints the default language when using a langcode in the options.

```
$wrap = entity_metadata_wrapper('node', $node->nid, array('langcode' => 'zh-hans'));
print $wrap->field_main_subtitle->value(); // Returns English value

```

Printing out the $wrap array shows the following towards the end which might give some clue (langcode:protected =\> und):

```
[propertyInfoAltered:protected] =>
    [langcode:protected] => und
    [propertyInfoDefaults:protected] => Array
        (
            [type] => text
            [getter callback] => entity_property_verbatim_get
            [clear] => Array
                (
                )

        )

    [type:protected] => node
    [data:protected] =>
    [info:protected] => Array
        (
            [langcode] => zh-hans
            [type] => node
            [property defaults] => Array
                (
                )

        )

```

Any ideas?

# Answer
> 0 votes
Try this

```
print $wrap->language('zh-hans')->field_main_subtitle->value()

```

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


# Question
Title: How to create a rule to assign roles to users based on some checkbox items in their profile?
I am pretty new to Drupal. I am using Profile2 so that the user can select there own user role. So say I have a profile page with some checkbox items like

* Automotive
* Computer
* Garden
* etc

How would I add a condition or data comparison in Rules to say, If Automotive is selected/checked, set user role to that role? I also need to be able to select multiple checkboxes to get multiple roles.

Any suggestions?

# Answer
> 3 votes
# Part 1 - Make it work for a single selection and related role

Create a rule which looks like so:

1. **Rules Event**: After saving user profile.
2. **Rules Conditions** (both conditions must be satisfied):

* entity has field (with the field corresponding to (eg) "Automotive".
    * data comparison to check if "Automotive is selected/checked".
3. **Rules Action**: : Assign role to user (for the role related to "Automotive").

You could create a similar rule for each possible combination of checkboxes and roles to be assigned. Or continue as detailed in Part 2 to further enhance your rule from Part 1 so that you end up with a single rule for all possible combinations.

# Part 2 - Make it work for other possible combinations

To also make it work for other possible combinations, and because of the fact that a Rules action cannot contain "conditions", you basically have 2 possible approaches:

* Create a similar rule (as in Part 1) for each possible combination.
* Use the Conditional Rules module to enhance the *Rules Action* in the above rule to alter the flow, using either ***Conditional*** (if/else) of ***Switch*** logic. Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

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


# Question
Title: How to put 2 'views' side by side in 1 region using the bootstrap theme?
Is there a way to place 2 separate views (mine in particular are in block), and set them beside in each in a region? I am using the bootstrap subtheme and specifically the content region. I am using drupal 7.

# Answer
> 2 votes
You need to use CSS. Inspect element with your browser, find the div class of the 1st view and use

```
.view-myviewname { float: left; }

```

JS Fiddle Example

# Answer
> 1 votes
You can always use CSS to position things as you see fit. Your views should have specific classes you can target. Alternatively you could always layout your regions accordingly.

---
Tags: views, theming
---


# Question
Title: Hook_menu_alter does not load correct page
I'm trying to check if a user has permission(registered by a module) before he `adds/edits` fields on a node type registered by the module.

The approach is to use hook\_menu\_alter and add an access callback.

The URL i am trying to add this to is

```
admin/structure/types/manage/applx-application/fields

```

Where '`applx-application`' is the node type.

The problem is after the callback has been added via the hook, the page falls to `admin/structure/types/` instead of a`dmin/structure/types/manage/applx-application/fields`

I'm not sure what i'm doing wrong. Oh and `hook_menu_alter` is called by hook\_hook\_info. If that is of any concern.

```
    <?php
/*
    Implements hook_menu_alter
*/
function applx_menu_alter(&$items){
    $items['admin/structure/types/manage/applx-application/fields']['access callback'] = 'applx_permission_check';
    $items['admin/structure/types/manage/applx-application/fields']['access arguments'] = array('field_management');
}

```

My only guess is that it falls back to `structure/types` because the system module's menu hook expects a wildcard in place of **applx-application** i suppose.

What is the right way to do this, if not this way?

# Answer
Digging a little bit more i found out that the right way to do this is to use

hook\_field\_access
> -1 votes

---
Tags: users, routes
---


# Question
Title: How to restrict node authors from commenting on their own nodes?
On my site we have enquiries (nodes) and price quotes (comments). So node authors shouldn't be offered to quote prices to themselves.

That's why I want to disallow node authors comment their own nodes. How can I do so?

Updated: The 'user-compare' option in panels visibility rules could easily allow to achieve what i want. I've used this functionality for other panes i.e. profile fields etc. But i didn't find 'user-compare' entry in Panels visibility rules for comment form in node template. Why?

I chose the way offered by Pierre.Vriens using Rules because I couldn't make the code snippet by oksana-c work with Panels. Unpublishing comments with The Rules is not best user experience. Comment Permissions module also didn't help. Any suggestion for unsetting whole comment form for node authors programmatically in Panels environment would be much appreciated.

# Answer
> 2 votes
You can use the Rules module for this, by creating a rule that looks like so:

* **Rules Event**: After saving a new comment.
* **Rules Condition**: Data comparison like `comment:author` is equal to `comment:node:author`.
* **Rules Action**: Set a data value for `comment:status`, and set it to `unplublished` (which you should be able to do if using the Rules event "After saving a new comment").

Here is the actual Rule I created for it (in *Rules export format*, which you should be able to import in your own site aso, using the Rules UI):

```
{ "rules_unpublish_selected_comments" : {
    "LABEL" : "Unpublish selected comments",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "comment:status" ], "value" : "0" } } ]
  }
}

```

After you imported this rule, you must first "enable" it before it actually becomes active i your own site (alternative: exclude the line with `"ACTIVE" : false,` before importing this rule.

Consider the above as a "template Rule", which with some minor tuning you can also use for all sorts of variations of processing comments via the Rules module ... (eg by using some other Rules Condition).

If you're not familiar with the Rules module, have a look at the video about Rules(Sending Emails) - Comment reply notification which demonstrates how to use the Rule UI to build a rule that is about a variation of this question.

Happy Rules-ing!

PS: No need for custom PHP coding ...

# Answer
> 3 votes
You'd want to use `hook_node_view_alter()` in your theme to unset the comment form if the logged in user is same as node author.

```
function yourtheme_node_view_alter(&$build) {
    global $user;
    // get the uid of logged in user
    $logged_in_uid = $user->uid;

    // if content type is 'your_content_type'
    if ($build['#bundle'] == 'your_content_type') {

        //get node author's uid
        $node_author = $build['#node']->uid;

        // if logged in user is the node author - unset comment form and remove the 'Add comment' links from node display
        if ($node_author == $logged_in_uid) {
            unset($build['comments']['comment_form']);
            unset($build['links']['comment']['#links']['comment-add']);
        }
    }
}

```

Also, you can check out Comment Permissions module. It does not offer the functionality that you need, but it provides more granular permissions than core comment module.

> The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

# Answer
> 0 votes
* Log into the Drupal Dashboard
* Click on Structure from the upper menu bar and then select the Content types category.
* Click Edit next to the name of the content type you wish to edit
* drupal\_global\_comment\_1
* Scroll down and click on Comment settings
* drupal\_global\_comment\_2
* Select Closed from the drop down menu under Default comment setting for new contentdrupal\_global\_comment\_3
* Click the Save content type button at the bottom of the page.

---
Tags: 7, comments
---


# Question
Title: How to validate a file upload field added to a form using hook_form_alter?
I am trying to add a file upload field to all story node forms. I tested the code and I am successfully getting the file upload field on the form.

```
$form['my_file_upload'] = array(
    '#attributes' => array('enctype' => 'multipart/form-data'),
  '#type' => 'file',
  '#title' => t('Image'),
  '#description' => t('Image should be of minimum 50x50px width and should be of type png or jpg'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#size' => 48,
  '#weight' => 4,
);

```

Now the question is How do I validate the file and also how do I retrieve the file after it has passed validation?

(Site runs on Drupal 6)

# Answer
What you describe is what the Upload module does: In upload\_form\_alter() (an implementation of `hook_form_alter()`), it adds the form element to the node edit forms, and in the form submission handler it adds to the form (upload\_node\_form\_submit()), it handles the uploaded files. With \_upload\_file\_limits(), it checks the user didn't reach the assigned quota; with file\_save\_upload(), it checks the file passes the validators, and saves the file.

The Upload module, once enabled, allows you to enable the file upload for the content types. For example, for the Page content type, you can enable it at admin/content/node-type/page.

In the node edit form, the form element the Upload module adds appears as in the following screenshot.

If the Upload module is already enabled, and you need a upload form element more, than you should use the CCK module.
> 1 votes

# Answer
question is already asked here, Custom validation for a form?

but still solving your problem, you can add validate method in form alter .

```
$form[#validate][] = 'function_name_callback';

```

and then you can validate the form submission in that function

```
function function_name_callback($form, $form_state){
//validate here
}

```
> 1 votes

---
Tags: 6, forms
---


title: Get a view field in the edit form

text:
# Question
Title: Get a view field in the edit form
I have a site that I have a form for users that they write down their personnal info's. I did a view, and then I made a field that has this view. Now what I want to do is to see this view field in the user's edit form. I can see all the fields that I want in the user's form but I cannot see the view field.

# Answer
Alter the form using `[hook_form_alter][1]`

```
<?php print views_embed_view('<Your view id>', $display_id = '<display id>'); ?>

```

Make that `display:none;` from CSS.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Can you print single view fields in a block template file?
I am new to drupal and I am wondering how to gain more control over a view block. Currently I am embedding my view block in my page by doing :

```
<?php print views_embed_view('news_overview', $display_id = 'block'); ?>

```

This works but if I want to style this further I have to go into my view and format it as content and add the html templating there which leaves me with a bit less control than I want.

I made a views-view--block.tpl.php file to try and style my view block a bit more but I am left wondering how to render single view fields here.

I tried doing this to for example render a body field:

```
<?php foreach($view->result as $object): ?>
    <?php print render($object->_field_data['nid']['entity']->body['und'][0]['value']); ?>
<?php endforeach; ?>

```

Ofcourse doing this for each field is a hassle and I was wondering if there is an easier way to output view fields inside my **views-view--block.tpl.php** template.

Cheers.

# Answer
The first thing do not use that tpl file(**views-view--block.tpl.php**), this will alter all views of your current system. you can use **views-view--news-overview.tpl.php** this will alter your current views view only, there is many suggestions in **views-\>advanced-\>theme:information**. you can use appropriate tpl file.
> 1 votes

---
Tags: views, theming, blocks
---


# Question
Title: Integrating dropdown menu of different views options on a page
I have one content type called 'images' - at the moment they are just displayed as a list. However I want the users to have some options on how to view those images.

What I have done: I have created 3 different Views that have different slideshow settings

What I need help with: I need to have these 3 options appear automatically when any node from that content type is viewed as a dropdown with label: "View images as:"

**Most importantly the different views need to be generated programmatically using the images on that node and not by creating 3 slideshow for each image page!!!**

# Answer
> 1 votes
there is no option in views to expose any changer for 3 different blocks, one thing you can do is make a drop-down and show/hide views using javascript/jQuery or make single unformatted view and change format using js/css on dropdown change.(you need to make some custom codes.)

---
Tags: 7, views
---


# Question
Title: How I can pre-populate a webform field with the node title and node link?
In some page I have inserted a link "Contact me for info" that links to a webform page. I would that some fields of the webform form are be pre-populated with the node title and node link from the previous page. How I do it?

# Answer
Use the PrePopulate module and Tokens to build dynamic links on your pages. When clicked, the link's content will be entered into those fields automatically.

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

There's an example on the project page.
> 0 votes

# Answer
You could also do this with a little bit of code:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is your webform, you could make it
  // more dynamic by checking the form title or something.
  if ($form_id == 'webform_client_form_1') {
    // Get the information from the previous page, the best option
    // to me seems to pass the node id via a parameter.
    $get = drupal_get_query_parameters();

    if (!empty($get['previous_page'])) {
      // Load the previous page.
      $previous_page = check_plain($get['previous_page']);
      $node = node_load($previous_page);

      // Check if the previous page is a valid node.
      if (!empty($node)) {
        // Enter the default values.
        $form['submitted']['YOUR_TITLE_FIELD']['#default_value'] = $node->title;
        $form['submitted']['YOUR_URL_FIELD']['#default_value'] = 'node/' . $node->nid;
      }
    }
  }
}

```
> 1 votes

---
Tags: webforms, nodes
---


title: Adding Ajax on existing dropdown list

text:
# Question
Title: Adding Ajax on existing dropdown list
I added this code in my template.php

```
function PORTO_SUB_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'rapporto_di_lavoro_node_form') {

    $form['field_livello']['und']['#ajax'] = array(
                                  'callback' => 'my_test_callback',
                                  'wrapper' => 'callback_wrapper',
                                  'progress' => array(
                                    'message' => 'caricamento',
                                    'type' => 'throbber',
                                    ),
                                );        }}

function my_test_callback($form, &$form_state) {
dpm($form_state);
}

```

When I select an item I can see the throbble, but no dpm() message. What's wrong?

As I'm still not modifying fields, I don't need to unset or indicate wrapper, aren’t I?

# Answer
> 0 votes
similar question is here.

Dynamic select list in the form (dependent dropdown)

you can get your solution from here.

---
Tags: ajax, forms
---


title: Drupal 8 node serialization to JSON

text:
# Question
Title: Drupal 8 node serialization to JSON
I am trying to use \Drupal\node\Entity\Node::load($nid) to store a node object in a variable and pass the variable into drupal 8's serialization component or even symphony's serialization methods. All my efforts have resulted in a JSON object that is only encoding the first property of the node which is {"in\_preview":null}.

For example the following callback returns {"in\_preview":null}

```
public function page(){

  $nrm = new \Drupal\Component\Serialization\Json;
  $node = Node::load(2);
  $json = $nrm -> encode($node, 'json');

  return $json;

}

```

What class/method would accomplish serialization of $node in the above code?

# Answer
> 19 votes
You should use the `serializer` service if you want to serialize a Drupal data type (Typed Data API) so that normalization is run properly. This requires enabling the serialization module as pointed out by Alari Truuts, which defines the `serializer` service.

The serialize method is a little confusing as to what the `$context` parameter means. For Drupal Typed Data, it requires the plugin id of the data type (EntityAdapter in this case).

```
$serializer = \Drupal::service('serializer');
$node = Node::load(2);
$data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);

```

---
Tags: 8
---


title: Add class to empty Panels regions

text:
# Question
Title: Add class to empty Panels regions
How can I add a css class (.empty-panel-region) to Panel's regions that don't contain any panes?

# Answer
> 0 votes
The following works with all standard renderers (default/IPE).

There is no preprocess possibility for the regions, so some extra work is needed.

First add the following preprocess function to your template.php of your theme or your own module (change MY\_THEME accordingly).

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MY_THEME_preprocess_panels_pane(&$vars) {
  // Determine if a panels panel (region) is empty.
  // Every pane needs to be checked for content.
  // Set the result on the panels display object.
  if (empty($vars['content']) || (isset($vars['pane']->IPE_empty) && $vars['pane']->IPE_empty)) {
    if (!isset($vars['display']->panel_is_empty[$vars['pane']->panel]) || $vars['display']->panel_is_empty[$vars['pane']->panel] ) {
      $vars['display']->panel_is_empty[$vars['pane']->panel] = TRUE;
    }
  }
  else {
    $vars['display']->panels_is_empty[$vars['pane']->panel] = FALSE;
  }
}

```

Then you can use the data in the $display-\>panel\_is\_empty array in your PANELS-LAYOUT.tpl.php files to conditionally add extra classes. (Change 'PANEL' to the specific region.)

```
<div class="panel-panel <?php print !empty($display->panel_is_empty['PANEL']) ? 'panel-panel-empty' : ''?>">
  <?php print $content['PANEL']; ?>
</div>

```

---
Tags: panels, theming
---


# Question
Title: How do I see the ID of a content type record?
Using Entity Reference, I'm able to create a Field in a Content Type (Person) which references another Content Type (Story). When I go to input link data, I see a list of Title(s) of Story(ies).

How do I know that I have the right story? There are many crime fiction stories with the same title.

Is there a way to expose the Content Type record ID?

# Answer
> 0 votes
When creating your entity reference field there is a "Mode" selection. The default is simple but you can choose to use a Views entity reference display type instead.

So in views if you create a new view (that displays the data you want) and add a entity reference display type to i. You can then use that in your entity reference field.

EDIT: Just seen the comment above referencing Show node IDs along with titles in Entity reference Autocomplete list Do that

---
Tags: entities
---


# Question
Title: Why am I getting a 403 error with this route?
I'd like to apply the admin (or other) theme to user `/user/login` page. Since ThemeKey isn't available I'm attempting to implement via routes. "View admin theme" permission is granted to anonymous.

Using this route:

`my_module_name.user_login:
 path: '/user/login'
 options:
 _custom_theme: 'my_custom_theme'`

gives the correct theme, but a 403 response on the `/user/login` page. Why am I getting a 403 response (with the anticipated theme) instead of the standard login page?

# Answer
Because you don't have any access checks.

If anyone is allowed to access it, you must specify so explicitly with `_access: 'true'` in an access section.
> 4 votes

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


# Question
Title: How do I set a specific image header for each page?
I am trying to have a header with a different image for each page of my site. I believe I should be creating a block. I don't want to create x blocks for x pages, and I prefer to do it programmatically.

So I developped a block using in SubheaderBlock.php.

```
/**
 * Provides a 'SLS Block' Block
 *
 * @Block(
 *   id = "subheader",
 *   admin_label = @Translation("slssubheader"),
 *   category = "custom",
 * )
 */

namespace Drupal\subheader\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class SubheaderBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node) {
      $nid = $node->id();
    }

    return array(
      '#title' => '',
      '#description' => '',
      '#nid' => $nid,
    );
  }
}

```

Then, I can use the node ID in the Twig template and change the picture accordingly. The node ID is well passed to the Twig template, but it is cached! So, whenever the page change, `{{ #nid }}` outputs the same ID.

I have also tried to change Twig template suggestion and have a Twig template for each page, but still there are same caching problem.

The code below is probably not the perfect one.

```
/**
* @file
* Code for the example module.
*/

/**
 * Theme hook
 */
function subheader_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
    $twig = 0;
    // change the suggestion only for the block_id 'subheader'
    if(isset($variables['elements']['#plugin_id'])){
        if  ($variables['elements']['#plugin_id']=== "subheader"){
            // give the twig template the same ID as the NID
            $node = \Drupal::routeMatch()->getParameter('node');
                if ($node) {
                $twig = $node->id();
                }
    // suggestion pattern is 'block__subheaderID
    $suggestions[] = $hook . '__' .'subheader'.$twig;
}}
}

```

A

# Answer
After some many headache... I believe I got what I wanted, thanks to Ivan.

> SubheaderBlock.php

```
<?php
/**
 * Provides a 'Subheader' Block
 *
 * @Block(
 *   id = "slssubheader",
 *   admin_label = @Translation("slssubheader"),
 * )
 */

namespace Drupal\subheader\Plugin\Block;
use Drupal\Core\Block\BlockBase;

class SubheaderBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {

   // get the node id if exist
   $node = \Drupal::routeMatch()->getParameter('node');
   $nid = $node ? $node->id() : 0 ;

   $outpout['id'] = array(
           '#markup' => $nid,
           '#cache'=>[
                 'contexts' => ['url:pager_id' ],
                 ]

       );

    return $outpout;
  }
}
?>

```

I get the id in twig with

```
{{ content.id }}

```

I checked with a a random number rand(1,100) it works perfect. There is one different cache per nid.

althought it works, I am not sure about the best practice for #markup and url:pager\_id
> 0 votes

---
Tags: theming, 8
---


title: Theming custom fields

text:
# Question
Title: Theming custom fields
Migrating from D7 to D8, can someone explain how to theme a custom field in a content type?

Say I start with the "Basic page" content type and I add an image field, however I don't want this image to appear in the body of the text, I want it to span the entire page.

In Drupal 7 I would have gone into /sites/all/themes/mytheme/templates/page.tpl.php and added the following:

```
<?php if(isset($node->field_image_undernav) && count($node->field_image_undernav) > 0):?>
    <?php $imagePath = file_create_url($node->field_image_undernav['und'][0]['uri']); ?>
    <img class="img-responsive" id="img-top" src="<?php print $imagePath;?>"/>
<?php endif; ?>

```

How do I do this in Drupal 8? I'm guessing it's something like /themes/mytheme/page.html.twig and adding:

```
{# Top Image #}
    {% if page.machine_name_of_field %}
       {% block machine_name_of_field %}
         {{ page.machine_name_of_field }}
    {% endblock %}
{% endif %}

```

This changes where I can render the image in the template, but includes unwanted fields (like title) and some DIV wrappers. I just want to locate the image URL.

If I do

```
{{ dump(page.machine_machine_name_of_field) }}

```

I get NULL. If I dump(page), I see the URL but concatenated as part of a string in \["#markup"\]. Any way to extract just the image URL from this field so I can place it exactly where and how I want?

The official D8 theming documentation doesn't seem to have this info, and unofficial guides like John Hannah's is helpful but seems to stop after basic setup.

Any guidance on this specific issue or documentation to learn more is much appreciated.

# Answer
> 1 votes
Berdir set me in the right direction with this question but the actual specifics of what I needed are buried in the replies to this question on rendering images from a node:

in /themes/mytheme/page.html.twig add

`{{ file_url(node.machine_name_of_field.entity.uri.value) }}`

That renders just the image URL so I can place the image anywhere.

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


title: How to use max-age

text:
# Question
Title: How to use max-age
Here's a simple "Hello World" controller. It's working correctly, except for the "max-age" statement. The request returns a Drupal cache hit every time after the first request, rather than just for 5 seconds. I've tried to find a simple example of how to do this but haven't had much luck. If anyone could help, that would be very much appreciated.

```
<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {

  public function content() {

    return array(
      '#type' => 'markup',
      '#markup' => $this->t('Hello, World!'),

      // THIS ISN'T WORKING:
      '#cache' => array("max-age" => 5),
    );
  }
}
?>

```

# Answer
The page cache module doesn't respect max-age. Unfortunate but the problem is that Drupal usually contains elements like forms that are by default set to max-age 0, but that only applies to authenticated users most of the time.

To invalidate the page cache, you need to use cache tags, which you invalidate when something changes.

If that doesn't work, you can try to set the Expires header on the response, but for that you either need to return a Response object or alter it in an event when it has been created.

Note: max-age does work for dynamic page cache (authenticated users), rendered blocks, views, entities and so on. Just not for the anonymous page cache.
> 4 votes

---
Tags: 8, caching
---


# Question
Title: Infinit loop when I 'print_r' variables like $form_state, $form
I don't understand, I want show some vars during my dev. I work on windows and Linux.

On windows, When I use print\_r for show $form or $form\_state (from the hook form\_alter). There isn't any problem, when the page is loaded, I can see the content of theses vars.

But on linux, when I use print\_r, I see the RAM (via top/htop) rise continuously until 4Go and my OS freeze x) The page I request is never loaded.

I don't understand because I don't think have a special configuration. My configuration is recent.

On Linux (Mint)

php -v : 5.6.14 apache2 -v : 2.4.10 (Raspbian)

**Solution**

Activate the sub-extend drupal Kint from the devel package :)

# Answer
You might not like the answer, but it's still true: Don't use print\_r() for $form/$form\_state, entity or other complex objects. It just doesn't work.

Try kint() from the devel module instead, make sure to install the kint submodule too.
> 3 votes

---
Tags: 8
---


# Question
Title: How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc?
How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc...

Is there any easy way to migrate a Drupal 6 Ubercart store to another CMS or shop system?

What would you use instead of Drupal Ubercart?

# Answer
> 1 votes
> 1. **How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc...**

A typical approach to migrate such site to D7 is to use the Migrate module.

> 2. **Is there any easy way to migrate a Drupal 6 Ubercart store to another CMS or shop system?**

Using the Commerce Migrate Ubercart module will pretty sure simplify things. Some details from its project page:

> *Commerce Migrate Ubercart is a migration using Commerce Migrate and the Migrate suite that can migrate 6.x and 7.x Ubercart stores from either the existing Drupal database or an external database on the same machine.*

Since this includes D6 and Ubercart, you should definitely have a look at this module if you go for Drupal Commerce

> 3. **What would you use instead of Drupal Ubercart?**

Going for the Drupal Commerce module is definitely an option you should consider, and the modules mentioned above should help (a lot?) to get you there.

---
Tags: 6, commerce, ubercart, migrations
---


title: Relationship between content types

text:
# Question
Title: Relationship between content types
I have two content types: *Region* and *City*. *Region* nodes include *City* nodes; every *City* node is related to some *Region* node.

How I can create a relationship for this situation? When I create a *Region* node and refer a *City* node in a field, all *City* nodes have its *Region* referencing field set to this *Region* node and vice versa.

# Answer
You can use Corresponding Entity References to achieve this.

Follow these steps:

1. Create two content types: **Region** and **City**.
2. Insert entity reference field: `Cities` in **Region** and `Region` in **City**.
3. Now enable Corresponding Entity References and update its configuration by going on your site: Configuration \>\> System \>\> Corresponding entity references.
4. Check this configuration: **Correspond Region on node(s) of type city with Cities on node(s) of type region.**
5. Now in next tab **Updating existing entities** of entity type: **node**.
> 3 votes

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


title: Custom css only for one content type

text:
# Question
Title: Custom css only for one content type
I want to include custom css only for one content type, is that possible?

# Answer
Assets such as CSS and JavaScript files are added via the asset management system.

There are three types of assets libraries settings & replacements.

What you need is a library asset that will include your CSS files.

Adding assets is done by setting the #attached array in a render array. That way you can *attach* the asset only when the render array is rendered.

Because you do not control the render array of nodes, you will need to implement `hook_page_attachments` and add your library on your specific conditions.

## foo.libraries.yml

```
bar:
  css:
    component:
      css/baz.css: {}

```

## foo.module

```
foo_page_attachments(array &$attachments) {
  if (/*CONDITION*/) {
    $attachments['#attach']['library'][] = 'foo/bar';
  }
}

```
> 1 votes

# Answer
use **node-type-"node-type-machine-name"** class from body, it appears in body, and then apply inherited CSS on child classes or on elements. e.g. if you are using a content type conference use

```
.note-type-conference{
//style
}

```

or

```
.note-type-conference .any-other-child-class{
    //style
    }

```

open your developer console of browser and check body element it contains many unique and specific classes.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How NOT to redirect using the Rules module?
I have a comment form in a panel. The path to the panel is *user/\[uid\].*

When I post a comment I am taken to another page where all the comments are shown *(user/\[uid\]/comments.)* I do not want this, I want to stay on the same *user/\[uid\]* page.

Does anyone know how to do this using the Rules module?

# Answer
> 0 votes
A possible "remedy" for this is to use the Rules module (indeed ...). To do so, have a look at my answer to "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?".

Use the rule included there (within "Option 1"), and apply these changes to it:

* Adapt the regular expression within the "Rules Condition", to make it match your ***(user/\[uid\]/comments.)***.
* Adapt the "no\_access" url to your ***user/\[uid\]***.
* Probably you don't want to display any message, so just remove that "Rules Action".

---
Tags: rules, comments
---


title: Form alter in a specific content type

text:
# Question
Title: Form alter in a specific content type
how can i alter/inject a form in a specific content type. I'm developing a module (product list/shopping cart) to insert a form after the body of a specific content type but right now it's showing up in all the existing content types.

The module was not initially developed by me so i'm having a bit of trouble picking up from where it was left…

Here is the part i think is relevant:

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

  $products = db_select('ftf_product')->fields(NULL, array('pid', 'nid', 'name', 'font_ref', 'description', 'app', 'web', 'desktop',  'avangate_desktop', 'avangate_web', 'avangate_app'))->condition('nid', $form['nid']['#value'], '=');
  $result = $products->execute();
  foreach ($result as $record) {
    $defaults[] = $record;
  }

  if(empty($form_state['num_products'])) {
    $results = $products->countQuery()->execute()->fetchField();
    $form_state['num_products'] = $results;

    if($form_state['num_products']  == 0) {
      $form_state['num_products'] = 1;
    }
  }

  $form['products'] = array(
    '#type' => 'fieldset',
    '#title' => t('<strong>Typeface products</strong>'),
    '#collapsible' => TRUE,
    '#collapsed' => (($defaults[$form_state['num_products']-1]->name && !$_SESSION["collapse_typeface_product"])?TRUE:FALSE),
    '#weight' => 5,
    '#tree' => TRUE,
    '#attributes' => array('class' => array('container-inline')),
    '#prefix' => '<div id="participants"><p> </p>',
    '#suffix' => '</div><p> </p>',
    '#description' => t('<p style="color:grey">Create, edit and delete products here. To add or edit Typeface Price Factors please visit the <a href="/admin/config/content/ftf_pricetable">admin section</a>.</br></br></p>'),
  );

```

# Answer
```
function ftf_product_form_node_form_alter(&$form, $form_state) {

  if($form['#node']->type == 'YOUR_NODE_TYPE'){
    $products = db_select('ftf_product')->fields(NULL, array('pid', 'nid', 'name', 'font_ref', 'description', 'app', 'web', 'desktop',  'avangate_desktop', 'avangate_web', 'avangate_app'))->condition('nid', $form['nid']['#value'], '=');
    $result = $products->execute();
    foreach ($result as $record) {
      $defaults[] = $record;
    }

    if(empty($form_state['num_products'])) {
      $results = $products->countQuery()->execute()->fetchField();
      $form_state['num_products'] = $results;

      if($form_state['num_products']  == 0) {
        $form_state['num_products'] = 1;
      }
    }

    $form['products'] = array(
      '#type' => 'fieldset',
      '#title' => t('<strong>Typeface products</strong>'),
      '#collapsible' => TRUE,
      '#collapsed' => (($defaults[$form_state['num_products']-1]->name && !$_SESSION["collapse_typeface_product"])?TRUE:FALSE),
      '#weight' => 5,
      '#tree' => TRUE,
      '#attributes' => array('class' => array('container-inline')),
      '#prefix' => '<div id="participants"><p> </p>',
      '#suffix' => '</div><p> </p>',
      '#description' => t('<p style="color:grey">Create, edit and delete products here. To add or edit Typeface Price Factors please visit the <a href="/admin/config/content/ftf_pricetable">admin section</a>.</br></br></p>'),
    );
  }
}

```
> 1 votes

# Answer
Since you want to alter only one specific form, hook\_form\_FORM\_ID\_alter is ideal. Replace `FORM_ID` with the `form_id` of your content type (should be something like `machine_name_node_form` \- `print $form_id`). That hook's implementation has the advantage of not being invoked by all forms, but only by the specified form. This is important in terms of performance.

Hope it helps!
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to make the Access by Term module respect User Role permissions first?
I need Access By Term (ABT) to respect the user Role permissions before considering the term relation between the user and the node.

**Scenario** The user does not have permission to edit "Basic Page" content type but he is term related to a "Basic Page" node. He should not have permission to edit this page because his Role doesnt grant it, but as he is related to this node by a term, ABT grants him "update" permission.

Any ideas? Is it possible without patching it?

# Answer
> 0 votes
You are using Access By Term. I've never used this module, but I have used Workbench Access which allows setting of an *Editorial Section* for content and people assigned to those sections to edit that content.

It sounds like you want a complex workflow better supported by Workbench.

# Answer
> 0 votes
Have a look at my answer to "How to make the permissions of a module more granular?", which explains how you can use the Rules module for such kind of permission issues.

IMO this question here can be consider as another "use case" of it.

To also make the sample rule included there for this specific question, you'd probably only have to adapt the actual "url" to be intercepted.

---
Tags: taxonomy-terms, users
---


# Question
Title: Best way to define entity and additional custom logic (CRUD) in module
I want to create a new content type, e.g. company. This company needs an additional field which is a multiple file upload field. When the full node of the content type is displayed, I want to run some code in a controller which reads the uploaded files, executes logic and sends information to the twig template. However I'm unsure how to proceed. As far as I can see there are three options (of which the first isn't really an option):

1. I can create an entity type through the admin interface, and create a new node.html.twig template file, however this lacks the ability to execute custom PHP logic and send the information to twig, as i only have the twig template.
2. I can create a content type in a module and define the fields through the admin. If i understand correctly, this can be done through `drupal generate:entity:content` with the Drupal Console.
3. I can create a module in which I define the content type, and hard-code all the fields. This is less flexible but maybe a stronger option: if something happens with the database I don't have to recreate the structure.

Both option 2 and option 3 can be viable. I've used Symfony2 before and using that I would take option 3, however it seems this option is over-complex in D8. If I understand correct in D8 fields should be defined through the admin interface. And a custom template can be created in the module eventually.

How should i tackle this issue? Which option is best? What is the best way to create a controller, which is used in displaying an entity/content type which is created via the D8 admin interface?

# Answer
> 0 votes
Given that you want to change the formatting of a file field, then I would create a FieldFormatter plugin, which could probably extend FileFormatterBase (or one of its sub classes). This would allow the formatter to be a configurable option for file fields in the Manage Display interface (or as part of a content type configuration YAML that your module provides).

By implementing FormatterInterface::viewElements, you can add to the render array that is returned.

To summarize:

1. Create a field formatter plugin for file fields in a custom module: `drupal generate:plugin:fieldformatter --field-type=file`
2. Create a content type: `drupal generate:entity:bundle --bundle-name=company --bundle-title=Company`
3. Add a multiple-value file field to the content type.
4. Configure the file field to be displayed with your custom field formatter plugin (in Manage Display).

Edit: Added drupal console commands as far as I know them

---
Tags: 8, entities
---


# Question
Title: change RegEx in filter_url for text field
I have nodes with text field containing URLs. The content is imported from XML file. The URLs are converted to links with drupals filter system, which works fine for most of the links but not all. I guess its the regex in filter\_url function, but I can't figure it out.

Example URL:

```
http://example.net/2027/uc1.$b81009?urlappend=%3Bseq=7

```

is converted to

```
<a href="http://example.net/2027/uc1">http://example.net/2027/uc1</a>.$b81009?urlappend=%3Bseq=7

```

I'm not a php expert but I'm trying to fix this issue with a custom module. I copied the function `_filter_url` to mymodule.module, renamed it to `mymodule_filter_url`. Invoking `hook_filter_info_alter(&$info)` I change the process callback:

```
$info['filter_url']['process callback'] = 'mymodule_filter_url';

```

Now I have to find the regex expression, which stops the URL encoding right before the '.$'. I guess it's in one of these lines:

```
$trail = '[a-zA-Z0-9:%_+*~#&\[\]=/;?!\.,-]*[a-zA-Z0-9:%_+*~#&\[\]=/;-]';
$punctuation = '[\.,?!]*?';

```

But here I'm stuck. Can someone help me?

# Answer
I think, I got the answer. I added "\\$" to the $trail RegEx pattern.

```
$trail = '[a-zA-Z0-9:%_+*~#&\[\]=/;?!\.,\-\$]*[a-zA-Z0-9:%_+*~#&\[\]=/;-]';

```

Are there any drawbacks with this solution or is there a better way solving it?
> 0 votes

---
Tags: uri, input-formats
---


title: hook_node_access called more than once

text:
# Question
Title: hook_node_access called more than once
I have this very simple implementation of hook\_node\_access

```
function applx_node_access($node,$op,$account){
    drupal_set_message($node);
}

```

This returns

```
applx_application
forum
article
page
forum

```

And because of this i am not able to proceed further. I'm not sure why it prints the name of all bundles.

# Answer
`$node` contains all the content-type in your application as value. So, you need to set your node access based on the `$node` value.

```
function hook_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if($type == 'forum') {
    //set your permission based on $op value.
  }
}

```
> 6 votes

# Answer
It happens because the first parameter of `hook_node_access()` could be either:

* A string containing the content type of the node
* A node object

It is a string for the content type when a node doesn't exist yet, for example because it is going to be created.

In fact, the first line of `node_node_access()` (the implementation of that hook made from the Node module), is the following one.

```
$type = is_string($node) ? $node : $node->type;

```

Your code needs to check the type of the value passed as first argument, in a similar way.

The hook is invoked multiple times because Drupal is checking what content types should be shown in node/add for the currently logged-in user. In fact, your hook implementation is getting the machine names of the content type defined in that site.

Notice that, in Drupal 8, the first parameter of that hook is always an object implementing the `NodeInterface` interface, so it is not anymore necessary to check the type of the first parameter.
> 5 votes

---
Tags: nodes, hooks
---


# Question
Title: Views: Exposed filter If anonymous. Filter by user field if authenticated
I have created two 'Postal code' (text) fields: one in a content type (Event) and another in the user account. I have also created a view showing Events. Now I would like to do the following:

When a user go to the events view: If the user is anonnymous a exposed filter must be show. If the user is authenticated, show only events with the postal code of the user.

# Answer
> 2 votes
Have you tried the module Views Dependent Filters?

For example, you could create a filter which checks if the user is logged in (or has a postal code) and set a dependency to that filter in your postal code filter.

You could also write some custom code (which might be easier in my opinion):

```
function YOUR_MODULE_form_alter(&$form, $form_state, $form_id) {
  // Get the current logged in user object.
  global $user;

  // Check for the exposed form, you would do good to add
  // some extra checks to make sure you only identify your
  // postal code exposed filter.
  if($form_id == 'views_exposed_form') {
    // Load the full user object.
    $account = user_load($user->uid);

    // Check if the user has a postal code.
    if (!empty($account->field_postal_code[LANGUAGE_NONE][0]['value'])) {
      // Hide the exposed postal code field.
      $form['field_postal_code']['#type'] = 'hidden';
      // Set a default value for the exposed postal code field.
      $form['field_postal_code']['#default_value'] = $account->field_postal_code[LANGUAGE_NONE][0]['value'];
    }
  }
}

```

You might want to apply the filter immediately without needing to submit the form. You could use `hook_views_pre_view` for that:

```
function YOUR_MODULE_views_pre_view(&$view, &$display_id, &$args) {
  global $user;

  if ($view->name == 'your_view') {
    // Do the same user postal code check as above here.

    // Apply the exposed filter.
    $view->exposed_input['field_postal_code'] = $account->field_postal_code[LANGUAGE_NONE][0]['value'];;
  }
}

```

I'm not sure if the hook\_views\_pre\_views part works, though, so you might need to do a little research there.

# Answer
> 1 votes
Just create two views. Have one accessable to anonymous users and the other for logged in users and set the filters appropriately.

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


title: Drupal Filter not working in views?

text:
# Question
Title: Drupal Filter not working in views?
I am trying to filter a development profile in a view where it only shows the developers of the project. I have the filter set on published and only with taxonomy terms "Developers", but the view keeps displaying literally everything published, as if its ignoring the taxonomy filter.

Has anyone ran into this problem and know how to fix it? I am using Drupal 7.

# Answer
> 0 votes
Maybe you can add role. Admin menu --\> People ---\> Permissions --\> Roles

example : "Editor" created

At the views's filter criteria choose: Show campaign for specific roles (field\_bcc\_specific\_user\_roles) and select Is equal to "Editor"

---
Tags: 7, views
---


title: Breadcrumb/block settings

text:
# Question
Title: Breadcrumb/block settings
Should Views (that are setup as a Page) be able to inherit breadcrumbs/block visibility settings? When I create a Views page, set a path, add it to the menu (then adjust it to be a sub-menu of another parent item), when I am on the actual Views page, it looses (in this case) any block settings that should be shown on this page. From the screen shot below, you can see the menu block disappear (as well as the LEAD logo on the lower left side). More odd than that, is whenever I set the View to be added to a menu (as I have done in the Views settings), it doesn't show up (which is why I had to add it to the menu manually). I've gotten it to work with another Views page (the menu link showing up), but the blocks still disappear.

Also, once you click on an individual node, they also loose any type of breadcrumb/block visibility (even though I've set the URL to be the correct breadcrumb /about/faculty-staff/directory/USER\_ID). Any help would be greatly appreciated. Thanks!

Current setup: Drupal 7.5 Views: 3.0-rc1 Menu Block: 2.2

**Screenshot Explanation:**

Directory page (Views page - blocks missing from this page)

Main Faculty & Staff page (parent page)

User Profile view

Views config

Menu list

Menu config

# Answer
To your first problem, the menu disappearing on about/faculty-staff/directory:

* Check how the menu block is configured.
* Check if there is another menu item in another menu that links to this page. It could be that Drupal picks this up and thinks we are in another menu.

(There is a more general solution that I am going to post in another answer)
> 0 votes

# Answer
A generally useful way to fix all of this:

* Use Crumbs to generate the breadcrumbs.
* Use Menupoly instead of Menu block, to have your submenus expand for items that are in the breadcrumb trail, even if the current page itself is not in any menu.

Configure **Crumbs** (7.x-2.\*):

* Visit the configuration at Admin \> Structure \> Crumbs \> Plugin weights,
Make sure the menu plugin for this specific menu is enabled (or some parent plugin wildcard key). If necessary, give this specific menu a higher priority than other menus.
* Go to Admin \> Structure \> Crumbs \> Entity parent \> User,
Set about/faculty-staff/directory as the parent path for users with "staff" role.
* Alternative: Use the "Path alias" plugin, where the parent path is based on the url alias.

Note.
You could also use Easy Breadcrumbs or Breadcrumbs by path to get breadcrumbs based on url alias. This would be equivalent with only having the "url alias" plugin enabled in Crumbs. But it does not do anything else, and it does not support Menupoly.

Define the menu with **Menupoly**:

* Create a custom module
* Implement hook\_menupoly(). See the example module for inspiration.
* Go to Admin \> Structure \> Blocks, and move the newly created menupoly block to the sidebar.

E.g.:

```
/**
 * Implements hook_menupoly()
 */
function MYMODULE_menupoly() {
  return array(
    'sidebar_menu' => array(
      'menu_name' => 'main-menu',
      'expand' => MENUPOLY_EXPAND_ACTIVE,
    ),
  );
}

```

Good luck!
> 0 votes

# Answer
The reason behind disappearing of `block` is still not able to find `region` in pages just like `page.tpl.php`.

**Suggestions:**

1) Create a custom template for `views` page using `theme_preprocess_page` in `template.php`.You have to create `template` using `theme_hook_suggestions` under the condition of `views` page `url`.

2)Assign or create `region` in new `views` page template.

3)Assign your `menu block` in above `region`.

**Note:** You don't need to edit or create any `views` template like `views.tpl.php`.It should be custom just like `page.tpl.php`.

Also `block` visibility settings should be available to `views` page `url`
> 0 votes

---
Tags: views, blocks, 7, breadcrumbs
---


# Question
Title: views exposed form alter hook works with login but not work with out login?
I have created views exposed form for searching title based content and i want to display search results into another page for this i have wrote below code in my custom module,it's working fine with login but can't work with out login please advice.

```
<?php
function module_name_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
 drupal_set_message('Form Hook Called');//just to check that hook is called by drupal
  if($form['#id'] == 'form id here')
  {

    $form['#action'] = base_path().'path';
  }
}

```

Thanks,

# Answer
> 0 votes
Please check your `code` on `search_redirect_permission`.You have to use

`access search_redirect module content` in `user_access` function to display result.You have to use `search` api under anonymus login codition.

**Something like:**

```
if (user_access('access search_redirect module content')) {
  // search results!
 } else {
  // no search results!
 }

```

But I don't understand why you are using `hook_permission()`,if it should be viewed by anonymous users.

**EDIT:** For `form redirect` you should do something like:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{

    if($form_id == 'your_form_id')
    {
      //YOUR SOME LOGIC IF ANY
      $form['#submit'] = array('custom_form_submit_handler');
    }
}

function custom_form_submit_handler($form, $form_state)
{
//YOUR SOME LOGIC IF ANY
   $form_state['redirect'] = 'your_url';
}

```

---
Tags: views
---


title: How can I verify email addresses?

text:
# Question
Title: How can I verify email addresses?
Here is the workflow

1. Users register with a valid email and a password
2. Drupal automatically sends an email to the new registered user
3. The email contains a link to verify the email
4. The email verification is performed

This is similar to email addition and verification of http://drupal.org. I can't find any module for that purpose. Some patches are available on https://www.drupal.org/node/115801. Any way?

# Answer
> 2 votes
That sounds like the core behaviour to: "*Require email verification when a visitor creates an account*"

However, the password will be selected after clicking the email verification link, to activate the account.

---
Tags: 8, users, emails
---


# Question
Title: Database error when upgrading from Drupal 6.37 to Drupal 7.41
I have updated my site from Drupal 6.21 to 6.37 and it worked fine. Now I am trying to upgrade it to Drupal 7.41. I have changed the core as per the instructions that we follow for upgrading, but there is a database error I am seeing and don't know how can we fix it. I have googled and there were few threads asking to manually increasing the field size https://www.drupal.org/node/1133024 but it doesn't helped much and shows the same error again.

How can I fix this error?

# Answer
> 1 votes
## Heading ##I see this post is a few days old, hope you are still watching.

What is happening is that the update is trying to 're-shape' the type field in the system table, to look like this in D7:

`type | character varying(12) | not null default ''::character varying` However in D6 the field looked like this:

`type | character varying(255) | not null default ''::character varyin
g`

Now you have old content in that field that is longer than 12 and would be truncated and therefore the ALTER TABLE command fails. Now, this is what I would call a messed up update system.

I think there are several options to fix this.

First make a backup of your system table.

Then open a database connection to your drupal database and check what the longest entry will be. I am assuming you are using Postgres:

`select (length(type)), type from system group by type;
 length | type
--------+--------
 5 | theme
 6 | module`

That is my output, now you can check which entry is longer than 12 characters, and see if it contained any useful data.

Now, the easiest way is probably to simply do the field truncations yourself:

`ALTER TABLE system ALTER COLUMN type TYPE VARCHAR(12) USING SUBSTR(type, 1, 12)`

Then attempt the migration again, you still have your backup should this go wrong.

Second option depends on if you need these defined types, possibly they can simply be deleted:

`select type from system where length(type) > 12;` Turn this into a delete statement if you will.

Third option is possible if no code will rely on the field size being 12.

The code for the db update is in modules/system/system.install line 2112:

```
function system_update_7018() {
  db_drop_index('system', 'modules');
  db_drop_index('system', 'type_name');
  db_change_field('system', 'type', 'type', array('type' => 'varchar', 'length' => 12, 'not null' => TRUE, 'default' => ''));
  db_add_index('system', 'type_name', array('type', 'name'));
}

```

change length =\> 12 to the maximum desired length, and run the dbupdate again.

I can't say which consequences each of the approaches will have and each can possibly cause follow-up errors and break other stuff, so you should try them all.

Hint: use drush for the updates, there will be a lot of repetitive tasks, roll-back-update-roll-back-update.

---
Tags: 7, upgrading
---


title: drop-down menu not working anymore

text:
# Question
Title: drop-down menu not working anymore
The Drop-Down menu on a site I manage has stopped working. The link is here: http://www.lslib.com/ I suspect it might be a jQuery issue but I have installed the `jQuery Update` module but it still does not seem to work. Any hints on what I may be missing or what needs to be fixed?

Thank you!

I see something like this in my html:

```
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
window.jQuery || document.write("<script src='/sites/all/modules/jquery_update/replace/jquery/1.10/jquery.min.js'>\x3C/script>")
//--><!]]>
</script>
<script type="text/javascript" src="http://www.lslib.com/misc/jquery.once.js?v=1.2"></script>

```

and I imagine a browser might take jquery 1.2 instead on 1.10. I could npt find which template `<script type="text/javascript" src="http://www.lslib.com/misc/jquery.once.js?v=1.2"></script>` is coming from. How can I remove this?

# Answer
Looks like you are getting a javascript error in your superfish.js file.

```
Uncaught TypeError: Cannot read property 'msie' of undefined

```

The $.browser method has been removed as of jQuery 1.9.

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

As stated in the Upgrade Guide you can try using the jQuery Migrate plugin to restore this functionality and let jQuery Tools work or you can use an earlier version of jQuery for your site (1.8 for example)
> 2 votes

---
Tags: javascript, navigation
---


# Question
Title: Add multichoice question to quiz node programmatically
I'm using the latest version of drupal and quiz module. In my custom module, I have created a quiz by using below code

```
 $quiz = new stdClass();
  $quiz->title = 'Testing Quiz';
  $quiz->type = 'quiz';
  $quiz->language = LANGUAGE_NONE;
  $quiz->uid = 1;
  $quiz->status = 1;
  node_object_prepare($quiz);
  $quiz = node_submit($quiz);
  node_save($quiz);

```

However, the quiz is created successfully. I have a list of multichoice question, which is imported using feeds module. Now what I want is assign those multichoice question to this custom quiz node.

How can I do this?

# Answer
> 1 votes
Finally, I got the solution. The below code is used to add the multichoice question node to quiz node.

```
  $multichoice_node = node_load($nid); //load multichoice question nid
  $multichoice_node->add_directly = array(
    'latest' => array(
      $quiz->nid. '-'. $quiz->vid => $quiz->nid. '-'. $quiz->vid
    )
  );
  node_save($multichoice_node);

```

---
Tags: hooks, quiz
---


# Question
Title: How to control content access based on value of a List (text) field in user profile?
When my users sign up, they must choose whether they are a Man or a Woman, via a List (text) field. If a user chooses "Man", they should only be able to see Woman users on the site. Likewise, if a user chooses "Woman", they should only be able to see Man users on the site. The users cannot edit the value of this field once it is set. The user is assigned a custom user role (man or woman) when they sign up, based on what they choose from that field.

I am also open to using Profile2 with two Profile types (man and woman), but I would still need a method to restrict one profile type from viewing other users of that same profile type.

How can I set up a permission that will allow this type of access restriction? I have not been able to find a solution to solve this scenario.

# Answer
> 0 votes
Check taxonomy\_permissions (I think will do in combination with role assignment and has a stable release too), term\_access module, Access by Term

# Answer
> 0 votes
I finally found a module that does the job: drupal.org/project/view\_profiles\_perms.

> This module provides permissions to view user profiles depending on what roles the profile requested to be viewed has.

# Answer
> 0 votes
As an "alternative" to the View profiles permissions module you've found yourself, you could also use the Rules module for this, as explained below.

# Part 1: Create a 1st rule to assign role "Woman"

1. **Rules Event**: after a new user account is created
2. **Rules Conditions**:

Check the value specified for your selection list (=`Man` or `Woman`), using these conditions:

(a) Entity has field (related to that selection list field), to make that field available to test its value. (b) Perform a data comparison, to check if the value selected was `Woman`.

Refer to my answer to "How to specify a Rules condition related to select list values?" which includes a similar set of Rules conditions (though for entity "node" instead of "user" as you would need here).
3. **Rules Action**: grant the role "Woman".

# Part 2: Create a 2nd rule to assign role "Man"

This is similar to what's detailed in Part 1 (use "Man" instead of "Woman").

# Part 3: Optionally combine both rules in a single rule

The reason why you'd need 2 rules as detailed above, is that Rules does not allow to add "Rules Conditions" within the "Rules Actions". To get around that, you may want to use the Conditional Rules module using either ***Conditional*** (if/else) or ***Switch*** logic. For more details on that, refer to my answer to "How to access rules condition values in the rule event?".

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

# Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

**PS**: One of the advantages of using the Rules module, is that you can probably (actually: pretty sure) use it for lots of other features to implement in your site (which helps to avoid your site suffering "*modulitis*", aka "*way too much contributed modules that slows down a site*").

---
Tags: 7, users
---


title: drush migrate-manifest not found

text:
# Question
Title: drush migrate-manifest not found
I'm trying to migrate a D7 site to D8 following this tut: http://www.metaltoad.com/blog/migrating-taxonomy-drupal-7-to-drupal-8

When I run

`drush migrate-manifest manifest.yml --legacy-db-url=mysql://{dbuser}:{dbpass}@localhost/{dbname}`

I get the error:

The drush command 'migrate-manifest' could not be found.

I'm using drush version 8.0-dev. Installed via composer. I also tried version 7.\* and got the same message plus "Drush 7.0.0 does not support Drupal 8." What gives?

# Answer
Now this has been moved to Migrate Manifest module. You can enable this module and use drush migrate-manifest command.
> 3 votes

# Answer
Seems the Drush command was moved to the `migrate_tools` module - which is part of `migrate_plus` (can be downloaded from https://www.drupal.org/project/migrate\_plus). Use Drush master branch (suitable for Drupal 8) and download migrate\_tools the module and you will be able to call the migrate-manifest command.
> 2 votes

---
Tags: drush, migrations
---


# Question
Title: How to alter the output of a file-field as a custom field-widget
I am implementing a custom field-widget for the file-field in Drupal 8.

I extended the `FileWidget` class as my widget uses most of the file-field-widget functionality.

There is just a small part I want to theme/customize from the file upload form, the part I marked in the following screenshot:

What is the best way to alter the output from a field-widget?

I want to add some surrounding container elements and similar things you do in a theme function.

# Answer
> 1 votes
The file field for uploading is defined in the render callback of `ManagedFile`:

```
public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
  ...

  // The file upload field itself.
  $element['upload'] = [
    '#name' => 'files[' . $parents_prefix . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#multiple' => $element['#multiple'],
    '#theme_wrappers' => [],
    '#weight' => -10,
    '#error_no_message' => TRUE,
  ];

```

So one way to change the output of the field is to define a custom form element which extends `File`. The element can be themed as wanted.

And in the process callback of the custom widget the type of the upload element can be overwritten to use the newly defined element:

```
public static function process($element, FormStateInterface $form_state, $form) {
  $element = parent::process($element, $form_state, $form);
  $element['upload']['#type'] = 'myCustomFileElement';
  return $element;
}

```

# Answer
> 0 votes
To add custom html wrapper around, you should use drupal form API #prefix and #suffix attribute to form element.

For example:

```
function HOOK_form_FORM_ID_alter(&$form, &$form_state, $form_id){
  $form['field_my_field']['#prefix'] = '<div class="the-custom-class">';
  $form['field_my_field']['#suffix'] = '<img width="32" height="32" src="http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/matte-blue-and-white-square-icons-alphanumeric/116590-matte-blue-and-white-square-icon-alphanumeric-plus-sign.png"></div>';
}

```

Here you need to replace HOOK with your custom module name,and FORM\_ID with id of form.

Hope it will help.

---
Tags: 8, forms
---


# Question
Title: How to restore private file structure after major version update?
After a Drupal 6 to 7 update we are unable to use private image download, symptom is we cannot access private files via system/files, while public files can be loaded.

Trying to download private file results in a 404 -- Not found error, sent from the web-server directly, not drupal. After some changes to the configuration this results instead in a Drupal Error page. The server log says

`File does not exist: /home/licebase/drupal/system/files/genefinding_diagram_1_2.png, referer: https://myhost/node/761470/edit?render=overlay`

The system file exists and has the correct permissions.

**Centos 6 on virtualization host, PHP 5.3.3, Postgres 8.4 on dedicated DB server, Apache 2.2.15 (centos) + a lot of active modules + fields+cck**

# Answer
Edit: We have a workaround, I hope this question can serve as a good practice guide of good to debug complex software like Drupal showing unexplainable errors or WSOD. Wish we had followed our own advice to not waste time on our futile attempts time.

tl;dr It was the core module **Database logging 7.42 Logs and records system events to the database.** which is interfering with private files in our specific setting. We disabled most modules including core, and brought them back one-by one. Database logging is reproducibly inducing the error on activation.

1. Don't panic and make a debugging plan, listing options of what could be checked, and then stick to it until everything has been checked. If out of options, try to shake things up
2. Compare your system to a vanilla system and note down what is does differently
3. Modules might interfere with each other in unexpected ways or with your specific configuration. That doesn't mean there is a bug in any of those modules. Boil down your system to the least complex configuration possible, remove any unneeded entry in your configuration file, disable any module that can be disabled including core modules, suspect everyone.
4. Check if error still present, if not re-enable all modules one-by-one, and note down which configuration change causes the error. Otherwise, start debugging going to 1.

## Cheers
> 1 votes

---
Tags: files
---


# Question
Title: Output the "Body" field with markup using Views PHP to be used in Views Datasource (JSON)
We are creating an API using Views/Views Datasource and we want to output the Body field with markup already in the field not plain text. How can we do this? This Views\_PHP approach just outputs the standard Body field as text.

```
$nid = $row->nid;
$node = node_load($nid);
$display = array('type' => 'ugc');
$output = field_view_field('node', $node, 'body', $display);
print render($output);

```

On the example below the @papermill should be a link if this was rendered on the front end.

# Answer
No need for Views PHP, in the settings for my JSON putout it ticks Plaintext output by default!

UPDATE: this does answer the question but we can no longer render our REACTJS App on the front end because i presume of some kind of encoding issue with some characters inside the Body field?
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to check with the Rules module if a user has a custom picture?
I'm using the Rules module, and I have a rule with these Rules Events:

* After saving a new user account
* After updating an existing user account

Within the Rules Conditions, I try to put "Data value is empty" -\> account: (I don't found "picture", "image" or any of this)

I have: admin/config/people/accounts user images \[check\]

Any idea how I can check if the user has used a custom image?

# Answer
> 3 votes
Here's what I did, using a quick custom module to define and evaluate the condition that a user has uploaded a custom image to the core-provided Picture in the user account.

Module name: mymodule

This goes in mymodule.rules.inc:

```
/**
 * Implements hook_rules_condition_info()
 */
function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_user_has_picture' => array(
      'label' => t('User has picture'),
      'parameter' => array(
        'account' => array(
          'type' => 'user',
          'label' => t('User account')
        ),
      ),
      'group' => 'User',
    ),
  );
}

/**
 * Evaluates condition user_has_picture
 */
function mymodule_condition_user_has_picture($account) {
  if ($account->picture == NULL) {
    return false;
  } else {
    return true;
  }
}

```

Note that I've chosen to make the condition positive (returns TRUE if picture is found). If you want the condition to return true when the picture is NOT found, use the Negate option found in Rules.

# Answer
> 0 votes
Another variation for such Rules **Condition** (to "*check if the user has used a custom image*"), is to use the technique illustrated in the Community documentation within "Create a Rule to Evaluate If a Logged-in User Has Created Content of Type X". Here is the relevant part of it:

> (*Bullet 3.*) Select the **condition** to add: "*PHP \> Execute custom PHP code*".
>
> (*Bullet 4.*) On the Add a new condition page, in the PHP code, Value field, enter ... In this code, the SQL query checks the database for ...

So with that, you've reduced the question to writing the appropriate SQL within that custom PHP code, and ensure the code returns true or false depending on the query result.

---
Tags: rules
---


# Question
Title: How do you return an entity property of 'type' => 'struct'
I am using Drupal 7.x and have a created a custom entity. I am using the Entity API module to extend EntityDefaultMetadataController and override public function entityPropertyInfo() to add properties for displaying when my entity is viewed.

More information on hook\_property\_entity\_info:

http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.api.php/function/hook\_entity\_property\_info/7

I understand how to return different types of properties such as 'text', 'int', 'list', 'entity', and so on, using callbacks. However, I have not been able to successfully return a type of 'struct'. My field is always empty when I try to display it.

Example code:

```
  $info['properties']['my-structure_property'] = array(
  'label' => t('My Structure Property'),
  'type' => 'struct',
  'getter callback' => ?  // What should this return?
  'property info' => array(
    'sub_field1' => array(
      'type' => 'text',
      'label' => t('Subfield 1'),
      'getter callback' => 'entity_metadata_sub_field1_property_get', // Returns a text field
    ),
    'sub_field2' => array(
      'type' => 'entity',
      'label' => t('Subfield 1'),
      'getter callback' => 'entity_metadata_sub_field2_property_get', // Returns an entity
    ),
  ),
);

```

What should I be returning in my callback? I have tried returning an object, an array...?

# Answer
> 0 votes
Based on entity\_metadata\_node\_entity\_property\_info\_alter() and entity\_property\_text\_formatted\_info(), I suppose the getter callback should be the most generic callback the entity API offers: `entity_property_verbatim_get`.

This should allow you to access the properties as: `$custom_entity->structure_property->sub_field1`

---
Tags: entities
---


# Question
Title: Displaying Profile2 edit page with Panels
I have a profile2 edit page (Drupal 7) found at user/\*/edit/main. It has several fields that the user can edit.

As it stands, all the fields are displayed one on top of the other in one column and that makes a rather long list and lots of scrolling.

I would like to list those fields in an (imaginary) table or grid of 2 or 3 columns.

I tried Display Suite, but it's not compatible.

I am trying Panels but I can't get it to work. I use the user profile template of Page Manager (/user/%user.) The variant's selection rule is Path: user/\*/edit/main, no context and the "Profile2 from user" relationship.

I have found all my fields and I have organized them in two columns (2 regions side by side) in the panel content.

The variant is enabled but it doesn't work. There is no change whatsoever when I visit the page (all fields still listed in one column.)

Am I doing something wrong or is Profile2 not compatible with Panels (like with Display Suite?)

Any and all suggestions or workaround would be greatly appreciated.

Thanks. :)

# Answer
> 1 votes
I guess panel and display suite both dont provide this use case. you could use hook\_theme and then render function. Example code

```
   function modulename_theme(){

        return array
        (
                    'user_profile_form' => array
            (
                'render element' => 'form'
            ),
        );
    }
function theme_user_register_form($variables){
    $form = $variables['form'];
    $output='<div id="other-side">';
    if(isset($form['profile_main'])){
     $output.= drupal_render($form['profile_main']['field_profile_main_fname']);
     $output.=  drupal_render($form['profile_main']['field_profile_main_lname']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_phone']);

}
    $output.="</div>";
$output='<div id="right-side">';
if(isset($form['profile_main'])){
    $output.= drupal_render( $form['profile_main']['field_profile_main_gender']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_dob']);
 }
}
    $output.="</div>";
    $output.= drupal_render_children( $form);
    return $output;
}

```

Then on css you could add float left and width on divs to make it 2 columns

# Answer
> 0 votes
Have you checked https://www.drupal.org/project/profile2\_panels? It claims to do exactly what you need

---
Tags: panels, users
---


title: Change teaser template based on a field

text:
# Question
Title: Change teaser template based on a field
I have a drop down in my article content type which lets the user select which teaser template to use for that article.

I'm trying to change the template in `themename_preprocess_node()`, since this is where I know what template is assigned to that specific article.

My problem is that I am struggling to specify which twig template to render.

How can I achieve what I am trying to do?

# Answer
You can't change the template in preprocess, there's a separate hook for that, `hook_theme_suggestions_template()`

This is what node is doing for the node template:

```
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function node_theme_suggestions_node(array $variables) {
  $suggestions = array();
  $node = $variables['elements']['#node'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'node__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->bundle();
  $suggestions[] = 'node__' . $node->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->id();
  $suggestions[] = 'node__' . $node->id() . '__' . $sanitized_view_mode;

  return $suggestions;
}

```

You can provide something similar. Note that when you do this in a template, you have to use the alter hook, like this example from the bartik theme:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 */
function bartik_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $suggestions[] = 'form__search_block_form';
  }
}

```
> 3 votes

# Answer
This is how I ended up adding a theme suggestion based on a field (`field_teaser_template`) from the article.

```
  /**
   * Implements hook_theme_suggestions_HOOK_alter() for node templates.
   */
  function themename_theme_suggestions_node_alter(array &$suggestions, array $vars) {
    $node = $vars['elements']['#node'];

    if ($node->hasField('field_teaser_template') && $node->field_teaser_template->value) {
      $template_name = $node->field_teaser_template->value;
      $suggestions[] = 'node__teaser__' . $template_name;
    }
    return $suggestions;
  }

```
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How to use composer for module dependency?
I installed Drupal 8, and for the Panels module, I had to install the following other modules manually:

* Page Manager
* Layout
* Chaos tools suite

Can we use composer to install modules with their dependencies?

# Answer
See this composer template for Drupal project for an example of how this works. Usage:

```
composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction

```

With `composer require ...` you can download new dependencies to your installation.

```
cd some-dir
composer require drupal/devel:~1.0

```
> 2 votes

# Answer
Yes, you can. I just set this up today; it took about two hours. Here are my notes.

This blog post explains the basics. And this post explains about patching.

In short, this is what you need to do for the **composer.json** in your drupal root:

Add these lines to use Drupal Packagist:

```
  "repositories": [
    {
      "type": "composer",
      "url": "https://packagist.drupal-composer.org"
    }
  ],

```

Under `"require"`, add your modules:

```
  "require": {
    "drupal/address": "8.1.0-beta2",
    "drupal/advagg": "8.2.0-beta2",
    "drupal/cloudflare": "8.1.0-alpha1",
    "drupal/commerce": "8.2.0-alpha2",
    "drupal/email_registration": "8.1.*@dev",

```

For how to specify versions, see the Drupal Packagist page.

If you will be using module patches, you also need to add the patch library under `"require"`:

```
"cweagans/composer-patches": "~1.0",

```

And specify the patches under `"extra"` like this:

```
"patches": {
  "drupal/smtp": {
    "Does not set as default system on enable" : "https://www.drupal.org/files/issues/smtp-enabling_module_does-2651976-19.patch",
    "Remove install config" : "https://www.drupal.org/files/issues/remove_install-2651434-2.patch"
  }
}

```

Then run:

```
composer update

```

But, you might get a ton of errors about it not being able to handle drupal core. This happens if a module depends on core. To fix this, at the top of composer.json, add the Drupal core version number like this:

```
  "version": "8.0.3",

```

Don't forget to update this number when you update core.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: How Can I display values of variables in a "PHP contextual filter code" to debug my code?
I have to use PHP code in contextual filter code in a "Arguments/Contextual Filters" of a view:

```
global $user;
$uid=$user->uid;

$pid=db_query("select pid from profile where uid='$uid';")->fetchField();

$equipo=db_query("select field_equipo_proyecto_target_id from field_data_field_equipo_proyecto where entity_id='$uid';")->fetchField();

$num_equipo=db_query("select field_num_equipo_proyecto_value from field_data_field_num_equipo_proyecto where entity_id='$equipo';")->fetchField();;

printf("%02d",intval($num_equipo));
return sprintf("%02d",intval($num_equipo));

```

I think I have some error because I can´t get a correct value. I would like to know how display variables such as `$num_equipo`, etc to debug my code easier.

# Answer
> 2 votes
To expand on what Adrian offered, I would add the Devel Debug Log module. I had a similar problem trying to debug code that ran from a rule, and, I found it easy to write the contents of variables to the log. I then went to **Reports \> Debug Messages** and see what I needed to debug my code. The Debug Log module provides a *ddl($message)* function that is easy to use.

# Answer
> 2 votes
Install the Devel module with the Search Krumo module and you will be able to use the `dpm()` function.

> Devel
>
> * Helper functions for Drupal developers and inquisitive admins.
> * Enable the included Kint submodule as for pretty print of variables. kint($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug\_backtrace() is offerred.

You can read how to use the Devel module at: Debugging Drupal (a page which gives a brief overview of some of the tools you can use to make Drupal development and debugging easier).

---
Tags: 7, views, debugging
---


title: Customized View

text:
# Question
Title: Customized View
I am a beginner in Drupal, I am creating "view" for content type and i want to customize it as follows;

* Title background to be colored (shaded)
* Read More (which leads to original content path)

Can you help me ?

# Answer
For the title, you will need to style it by applying CSS to the appropriate class. See, for instance: https://www.drupal.org/node/2083339

The "Read More" link can be configured through the "More link", in the "Pager" section:
> 1 votes

---
Tags: views, entities, uri
---


# Question
Title: How to migrate from Commerce Kickstart to Drupal Commerce?
What’s the recommended way to migrate users, orders, products including products variation... simply everything to Drupal Commerce 7?

# Answer
> 1 votes
**tl;dr - Essentially, you're building a new theme on top of a site that is populated with content:**

> 1. Find or create a new sub-theme (that doesn't use omega\_kickstart as a parent).
> 2. Create a new home page.
> 3. Create new blocks for menus and taxonomy terms.
> 4. Re-implement any social features you were using.
> 5. Examine and fix any order, user, or content related problems.
> 6. Enable the new theme and configuration.
> 7. Disable all of the kickstart modules.
> 8. Test and repeat until you're happy with the results.

**More information:**

Let's say you disable all of the Kickstart-specific modules by running these commands:

```
drush -y dis commerce_kickstart_block commerce_kickstart_blog commerce_kickstart_comment \
  commerce_kickstart_inline_help commerce_kickstart_menus commerce_kickstart_merchandising \
  commerce_kickstart_order commerce_kickstart_product commerce_kickstart_product_ui \
  commerce_kickstart_reset commerce_kickstart_search commerce_kickstart_slideshow \
  commerce_kickstart_social commerce_kickstart_taxonomy commerce_kickstart_user

```

And then you can disable the other modules:

```
drush -y dis commerce_kickstart_help commerce_kickstart_migrate

```

Here's a picture of what your site's homepage will look like if you afterwards (assuming you're still using the same base theme):

You'll find that:

* All of the home page content is gone.
* The menus are gone.
* The admin menus are damaged but usable. (There appears to be a one-pixel line at the top of the page that allows you to click on menu items unless your screen is extremely wide.)
* All of the theming done for products is gone.

The good news is that:

* All of your content is still there.
* Links to existing products will work (albeit not as pretty).
* Administrative functionality is A-okay.

Given the current situation, you'll probably want to go ahead and create a new theme. I suppose you could sub-theme the existing theme, but I'm not sure why you would given that everything is now broken.

The homepage will also need to be replaced. Views, panels, or a node would all be good choices, depending on your needs. The rest of the blocks and menus will also need to be created as blocks and re-added to your theme, but you'd need to do this anyway so it's probably not a big deal.

Any other customizations around comments, users, orders, etc. will need to be reevaluated and implemented as you see fit.

Once you're happy, you'll just need to test, test, and test some more to make sure you've cleaned up all the edges.

---
Tags: 7, commerce, migrations
---


title: RedirectResponse not working

text:
# Question
Title: RedirectResponse not working
I'm in the process of porting my modules from D7 to D8. No real problems so far, but...

I have a multistep form from where I need to redirect to /node/add/xyz in the last step. (All required input form data is stored in D8 TempStore before the redirect). In d7 I used the simple and functional drupal\_goto('node/add/xyz') function which is gone in D8 for whatever reason.

I looked into core modules to see how it is done in the D8 way and it seems RedirectResponse() from the Symfony routing system is the way to go. However doing something like this:

```
return new RedirectResponse(url('node/add/xyz', array('absolute' => TRUE)));

```

But this is silently ignored, no error, nothing. I read that doing RedirectResponse from somewhere in the code may not work. So my next idea of doing it was to use a form redirect in this way:

```
$form_state['redirect_route'] = array(
  'route_name' => 'node.add',
  'route_parameters' => array(
    'node_type' => 'xyz',
  ),
);

```

even without any effect. I'm out of ideas and wish drupal\_goto() back. Hopefully someone out there can help me out!

Thanks in advance bzrudi

# Answer
Form redirects haven't changed between Drupal 7 and 8; you still need to use `$form_state['redirect']` (incidentally `drupal_goto()` shouldn't be used within form submissions in Drupal 7, it can mess things up).

Within your form class's `submitForm()` method, you can use

```
$form_state['redirect'] = 'node';

```

Or

```
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

```

Full info can be found in the `FormBuilder::redirectForm()` docs
> 2 votes

# Answer
In Drupal 8, you redirect a form in its `submitForm()` method by calling `$form_state->setRedirect()`.

This is the code used from `UserLoginForm::submitForm()`, which redirects the user to user/$uid.

```
  // A destination was set, probably on an exception controller,
  if (!$this->getRequest()->request->has('destination')) {
    $form_state->setRedirect(
    'entity.user.canonical',
    array('user' => $account->id())
    );
  }

```
> 2 votes

# Answer
Due to caching, you can't modify the `form_state` from `hook_form_alter()` anymore. Instead, in order to set or alter the redirect destination of a form, you need to attach a `#submit` handler to any action buttons available on the form, e.g.:

```
$form['actions']['submit']['#submit'][] = 'mymodule_form_submit';

```

and set the redirect destination in there:

```
function mymodule_form_submit($form, FormStateInterface $form_state) {
  $form_state->setRedirect('user.page');
}

```
> 1 votes

---
Tags: redirection, 8
---


title: Check when core was updated

text:
# Question
Title: Check when core was updated
I want to know which Drupal version I am currently using, and when it was updated.

There is a global `VERSION` that returns the current version. Is there a way to get how Drupal was updated?

# Answer
> 2 votes
Assuming you want to know when the update was really applied to your system, e.g. to check if the security fix was applied on time before the exploit was active in the wild:

If you are using drush for your updates and didn't delete recent folders, and didn't do any additional updates of your site, you can look up the last core update in your drush-backups folder. The updates have a timestamp in the folder names

e.g. in linux

`find ./drush-backups/<site-name> -name "drupal" -type d` or

`find ./drush-backups/<site-name> -name "modules/<module_name>" -type d` for a module update.

Otherwise you have to resort to the file modification attributes of the file-system, which might show write access from after the update.

To get the information in php you could try to use the php function filetime https://secure.php.net/manual/en/function.filemtime.php on the CHANGELOG.txt file. This file should be updated with core each time, even if the content is not up to date.

---
Tags: updating
---


# Question
Title: How to limit adding content of a specific content type to paid memberships only?
I have created a user role **"seller"**

when user enters to their account a **"Add blog post"**-tab is shown to user when user click on it he/she can add **"Add blog posts"**

**"Add blog posts"** is a node form which contains field "title","image upload","body"

I want to add restriction to "seller" type user Only those users can add post who paid **(paid membership)** for it to add **"Add blog posts"** (I have created a special role for paid membership).

**Notes**:

* I have created a special role for **paid membership**.
* When a user clicks on "**Add blog post**"-tab, the user must be redirected to checkout page if the user didn't paid in past. Users who already have the **paid membership** role should be able to create, edit and delete blog posts.

# Answer
> 1 votes
Assuming that your "***Add blog post***" matches with an URL like `node/add/blog`, you can use the Rules module to stop any user who is trying to use that URL, if that user does not have access to the role "***Paid membership***" that you have in place. Here is the actual rule to do so (in Rules export format, just import it in your own site and enable it there to see it at work):

```
{ "rules_limit_access_to_node_add_blog" : {
    "LABEL" : "Limit access to node\/add\/blog",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "node\/add\/blog" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Adding content for selected content types (such as for \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022) triggers some extra (Rules) logic, as you can see here. I.e. for anyone who does not have the role to do so.",
          "type" : "error"
        }
      }
    ]
  }
}

```

The assumption in this rule is that your role "***Paid membership***" has a role-id of "4" (if not just adapt the role after you imported the rule to make it fit, or change the value of "4" before importing the rule). And if your URL is different from `node/add/blog`, then adapt that also to make it fit for your case. Obviously, the actual error message being shown may need tuning also. And if the machine name of your content type is not "`blog`", but "`whatever`", just change all `blog` occurrences to "`whatever`" before importing this rule.

Happy Rules-ing!

# Answer
> 0 votes
I think the easiest solution is to create a new role **Paid membership** and give this role to the seller after he has paid.

You can assign the permission **Add blog content** to this role and remove that permission from the seller role.

---
Tags: rules, ubercart
---


# Question
Title: What are the differences between EntityFieldQuery and field_get_items()
What are the differences between `EntityFieldQuery` and `field_get_items()` ?

When should one be used over the other?

I have a relatively complex query that I need to build, using values from custom fields.

# Answer
> 2 votes
They are intended for different purposes.

EntityFieldQuery is an object to query entities using conditions that includes the value of their fields (for example: retrieve all entities of type node that have 'foo' as value in the field\_somestring field).

> Retrieves entities matching a given set of conditions.
>
> This class allows finding entities based on entity properties (for example, node-\>changed), field values, and generic entity meta data (bundle, entity type, entity id, and revision ID). It is not possible to query across multiple entity types. For example, there is no facility to find published nodes written by users created in the last hour, as this would require querying both node-\>status and user-\>created.

field\_get\_items(), on the other side, is a function to retrieve field data of a single entity:

> Returns the field items in the language they currently would be displayed.

So, I guess you should use EntityFieldQuery. Keep in mind the advice I copiyed above: you can only query properties (status, creation date, etc),metadata and field values, but you can't join with other data (any other specific table or query two entity types). If you need that use db\_select.

---
Tags: entities, database
---


title: Memcache do cache_pages?

text:
# Question
Title: Memcache do cache_pages?
I have disabled **Cache pages for anonymous users** from Drupal admin **admin/config/development/performance**.

I have set my site to point on 2 domains such as www.ex1.com and www.ex2.com. One domain is for german language and one is for English. All is working fine on my localhost where there is no memcache. But on my live server front page is getting cached.

In settings.php I have settings like below:

```
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_default_class'] = 'MemCacheDrupal';

// The 'cache_form' bin must be assigned to non-volatile storage.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

// Don't bootstrap the database when serving pages from the cache.
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

$conf['memcache_servers'] = array('memcached:11211' => 'default');
$conf['memcache_bins'] = array( 'cache' => 'default',
        // Any bin that goes to 'none' will fall through to database caching.
        'cache_form' => 'none', );

```

Do this can help like adding below line ?

```
$conf['memcache_bins'] = array('cache' => 'default',
                                 'cache_page' => 'pages',
                                 'cache_block' => 'blocks');

```

setting pages cache to point cache\_page.

Please suggest. That will be great if someone can explain that how we stop cache\_pages when we are using memcache.

**UPDATE:** Its happening with only view Titles ie: titles get cache if I visit one domain first and then second. It shows title language from first domain into second domain.

Thanks!

# Answer
> 1 votes
This is what you need.

```
// Turn off page cache
drupal_page_is_cacheable(FALSE);
// Set memcache prefix to be different for each hostname.
$conf['memcache_key_prefix'] = $_SERVER['HTTP_HOST'];

```

---
Tags: 7, caching
---


# Question
Title: How can I dynamically add URL or taxonomy to body class
Am creating my own theme and have successfully added the URL into the node class in node.html.twig with {% set classes = \[ 'url' ~ url|clean\_class, \] %} but I need to be able to style each page individually as a whole, not just at the node level - how do I add the URL or the taxonomy of the node to the page or body classes?

# Answer
> 9 votes
The answer provided by mradcliffe was what I needed. One improvement that will yield a css-friendly class name is to use the Twig |clean\_class filter. Here is the code:

In MY\_THEME.theme

```
<?php
function MY_THEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $variables['current_path'] = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
}
?>

```

In html.html.twig:

```
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    current_path ? 'context' ~ current_path|clean_class,
  ]
%}
<body{{ attributes.addClass(body_classes) }}>

```

Don't forget to clear your cache!

# Answer
> 3 votes
You may do something similar in the `html.html.twig` template, but the full url is not available by default. That means you would need to add a THEMENAME\_preprocess\_html() to your THEMENAME.theme file. The `path.current` service provides the current path (similar to `current_path()`, and the `path.alias_manager` service will do path/alias lookup (similar to `drupal_lookup_path()` although there is no change record for this change). Setting it into variables should expose that in the template with which you can add a class to `attributes`.

my\_theme.theme:

```
function my_theme_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $variables['current_path'] = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
}

```

templates/html.html.twig:

```
<body{{attributes.addClass(current_path)}}>

```

---
Tags: theming, 8
---