# Question
Title: How to use multiple reverse relationships from different content types in a single View Drupal 7?
i have three content types

1- News

2- Articles

3- Press Releases

On every content type we have a custom field called 'industry'.

so when we create a news (or article or press release) we fill the industry field 'construction medical energy etc etc' (Means on which page\[of content type industry\] it should be display)

i want to create a view where i want to show all three content types "news ,articles, press releases" which have the field 'construction' in it.

Step by step Snap shots are attached for my views and content types.

1. adding news: http://prntscr.com/b940qh
2. my view screen shot: http://prntscr.com/b943oi
3. Want Result like : http://prntscr.com/b948qv

# Answer
> 0 votes
Going of memory here, so things may not be exact.

One possible solution:

For **Contextual Filter** add Industry

**When Filter is not in the URL** select fixed value

**Type** select fixed

In the text box put `construction`

---

Another possible solution, if your Industry field is tax term reference field then add `Terms of the node` as a relationship. Then in Filter Criteria (below Fields), add tax terms and type your term name `construction`

---
Tags: 7, views
---


# Question
Title: Procedure to import a site to Acquia Dev Desktop
So, I'm looking for a painless procedure to import a site into Acquia's Dev Destkop on Windows

Theoretically, the procedure should be

1. Install clean drupal site (clean db and codebase)
2. Create Database and user for site to be migrated with phpmyadmin
3. Copy sites folder to new drupal root
4. Configure settings.php file to match new server environment.
5. Run Update.php script

The problem is I get a `PDOException: SQLSTATE[HY000] [1045] Access denied for user 'psr_admin'@'localhost' (using password: YES) in drupal_get_installed_schema_version() (line 155 of C:\Users\Nick\Sites\devdesktop\psr_final\includes\install.inc).`

This is the procedure I've followed on a number of installations, and I am wondering what I am doing wrong, or which aspect of the configuration is incorrect. I've even gone into phpmyadmin and re-created the database user and password to make sure that all the settings are correct. So, can someone tell me what I did wrong, or point me to the correct way to import a site into Acquia's dev desktop?

# Answer
Dev desktop hides the settings file on local sites, so it's a little difficult to see what the settings actually are.

Looks like you're on windows. Hopefully you can find the directory your local settings are stored in by looking at where they are on my mac:

```
~/.acquia/DevDesktop/DrupalSettings/

```

The local settings file name has the pattern:

```
cld_prod_<site_name>_<dev_test_prod>_default.inc

```

Don't change this file. But you can see if it's accessing the psr\_admin user you set up. By default my settings file shows the user 'drupaluser' with '' (an empty string) for a pw.
> 1 votes

---
Tags: migrations, acquia-dev-desktop
---


# Question
Title: How to display message (NDA, warning, etc.) before content can be viewed?
Say a user wishes to view a certain piece of sensitive content. How can we have the site first respond with a notice, before the content can be viewed?

Specifically, I'm looking to have the site respond with a simple NDA (Non-Disclosure Agreement) before displaying certain nodes (and even then, only to registered users, of course). But I can imagine many more uses: displaying conditions and terms related to the content, displaying an age warning for... er, more delicate content, and so on.

In my case, I need every sensitive node to display an NDA; presumably, the notice would be dismissed by some sort of "Agree" or "Proceed" link, which would then take the user to the content. After that, the node would ideally remember that the user has permission for future viewings of that specific node (i.e., doesn't need to see and agree to the notice every time).

I can imagine other sites, though, that might want to enable agreements for whole groups of content (such as a node type): view the notice once, and then have free access to any of the affected nodes.

Also, it would be ideal to have the option of allowing unimpeded view of the teaser, with the notice coming into play only when a reader tries to view the full node.

Whatever the details, does anyone have ideas for enabling this? I've found many modules or techniques to prevent access to specific nodes by user role, or password access, etc., but not to grant access after displaying a notice. There's the Legal module (http://drupal.org/project/legal) for displaying terms and conditions upon registering to become a user, but that doesn't handle viewing specific nodes.

As always, I suspect I'm missing something obvious. My kingdom for a solution!

# Answer
> 0 votes
You've listed a nebulous group of requirements that somewhat overlap with existing module projects out there. FWIW, there's also the Premium Content module which also has elements of what you're asking for.

My guess is you're not going find one that 100% matches your current and ongoing needs. So you either find one that matches the most & work on patches to that project, or you build your own. Depending on how specific your needs are one might work better than another.

If you go the "build my own" path, look at `hook_node_access()` & `hook_node_view()` (D8: `hook_entity_view()`) which respectively allow you step in front of node permission checks and rendering. They will be the core of your strategy to determine when to allow full access & when to send your user through a NDA confirmation workflow.

---
Tags: views, nodes
---


title: Model field of view and hide if empty

text:
# Question
Title: Model field of view and hide if empty
Hello this is my file views-view-field--sitemap--views-data-export--field-image.tpl.php :

```
<?php

$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

echo $fields["field_image"]->content;

```

When I check the box to hide empty if the image field, the empty fields are hidden in the preview of view but not out. How to hide empty fields when the view is displayed? I think there is a line to add in the template file.

# Answer
> 0 votes
```
<?php

if (!empty($field->original_value)) {

  $fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

  echo $fields["field_image"]->content;

}

```

---
Tags: 7, views
---


# Question
Title: Hide authoring information programmatically in a content type
How do I programmatically hide the *Authored by* part in a content type using hooks?

# Answer
I assume you need to hide the *Authored by* part basing on some conditions you check at run-time. If you need to hide that only for a content type, for example for the *Article* content type, then you can change settings in admin/structure/types/manage/article.

>

If you want to hide that information basing on the user ID of the user who created the node, then you could use the following code.

```
function mymodule_preprocess_node(&$vars) {
  $node = $vars['node'];

  // Remove that information if the node has been created from the user #1.
  if ($node->uid == 1) {
    $vars['display_submitted'] = FALSE;
    $vars['submitted'] = '';
    $vars['user_picture'] = '';
  }
}

```

Notice I am setting the same variables set by `template_preprocess_node()`, which uses the following code.

```
  // Display post information only on certain node types.
  if (variable_get('node_submitted_' . $node->type, TRUE)) {
    $variables['display_submitted'] = TRUE;
    $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
  }
  else {
    $variables['display_submitted'] = FALSE;
    $variables['submitted'] = '';
    $variables['user_picture'] = '';
  }

```

The template files used by Drupal core check `$display_submitted` before rendering `$submitted` and `$user_picture`. Probably Drupal core sets also `$variables['submitted']` and `$variables['user_picture']` for those template files that render them without checking first `$display_submitted`.
> 3 votes

# Answer
This variable is added in template\_preprocess\_node, which is the second step in template processing.

These processors pass the variables by reference, so in any of the lower hooks (you can use a theme or a module to implement hook\_preprocess\_HOOK), you can alter this variable.

So in your module or theme (change MYMODULE with theme name), use this code:

```
function MYMODULE_preprocess_node(&$variables) {
  $variables['display_submitted'] = FALSE;
}

```
> 1 votes

---
Tags: nodes, hooks
---


title: How do i mark html TRUE in l()

text:
# Question
Title: How do i mark html TRUE in l()
In Drupal 7 we have option to mark HTML=\>TRUE.

How can i do it in Drupal 8

my code is

```
    $create_icon_path = 'my_icon.png'; //my icon path
    $create_icon = '<img height=15 src = "/' . $create_icon_path . '">';
    $create_earlywarning_url = Url::fromUserInput('/node/5');
    $create_earlywarning = \Drupal::l($create_icon, $create_earlywarning_url);
    return $create_earlywarning;

```

But its printing the

```
"<img height=15 src = "my_create-icon.png">" in <a> tag.

```

# Answer
> 2 votes
Here is a way to do this:

```
$create_icon_path = 'my_icon.png'; //my icon path
$create_icon = '<img height=15 src = "/' . $create_icon_path . '">';
$create_earlywarning_url = Url::fromUserInput('/node/5');
$link_render_array = array(
  '#title' => array(
    '#markup' => $create_icon
  ),
  '#type' => 'link',
  '#url' => $create_earlywarning_url,
);
return \Drupal::service('renderer')->renderRoot($link_render_array);

```

Hope this solves it!

# Answer
> 1 votes
The `'html' => TRUE` option from links was removed from core for a few different reasons. Read the issue for more information.

One of the keys to understanding Drupal 8 is that you almost never need to explicitly render things or resort to the `\Drupal` class in object oriented code.

When you are in a controller or in any other context when you are returning content to be displayed, leverage render arrays and Drupal will do the right thing:

```
$create_icon_path = '/some/path/my_icon.png';
$create_earlywarning_url = Url::fromUserInput('/node/5');

$build = [
  '#title' => [
    '#theme' => 'image',
    '#uri' => $create_icon_path,
    '#width' => 15,
    '#height' => 15,
    '#alt' => 'My Alt Text',
  ],
  '#type' => 'link',
  '#url' => $create_earlywarning_url,
];

return $build;

```

So the key here, is that for the `#title` of the link, you can just make it a render array for an image, and the renderer will figure it out and output everything properly (eg, also include the RDF info if you have that enabled).

---
Tags: forms, 8, navigation
---


# Question
Title: How to create a user and only allow him to add users?
I have my system user roles, in the first image below:

I want my user level access to be like the second image.

I am the `administrator` of the site, I want to create a user with a role `MyID Organization Administrator`. This user must be allowed to add users and assign it with the role `MyID Manager`, `MyID Inputter` and `MyID Printer`. `MyID Organization Administrator` must only be allowed to add users and nothing more about administering the website itself. How am I gonna do that?

# Answer
You can try the Roledelegation module, which allows the admin to delegate certain users the ability to assign other users specific roles. Per the module's page:

> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
>
> The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions on the permissions page.
> 0 votes

---
Tags: 7, forms, users
---


title: Get whole node by post type

text:
# Question
Title: Get whole node by post type
Is there any way of getting a node by its post type? I've tried with the following code, but it doesn't really work.

```
$query = \Drupal::entityQuery('front_page_slider');

```

As far as I read on tutorials, it should work when the content type is *front\_page\_slider*. Instead, it returns an error.

> The "front\_page\_slider" entity type does not exist.

# Answer
> 5 votes
What you call *post type* is for Drupal a *content type*, or an *entity bundle*. The first argument of `\Drupal::entityQuery()` is the entity type that, in the case of nodes, is *node*.

The code you need is the following one.

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

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->execute();

$nodes = Node::loadMultiple($nids);

```

Note I added the `condition('status', 1)` line, which returns only the published nodes; if you are not interested only in the published nodes, you can leave that line off.

Furthermore, if you are executing the code without showing the result to the currently logged-in user, for example because it runs at cron time, you should disable the access check, and use the following code.

```
// Put the following line at the beginning of the file containing the code.
use \Drupal\node\Entity\Node;

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->accessCheck(FALSE)
  ->execute();

$nodes = Node::loadMultiple($nids);

```

Differently, you would get only the nodes for which the currently logged-in user has access.
In the example of a `hook_cron()` implementation, that user is the anonymous user. Without the `accessCheck(FALSE)` line, the code would get only the published nodes to which anonymous users have access, which could be none, if the user permissions don't allow anonymous users to see nodes.

`accessCheck(FALSE)` is used by `node_access_rebuild()`, which contains the following lines. (Read the comment before the code.)

```
  // Disable access checking since all nodes must be processed even if the
  // user does not have access. And unless the current user has the bypass
  // node access permission, no nodes are accessible since the grants have
  // just been deleted.
  $entity_query->accessCheck(FALSE);

```

---
Tags: 8, entities
---


# Question
Title: Model view and labels are not displayed correctly
I created a model view and labels are not displayed correctly when I export with the module: "Views data export".

Here are the contents of my model `views-view-field--sitemap--views-data-export--field-image.tpl.php` :

```
<?php

$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>';

echo $fields["field_image"]->content;

```

the result is :

`<image:loc>http://www.domaine.com/xxx.jpg</image:loc>`

instead of :

```
<image:loc>http://www.domaine.com/xxx.jpg</image:loc>

```

# Answer
You're trying to change the content of your XML to provide structural changes to the XML document. This content is escaped so it doesn't break the XML document.

If the whole goal of theming is set your XML image field to a `image:loc` element, you should just change add a **Label** to your field with it set to "image:loc". This will render the XML document image field as an `image:loc` element.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to display custom data array via Twig
I've created service which gets the raw data from custom content type. It looks like this :

```
  Array
(
    [front_page_slider] => Array
        (
            [1] => Array
                (
                    [title] => Lorem ipsum dolor sit amet
                    [body] =>Some example slider text up here
                    [field_image] => http://localhost/drupal8/sites/default/files/2016-05/slider1.png
                    [field_link_uri] => http://example.com
                    [field_link_title] => see more
                )

        )

)

```

After that i use array\_push function to add this array $variables global variable.

I've tried to display any of this fields like this:

```
{{ dump(front_page_slider[1].title) }}

```

or this: {{ dump(front\_page\_slider) }}

But both return NULL. What I do wrong ?

# Answer
> 0 votes
Have you added 'front\_page\_slider to the variables array in your twig template definition?

File...module\_name.module

```
function hook_theme(array $existing, $type, $theme, $path) {
  return [
    'template_name' => [
          'variables' => [
           'front_page_slider' => [],
      ],
    ],
  ];
}

```

# Answer
> 0 votes
Install Devel Module (also enable devel kint sub module)and use **kint**

**What is Kint?**

> Kint for PHP is a tool designed to present your debugging data in the absolutely best way possible.
>
> In other words, it's var\_dump() and debug\_backtrace() on steroids. Easy to use, but powerful and customizable. An essential addition to your development toolbox.
>
> This module allows to use kint($data) like as dpm()/dsm()/krumo() in Devel module.

something like
{{ kint(page) }}

Read more and some usage about kint.

---
Tags: 8, theming, nodes
---


# Question
Title: Setting #states property for a field_collection item added with the add_more button
This is a D8 question as the solution in Using #states with field collection doesn't work for D8.

Here are the solutions I have tried, but none of them was working:

**1- Adding an after build function for the field\_collection element**

```
$form['my_fc_field']['#after_build'][] = 'my_fc_field_after_build';

```

=\>The function is not called when the "add\_more" button is pressed

**2- Adding an after build function for the field\_collection item element**

```
$form['my_fc_field']['widget'][0]['fc_item_field']['#after_build'][] = 'fc_item_field_after_build';

```

=\>The function is not called when the "add\_more" button is pressed

**3- Altering my field\_collection widget**

```
function artprod_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getName() == 'my_fc_field') {
    $widgets_that_need_states = &$element['my_fc_field']['widget'];
    $childs = Element::children($widgets_that_need_states);
    foreach ($childs as $child) {
      $widgets_that_need_states[$child]['value']['#states'] = array(
        'visible' => array(
          "select[data-drupal-selector=\"xxxx\"]" => array(
            'value' => 'yyy'
          )
        )
      );
    }
  }

```

=\>The function is not called when the "add\_more" button is pressed

Conclusion: with all of those 3 methods I could set the #states property to the already constructed element, but not for the added elements.

# Answer
I could solve it myself...

The solution is to alter the field\_collection widget. In the point 3 of my question, I have made a mistake in the code. Here is a generic code to handle this behavior for changing the visibility of a text field according to the value of a select field:

```
function your_module_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $fn = $context['items']->getFieldDefinition()
    ->getName();
  if ($fn == 'your_field_collection')  {
    // Get the delta
    $delta = $element['#delta'];
    $element['your_fc_text_field']['widget'][0]['value']['#states'] = array(
      'visible' => array(
        "select[data-drupal-selector=\"edit-your-field-collection-$delta-your-fc-text-field\"]" => array(
          'value' => "your_value_when_visible"
        )
      )
    );
  }
}

```

**Note 1**: I used "data-drupal-selector" because this was the only jquery selector which was working for the "select" (select seems more tricky then other fields)

**Note 2**: Adding ":" before "select" like ":select\[data..." is breaking the feature. I don't know why!

**Note 3**: take care of the $delta in the data-drupal-selector

**Note 4**: Use "Inspect element" of your browser to get the correct value of your "data-drupal-selector"
> 1 votes

---
Tags: 8, javascript
---


# Question
Title: How to use URL parameter and page callbacks for tab menus correctly?
I'm using Drupal 6 and I'm trying to display two tab (menus) on a page that has the URL /vehicle\_info. Both pages that the tabs link to should take a node's nid as parameter. My current code looks as follows:

```
  $items['vehicle_info/%/basic'] = array(
    'title' => t('Basic & Bookings'),
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('administer fleet'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 10
   );
  $items['vehicle_info/%/history'] = array(
    'title' => t('Service history'),
    'page callback' => 'vehicle_service_history',
    'page arguments' => array(1),
    'access arguments' => array('administer fleet'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 20
   );

```

I'm running into 2 issues:

1. The tab "Service history" does not open the page "vehicle\_service\_history" (which is actually a view with the URL vehicle\_service\_history). It opens a page with the URL "vehicle\_info/123/history", which does not exist (123 stands for the current nid).
2. The default tab "Basic & Bookings" does not link to the URL "vehicle\_info/123" but only to "vehicle\_info".

What am I missing?

# Answer
> 1 votes
A couple of things seem to be missing here. The main confusion seems to be around `page callback` which should be a **function** not a URL. The URL is the key to your `$items` array.

1. Your first menu item has no 'page callback'. This would be inherited from the parent item (keyed as `$items['vehicle_info/%']` and a type of `MENU_NORMAL_ITEM`) if you had one, but you don't.
2. Your second item menu seems to be confusing URL with callback as well. If you want it handled by a view then your page display on your view should handle the URL path `vehicle_info/%/history`, i.e. it will have a contextual filter. Does your view work like this?

# Answer
> 0 votes
If vehicles is a content type that happens to sit under the path 'vehicle\_info' then you can simplify this a lot. Enhance the regular core tabs

```
$items['node/%node/basic'] = array(
  'title' => t('Basic & Bookings'),
  'page arguments' => array(1),
  'access callback' => 'vehicle_administer_fleet',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 10
);
$items['node/%node/history'] = array(
  'title' => t('Service history'),
  'page callback' => 'vehicle_service_history',
  'page arguments' => array(1),
  'access callback' => 'vehicle_administer_fleet',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 20
);

```

You will also need to define the custom access callback

```
function vehicle_administer_fleet($node) {
  return $node->type == 'vehicle' && user_access('administer fleet');
}

```

This is what drupal core does for it's own node tabs, more often then not, it is best to keep consistancy

# Answer
> 0 votes
You went wrong way!!!
you can achieve completely what you want with views.

Create A views ,add your field as you want , set page Url to `node/*/basic`, in view **Menu** section (below page url) select menu tab with you title(see this for more info about create menu tab with views ). Also in **Access** section you can select who can see this page created by views.

I think you really don't Know how powerful really views is ;).

---
Tags: 6, routes
---


# Question
Title: How do I get rid of the
Search
 at the top of the search results page?
A customer of mine insists on having *Search Results* as a heading. I can set this on the block I have created using the Custom search module.

How do I get rid of the `<h1>Search</h1>` at the top of the search results page?

# Answer
> 0 votes
I suggest way three way

* Hide it with css ( set it to `display:none`)
* Remove it with simple Jquery command ( `.remove`)
* override search result page template

I mean **duplicate page.tpl.php file in your custom theme** set name to **page--search.tpl.php** and remove `<h1><?php print $title; ?></h1>`. **finally don't forget clear the cache**

If this TPL doesn't work then you have to declare it in `template.php` using `theme_hook_suggestions` in the same way as answer of your linked question. See for the URL which your instance is using for giving search result.

For `$base_url/search` use

```
//replace your theme name with MYTHEME
function MYTHEME_preprocess_page(&$vars) {
  if (arg(0)=='search') {
    $vars['theme_hook_suggestions'][] = 'page__search';
  }
}

```

Add this in your `template.php` & as you are suggesting TPL for page, you have to use `THEME_preprocess_page($vars)`.

---
Tags: search
---


title: Bind click event to ajaxify form button

text:
# Question
Title: Bind click event to ajaxify form button
how the title says I would like to trigger javascript (jQuery) event from generated Drupal form button. I already add an *id* to the button and added the javascript in theme file like so:

```
$form['dialogCreateButton'] = array(
    '#type' => 'button',
    '#value' => t('Create'),
    '#ajax' => array(
        'callback' => 'form_kalendar_dialog_validate',
        'progress' => array(
            'type' => 'throbber', // needs to be defined
            'message' => t("Please wait..."), // instead of a message insert a javascript
        ),
    ),
);

```

and the javascript:

```
jQuery("#edit-dialogsavebutton").bind('click',function(event) {
    if(jQuery("#dialog-event-title").val().length == 0){
        focusElement.children("#eventTitle").text('(No title)');
    }else{
        focusElement.children("#eventTitle").text( jQuery("#dialog-event-title").val() );
    }
    jQuery('#dialog').dialog('close');
});

```

also with Drupal js:

```
Drupal.behaviors.rr = {

    attach: function(context, settings) {
        jQuery('#form-kalendar-dialog').once().ajaxComplete(function(event, xhr, settings) {
            console.log( event );
        });
    }
}

```

Only after several clicks the event is triggered, it acts very strange...

# Answer
Ajax callback function must to have an **ajax\_command\_invoke** function witch trigger an custom made function in **JS** side like so:

```
function form_kalendar_dialog_validate($form, &$form_state) {
  $commands = array();
  $commands[] = ajax_command_invoke(NULL, 'customMethod', array('Custom Method Arg.'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

JS

```
(function ($) {
  $.fn.customMethod = function(arg) {
    // Custom JS goes here.
    console.write(arg);
  };
}) (jQuery);

```

The answer whas here: Tlattimore blog
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: Libraries Not Loaded After Cache Clear / Reload
I'm experiencing a problem with drupal 8

whenever I clear the cache, my custom theme's libraries(ex: the css and js) will not be loaded

and I must reinstall the whole drupal to make it works again

is there anything I can do to trace the source of the problem ? Nothing strange is being logged in nginx and php's error log

# Answer
Solved

this issue occurred because I've another custom module with the same name as the theme.
> 2 votes

---
Tags: theming
---


title: Apply a style to the price

text:
# Question
Title: Apply a style to the price
I created a newsletter with the module "Simplenews". I also created a custom template for my newsletter :

```
  <table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>
    <tr>
      <td align="center">
       <a href="<?php print $node_url; ?>" target="_blank">
        <table class="deviceWidth" border="0" cellpadding="0" cellspacing="0" width="580" align="center" style="border: 1px solid #ddd;">
          <tr>
            <td>
              <table class="deviceWidth" border="0" cellpadding="0" cellspacing="0" width="280" align="left">
                <tr>
                  <td align="center">
                    <?php print render($content['field_image']); ?>
                  </td>
                </tr>
              </table>
              <table class="deviceWidth" border="0" cellpadding="0" cellspacing="0" width="280" align="right">
                <tr>
                  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #2b9900; font-size: 16px; font-weight: bold; text-decoration: none;">
                    <?php print render($content['title']); ?>
                  </td>
                </tr>
                <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>
                <tr>
                  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #313a42; line-height: 20px; text-align: justify;">
                    <?php print render($content['body']); ?>
                  </td>
                </tr>
                <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>
                <tr>
                  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
                    <?php print render($content['product:commerce_price']); ?>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
       </a>
      </td>
    </tr>
    <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>

```

I use the module "Commerce Price Savings Formatter" to view the original price, discounted prices and the discount percentage. Prices are displayed correctly on my site and the mail client, except on gmail that removes all the CSS class (even inline style). The next line problem `<?php print render($content['product:commerce_price']); ?>` because it displays the entire price (original discount and percentage). I want to apply a style to the original price, a different style to discounted prices and a different style to the club proucentage.

I think we should create 3 cell. But I do not know what to put in the line :

```
    <tr>
      <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
         <?php ?????????; ?>
      </td>

      <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
         <?php ?????????; ?>
      </td>

      <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
         <?php ?????????; ?>
      </td>
   </tr>

```

How to do this ?

```
  <table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>
    <tr>
      <td align="center">
       <a href="<?php print $node_url; ?>" target="_blank">
        <table class="deviceWidth" border="0" cellpadding="0" cellspacing="0" width="580" align="center" style="border: 1px solid #ddd;">
          <tr>
            <td>
              <table class="deviceWidth" border="0" cellpadding="0" cellspacing="0" width="280" align="left">
                <tr>
                  <td align="center">
                    <?php print render($content['field_image']); ?>
                  </td>
                </tr>
              </table>
              <table class="deviceWidth" border="0" cellpadding="0" cellspacing="0" width="280" align="right">
                <tr>
                  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #2b9900; font-size: 16px; font-weight: bold; text-decoration: none;">
                    <?php print render($content['title']); ?>
                  </td>
                </tr>
                <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>
                <tr>
                  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #313a42; line-height: 20px; text-align: justify;">
                    <?php print render($content['body']); ?>
                  </td>
                </tr>
                <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>
                <?php foreach($content['product:commerce_price'] as $commerce_price): ?>
                <?php foreach($commerce_price['#prices'] as $price): ?>
                <tr><td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;"><?php print $price['#markup']; ?></td></tr>
                <?php endforeach; ?>
                <?php endforeach; ?>
              </table>
            </td>
          </tr>
        </table>
       </a>
      </td>
    </tr>
    <tr><td height="5" style="font-family: 0px; line-height: 0px;"> </td></tr>
  </table>

```

# Answer
You have to find out which keys that hold the values in question within `$content['product:commerce_price']`. Then use those in your template. For example:

At the very bottom of your custom template append:

```
<?php drupal_set_message('<pre>'.print_r($content['product:commerce_price'],1).'</pre>'); ?>

```

Clear cahe, run your custom template (e.g. by visiting the page/url where the custom template used) and find keys that hold original, discount and percentage value.

After you found those keys, respectively use them in your "I think we should create 3 cell. But I do not know what to put in the line : `<?php ?????????; ?>`". Then remove the `drupal_set_message` line above.

Further reading:

https://www.drupal.org/documentation/theme
https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal\_set\_message/7.x
http://php.net/manual/en/language.types.array.php#example-101

HTH

**UPDATE**

From what I can see from your update, replace your

```
<tr>
  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
    <?php print render($content['product:commerce_price']); ?>
  </td>
</tr>

```

with

```
<?php foreach($content['product:commerce_price'] as $commerce_price): ?>
  <?php foreach($commerce_price['#prices'] as $price): ?>
    <tr><td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;"><?php print $price['#markup']; ?></td></tr>
  <?php endforeach; ?>
<?php endforeach; ?>

```

**UPDATE 2**

Replace the above with:

```
<tr>
  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
    <?php print $content['product:commerce_price'][0]['#prices']['list']['#markup']; ?>
  </td>

  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
    <?php print $content['product:commerce_price'][0]['#prices']['price']['#markup']; ?>
  </td>

  <td valign="top" align="center" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 20px; font-weight: bold; text-decoration: none;">
    <?php print $content['product:commerce_price'][0]['#prices']['savings']['#markup']; ?>
  </td>
</tr>

```
> 0 votes

---
Tags: commerce, emails
---


# Question
Title: Select form, write selected item to database
I'm using Drupal 7 and Form API.

My Problem:

I want to load rows from my Database and put them in a Select Form(Form API). After this form is submitted I want to write the selected option in my database.

The first step works fine but I don't know how to get the selected option for writing it into my database.

Load values from database:

```
$result = db_select('color', 'c')
->fields('c', array('ID', 'color', 'name')

->execute()

foreach($result as $row) {
     $options = $row->color . ' ' .$row->name;
}

```

Add options to form:

```
 $form['colors'] = array(
   '#type' => 'select',
   '#options' => $options,
 );

```

When form is submited:

```
db_insert() //Add ID of selected item to database

```

How do I get the ID of the selected color? The options of this select form is a name combination(color+name)

# Answer
First of all, there is a small error in your code, $options should be an array. Moreover, if you add a key=\>value pair for each option, you can get the key of the selected option in the form\_submit function. Here is what your foreach could look like:

```
foreach($result as $row) {
  $options[$row->ID] = $row->color . ' ' .$row->name;
}

```

and in your submit function you can grab the ID of the selected option like this:

```
$color_id = $form_state['values']['color'];

```

Good luck!
> 0 votes

---
Tags: forms
---


# Question
Title: Select nodes based on entity reference value
I have a content type **student**, and it has an Entity Reference field named as `field_offline_course_reference` and a email field `field_offline_course_student_ema`

I need a list of all emails of students based on `field_offline_course_reference` value.

How can I change the following code to achieve what I want to do?

```
$courseinfo = $theCourseId;
$query = db_select('node', 'n');

$query->join("field_data_field_offline_course_reference", "t", "t.entity_id = n.nid");
$query->fields("n", array("nid"))
    ->condition('n.type', 'students')
    ->condition('t.entity_id', $courseinfo);

$result = $query->execute();
    foreach ($result as $record) {
       var_dump($result);
}

```

# Answer
> 1 votes
You need to JOIN on nid ***and vid*** (entity fields are stored per nid/vid), add a JOIN to your email field table, set the fields to select the email value, and set your WHERE clause to entity reference target.

```
$query = db_select('node', 'n');
$query->join("field_data_field_offline_course_reference", "t", "t.entity_id = n.nid AND t.revision_id = n.vid");
$query->join("field_data_field_offline_course_student_ema", "e", "e.entity_id = n.nid AND e.revision_id = n.vid");
$query->fields("e", array("field_offline_course_student_ema_value"))
    ->condition('n.type', 'students')
    ->condition('t.field_offline_course_reference_target_id', $courseinfo);

```

---
Tags: nodes, database
---


# Question
Title: Treating string field as numeric to use as an exposed filter
I have a field in my users' profiles that has been defined as varchar initially even though it holds numeric values. I'm trying to use that field as an exposed filter and perform "greater than or equal" operation on it; however, since it's a varchar field, View doesn't give me that option.

In my module, I have come up with these two hooks to do a workaround:

```
function MY_MODULE_views_query_alter(&$view, &$query) {
    if ( $view->name == 'manage_users' ) {
        foreach($query->where[1]['conditions'] as $key => $condition) {
            if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
                $query->where[1]['conditions'][$key]['value'] = (int)$query->where[1]['conditions'][$key]['value'];
                $query->where[1]['conditions'][$key]['operator'] = '>=';
                break;
            }
        }
    }
}

function MY_MODULE_views_data_alter(&$data) {
    $data['field_data_field_count']['field_count_value']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_value']['argument']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['argument']['handler'] = 'views_handler_filter_numeric';
}

```

The first hook seems to be working fine and successfully changing the operator from `LIKE` to `>=`; however, that's not enough for me because it still thinks 2 is greater than 15. So I added the second hook to make sure the field is actually treated as numeric, but that doesn't seem to have any effect on how the results are returned and it still thinks 2 is greater than 15.

# Answer
> 3 votes
Excellent question!
You only need the `hook_views_query_alter` function, here is what it should look like:

```
function MY_MODULE_views_query_alter(&$view, &$query) {
  if ( $view->name == 'manage_users' ) {

    // For filtering
    foreach($query->where[1]['conditions'] as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
        $query->where[1]['conditions'][$key]['value'] = array(':val' => (int)$query->where[1]['conditions'][$key]['value']);
        $query->where[1]['conditions'][$key]['field'] = 'CAST(' . $query->where[1]['conditions'][$key]['field'] . ' AS UNSIGNED) >= :val';
        $query->where[1]['conditions'][$key]['operator'] = 'formula';
        break;
      }
    }

    // For sorting as well
    foreach($query->orderby as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count_field_count_value' ) {
        $query->orderby[$key]['field'] = 'CAST(' . $query->orderby[$key]['field'] . ' AS UNSIGNED)';
        break;
      }
    }
  }
}

```

Most important parts in this code snippet:

1. Using CAST to change the varchar into an integer \[doc\]
2. Using the 'formula' operator to instruct views that you are using a complex SQL expression, check the source code of `add_where_expression`! \[doc\]

Good luck!

---

Update Note: Even though this is working fine, the more elegant/readable way would be to have a function (equivalent to `add_where_expression`) that would allow overwriting a where/having condition.

# Answer
> 1 votes
> Alternatively, if the field is meant to hold numeric data why don't you just update the db so that the field is numeric?
>
> Are you saying directly changing it from a varchar to an int? Would that not cause any issues? Should I still keep the "\_format" column after I change the data type?

If you want to be safe, you can do it like this:

**1)** Go to your database and export your text field as a CSV file.

> **Note:** If you're using for your export, do not use CSV for MS Excel. **Use the CSV option**. As CSV for MS Excel displays the values in a comma format rather than columns.

**2)** Then open your exported .CSV file with Excel.

**3)** In Drupal delete the text field and create a new integer field.

**4)** Go to `/user/1/edit` and enter a number in your decimal field (do not enter `1` as you will not know which one is the uid and which one is the actual field) and save changes (this is so when we export we have the table structure)

**5)** Go back to your database and find the new decimal field, export as CSV. Then open on Excel.

**6)** Use the values from your 1st Excel to copy the node id's and the field values and paste them onto your 2nd Excel in the appropriate column(s) and save.

**7)** Import 2nd Excel to your integer field and check-mark ☑ replace table data with file.

**8)** In Drupal, clear/flush the cache to see the changes.

# Answer
> 0 votes
You could try using a hook\_views\_data\_alter and changing the field and filter handlers to `views_handler_field_numeric` and `views_handler_filter_numeric`, that should work pretty well. I haven't personally tried it in hook\_views\_data\_alter but the technique works great in hook\_views\_data.

Alternatively, if the field is meant to hold numeric data why don't you just update the db so that the field is numeric?

Assuming this is a site that is in production I would suggest using hook\_update\_N and db\_update to change the `type` column for the field in `field_config` to `number_integer` and the `module` field to `number`. Definitely test this update locally before pushing to the main branch.

---
Tags: entities, views
---


title: PUT method using drupal_http_request

text:
# Question
Title: PUT method using drupal_http_request
I need to update data in HP Quality Center with Drupal.

After login with success, I get some data from QC with the following code (simplified):

```
$headers = array('Cookie' => $cookie);
$request = drupal_http_request('http://qc.intra.xxx.com:8090/qcbin/rest/domains/' . $domainname . '/projects/' . $projectname . '/test-instances?query={cycle-id["' . $id . '"]}',
    array('headers' => $headers),
    'GET'
);
$xml = simplexml_load_string($request->data);
$json = json_encode($xml);
$testset_array = json_decode($json, TRUE);

```

What I want now is to update some QC fields. For that, instead of GET, I need PUT. The code I've tried to update a test instance:

```
    $xml_data = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            <Entity Type="test-instance">
                <Fields>
                    <Field Name="my_field">
                        <Value>my value</Value>
                    </Field>
                </Fields>
            </Entity>';

    $headers = array('Cookie' => $cookie, 'content-type' => 'application/xml');

    $url = 'http://qc.intra.xxx.com:8090/qcbin/rest/domains/' . $domainname . '/projects/' . $projectname . '/test-instances/404886';
    $request = drupal_http_request($url,
       array('headers' => $headers),
       'PUT',
       $data
    );

    $xml = simplexml_load_string($request->data);
    $json = json_encode($xml);
    $testset_array = json_decode($json, TRUE);

```

This is not working and I don't get any error also, what am I doing wrong?

Thanks

# Answer
For starters, looking at your code, `$xml_data` is instantiated but never used in your call to `drupal_http_request()`, you use the `$data` variable instead. Intentional or the culprit?

Second, your call to `drupal_http_request` follows the Drupal 6 (and earlier) syntax, what system are you using?

For Drupal 7, it should look like this:

```
$response = drupal_http_request($url,
  array(
    'headers' => $headers,
    'method' => 'PUT',
    'data' => $xml_data,
  )
);

// this should reveal what was actually sent out
dsm($response->request);

```

Hope this helps some!
> 3 votes

---
Tags: 7
---


# Question
Title: How do I create and synchronize product fields with entity fields on another site
**Case description:**

I have one centralized 'Asset management' Drupal website "A" (something like a simple ERP site) which manages the administration of purchased Assets, being ECK entities. The assets are unique, no stock management required.

I also have a Drupal webshop "B" using the Drupal Commerce modules, which has Commerce Product entities.

**Goal:**

The assets and products need to be two-way synchronized between the two sites, in such a way that:

* New Assets in site A will create new Products in site B.
* Some fields (title, price, status) will need to be two-way syncronized (so that when a product is sold, the Asset status field will be changed)

**Requirements**

Preferably without custom coding, but using existing Drupal modules in combination with Rules to allow flexibility in configuration.

**Question:**

* What would be a good approach in this case? Preferably without custom coding.

**My current investigations:**

There are multiple ways to construct a non-coding contributed module combination to get the result needed. My preference is a lightweight but configurable solution using Rules. I checked out these modules:

* Services module: Without other modules this requires custom coding to import and sync entities. Most services-based modules are dependent on it.
* Web Service Data module, This module allows you to bypass the default data storage location for fields and entities and instead load the data from a web service. Does not import or sync. Probably not suitable because the entities are not identical (assets and products)
* Remote Entity Api module but this might not be the most efficient way because that module creates local copies of the remote entities. This means that in site B there would exist also the same amount of asset entities as in site A, which are synchronized with the Product entities.
* Feeds module allows one-way import and sync, could be two-way but probably complex.
* The Migrate module: large framework, is a developer's tool, must have php skills.
* Services Client module the UUID needs to be inserted per entity? Not for many entities.
* Service Rules module creates endpoint for Rules Components. Requires a services client module. Might be of use (optional, see below)

**\[UPDATE MAY 30 2016\]**

According to my research the following modules combined, will likely be the most lightweight and configurable solution. I take into account that this case is not so much about migration of data, but about creating and updating using rules triggers and actions (as per the requirements).

* Web Service Client module is made to consume services without custom coding. It integrates with Rules to perform the required actions.
* Web Service Client for Feeds integrates the Web Servcice Client module with Feeds, which allows for a cron-based import of created or changed entities.
* Sevices Views module: in order to create a view of the assets fields that need to be created or updated.

**TO DO:** The suggested approach mentioned above needs to be tested in order to prove that it works. I still don't quite understand how to configure the Web Service Client module configuration of the 'REST service descriptions'. Probably because I am a newbie to services. In order to figure that out, I posted a question about it. I will add screenshots to that where needed.

**For those answering this BONUS question**: The answers have been rather broad up to now. Using the abovementioned update (may 30) please provide specific support for the solution suggested by me using the Web Service Client module configuration. This allows me to choose who gets the bonus. You may answer in the connected question in order to keep the answers on topic per question. I have also created two test sites with the modules installed and can provide admin login details if you want to test it out, or help me out with the configuration.

# Answer
I'll start with saying, you should throw your "no custom coding" requirement out. That's not to say it's not possible, but it's going to require you stitching a patchwork of solutions that might drive you to conflicting or cumbersome processes. Every data migration problem, save for the most basic (e.g. migrating content title & body nodes), will have key details and rarely has pre-made default path in Drupal.

You don't want a patchwork solution to a detailed problem like this; it will be difficult to manage if you find your future requirements or key module assumptions change in the future. Rather, you should rely on a few key tools to handle some big needs, and fill in the rest with custom code that leverages either Drupal's or contrib module's APIs.

You have 2 broad requirements. I'll list an outline of one approach.

1. An ETL solution between a new custom asset entities on Site A and commerce product on Site B.
    * You should, from the start, utilize a shared UUID on your asset entity & Commerce product; the alternative here is having some sort of shared PK mapping between sites that could have all sorts of problems.
    * The go-to-solution for Drupal data ETL is the Migration framework that allows you specify how to map fields, transform them if needed, and place them into your migrated destination. The duplicate insert problem is solved with UUIDs. Commerce Migrate provides extensions specific to the Commerce project.
    * You'll need to determine when/how such a migration sync will occur. A solution will need to be driven by your own workflow. As such, there's probably no one-size-fits-all solution here (e.g. if assets are periodically added on scheduled date a simple cron job to migrate products in might suffice a real-time requirement might require some RPC solution).
2. Data Field syncing.
    * You should rely on Serivces (as you have mentioned) and Services Entity API to provide CRUD transport. This will allow reliable data push/pull when you need it. Additionally, it could be the framework for providing a RPC service endpoint in the event you want to trigger an asset-to-commerce migration on site B from site A.
    * Just like with asset-to-product ETL, your sites' workflow is probably going to determine the best course of action. It could work with Rules (with a module provide custom conditions & actions to determine when to sync up via REST) or perhaps a simple custom module running a cron job.

In short, don't rely on a patchwork of module projects to somehow solve the problem for you through trial-and-error. Pick key tools that solve one single problem well (e.g. ETL, HTTP data transport, unique identification) and use your custom code to supply the logic that's unique to your use case.
> 2 votes

# Answer
Cross-site sync in Drupal 7 is non-trivial (there's a large project happening to make it easy in Drupal 8...some day), and since everything can have customizations general purpose tools have to be so flexible as to require massive effort to develop. True, there is lots of desire but rarely do two people have a shared set of requirements.

I've built a couple syncing solutions and usually at their heart they become CSV or JSON file exchanges. So while I've always used either custom code or a human to solve the hard problems to avoid duplicates and update loops, it *might* be possible to wire together feeds (using a JSON parser) and views (with a JSON display) or services in a way that would push information back and forth as long as it stays as simple as you suggested in your original post.
> 2 votes

---
Tags: 7, commerce, entities, services
---


title: Metatags generated from views results

text:
# Question
Title: Metatags generated from views results
I'm using the Metatag module to include appropriate Open Graph, etc. tags to delineate site content as it is shared on social media sites. The front page of our site is a Views Page, feature only the most recent piece of content. We would like some of the info from this featured node to be included in the meta tags for the home page of the site.

What I'm wondering is -- How can I include meta tags specific to the **first result** from a View?

Alternately, can anyone suggest an alternative approach to either featuring the most recent piece of content on the home page that would solve this problem?

Thanks!

# Answer
Found this thread, which was very helpful:

Metatags and Commerce - pass taxonomy metatags to commerce product view

I adapted that approach to have metatag generate the tags from the first entity returned by the view:

```
/*
 * Implement HOOK_views_post_render to run code for each view render
 */
function THEME_OR_MODULE_views_post_render(&$view, &$output, &$cache) {
  // check for a particular view and view display page
  if ($view->name=='YOUR_VIEW' && $view->current_display == 'YOUR_VIEW_DISPLAY') {

    // retrieve the first node in the view
    $entity_type = 'node';
    $entity = entity_load($entity_type, $view->result[0]->nid);
    $language = entity_language($entity_type,$entity);

    // Generate metatags output
    if ($tags = metatag_generate_entity_metatags($entity, $entity_type, $language, 'YOUR_ENTITY_DISPLAY_MODE')) {
      list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
      $instance = "{$entity_type}:{$bundle}";

      // register the term's metatags
      metatag_page_set_metatags($instance, $tags);
    }
  }
}

```

Here is alternate code which doesn't rely on the Metatag module, and allows for more finely tailored meta tags based on view results:

```
function HOOK_preprocess_html(&$vars) {

    // only operate on the front page
    if ($vars['is_front']) {

        // get the view results
        $view_results = views_get_view_result('YOUR_VIEW_NAME','YOUR_VIEW_DISPLAY_NAME');
        // load up the first node
        $node = entity_metadata_wrapper('node',$view_results[0]->_field_data['nid']['entity']);

        // get some data
        $title = $node->label();

        // some fields may require more processing
        $description = trim(drupal_html_to_text($node->field_description->value()['safe_value']));
        $image = image_style_url('YOUR_IMAGE_STYLE',$film->field_image->value()['uri']);

        // generate and output the meta tags
        $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' =>  'og:title',
          'content' => $title,
        )
        );
      drupal_add_html_head($tag, 'og_title');

        $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' =>  'og:description',
          'content' => $description,
        )
        );
      drupal_add_html_head($tag, 'og_description');

        $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' =>  'og:image',
          'content' => $image,
        )
        );
      drupal_add_html_head($tag, 'og_image');
    }
}

```
> 0 votes

---
Tags: views, organic-groups, meta-tags
---


title: Search box label

text:
# Question
Title: Search box label
I am using the code found on https://www.drupal.org/node/154137, and I added this code to my template.php file.

```
function sample_theme_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
}

```

The search box label is successfully changed from "Search" to "Go!" However, when a search is executed, the search results page (/search/node/search\_term) displays the *Search* label (even after a page refresh). I'm certain template.php should be overriding this.

Why isn't the *Search* label overridden from my code?

# Answer
> 1 votes
With `sample_theme_form_search_block_form_alter()` you are just altering the form whose ID is search\_block\_form, which is different from the form you see in that page, whose ID is search\_form. The *Advanced search* part is added from `node_form_search_form_alter()` (another implementation of `hook_form_FORM_ID_alter()`), so your hook needs to run after it, or you will not see the *Advanced search* part.

I would use the following code.

```
function sample_theme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['actions']['submit']['#value'] = t('GO!');
  elseif ($form_id == 'search_form') {
    $form['basic']['submit']['#value'] = t('GO!');
    // The Node module could not have added its form fields, so
    // check its submit button does exist.
    if (isset($form['advanced']['submit'])) {
      $form['advanced']['submit']['#value'] = t('GO!');
    }
  }
}

```

Keep in mind that, since you are implementing the alter hook in a theme:

* It is invoked after all the module hooks, so also `node_form_search_form_alter()` has been invoked, and you are surely going to alter its submission button too
* alter hooks implemented by themes are invoked only for the theme currently used for that page, and its base themes; this is different from the hooks implemented by the modules, since all the hooks implemented by enabled modules are going to be invoked.

The last point is particularly important if there is a module that is changing the theme used for a page by implementing `hook_custom_theme()`, or when the theme for which you are implementing that alter hook is used for the administrative pages, and not the search page.

# Answer
> 1 votes
Instead of trying the code in template file try the following code in a custom module.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "your_required_form_id") {
    $form['actions']['submit']['#value'] = t('GO!');
  }
}

```

Hope this will help you

---
Tags: 7, theming
---


# Question
Title: How do I show a view item as grid and view item as list, dynamically?
I have created a view to display list of user with their details, and I want to display a widget on views display page which shows item as **view item as grid** and **view item as list** dynamically.

How do I achieve this?

# Answer
Install and configure the Views Mode module.

> A Drupal Views display plugin which provides alternate display modes that can be switched to for a single View. This allows exposed filter parameters or contextual filters to be kept active while switching display mode.

To get this module to work, follow these simple steps:

1. Activate the modules.
2. Create a view.
3. Select your view, then create 3 different display, 1 page and 2 modes (one of the mode should be identical to the page display, since it's the 'default' mode).
4. Within the Advanced settings of the mode displays, you will find a new section called 'mode settings'.

4a. Attach your modes to your page's view

4b. your mode id is a value that'll be displayed within the url, therefore use only lowercase and normal chars (e.g. 'stickers').

4c. your mode name is the one that'll be displayed in your mode changer block, this can be anything.

4d. For consistency, change the system names of your view's mode displays for their mode ID (4b), they'll be easier to identify.
5. If everything's going well, visit admin/config/search/purl.

5a. You should see 3 tabs (param, modifiers & types).

5b. Select the third tab first (types) and select the 'query string' option.

5c. Within the Settings tab, select the 'Query string' modifier type, and write 'mode' in the 'key' field (this is the word that'll be displayed within your url, in my case it would look like www.site.com/view?mode=stickers).
6. Now all you need to do is to add the 'Views mode links' block to your view's page (you should see links appearing on your view's page).

This module does not work with an AJAX enabled pager.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do I theme a link with twig for a specific content type?
I'm trying to create a custom file-link.html.twig for a particular content type. I've looked at https://www.drupal.org/node/2354645 which doesn't link plugin theme twigs like file-link but tried `file-link--<CONTENTYPE>.html.twig` anyway. It doesn't work.

None of the variables passed include the node or content type. Any ideas on how to proceed?

# Answer
There are a number of things you would need to do to accomplish this.

1. Enable Twig debugging
2. Create a hook theme suggestions preprocess function
3. Get the node object within your theme hook.
4. Craft the theme hook suggestion to get a template name with the node type in it.

Once you have Twig debugging enabled, you can inspect your file link. As a default for file\_link, I see:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'file_link' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/field/file-link.html.twig' -->

```

In my case, I use Classy as a base theme for my sub-theme, thus the classy path above. but what is missing here is any useful theme hook suggestions out of the box. Next we will remedy that.

Since we are given the theme hook name above, I can craft the theme hook suggestion based on that and by getting the node type and incorporating it into the theme hook suggestion. (see function hook\_theme\_suggestions\_HOOK\_alter)

My theme hook alter then would be:

```
  function MYTHEME_theme_suggestions_file_link_alter(&$suggestions, $vars, $hook) {

  // Get the node type.
  $node = \Drupal::routeMatch()->getParameter('node');
  $type = $node->getType();

  // Create the theme hook suggestion.
  $suggestions[] = 'file__link__' . 'type_' . $type;

}

```

Once I do this and `drush cr`, I will see my new theme hook template suggestion as such:

```
<!-- THEME DEBUG -->
    <!-- THEME HOOK: 'file_link' -->
<!-- FILE NAME SUGGESTIONS:
   * file--link--type-news.html.twig
   x file-link.html.twig
-->

```

In my case, my node type is "News" and you can see that in the template suggestion name:

```
file--link--type-news.html.twig

```

Now you can create that file and theme away! For more insight on this, I just wrote a blog post about this: Drupal 8 Theming Tutorial: How to Craft Custom Theme Hook Suggestions and Templates
> 9 votes

# Answer
You have a great answer from @Danny-Englander how to get the theme suggestion for twig. But I think the question is too narrow, it should be broader, without twig:

How do I theme a file link for a specific content type?

To do this, put a class with the content type in the `<article>` tag in node twig and a class for the file link in file\_link twig. Then use css to select all file links inside this article tag. You can use the same selectors for javascript.

If you use the classy theme you should already have set the classes.

The reason for this is, that the node can be displayed in different ways. For example as an entity reference or inside a view. Then you will get a wrong routeMatch or no routeMatch at all. By using the article tag you can deal with this flexible. You can have multiple nodes in one page and all can have different content types.
> 1 votes

# Answer
I found a solution which worked in this situation, and so am posting for future reference.

I added this to our custom module:

```
/**
 * Implements hook_template_preprocess_default_variables_alter().
 */
function MYMODULE_template_preprocess_default_variables_alter(&$variables) {

  /** @var Node $node */
  $node = Drupal::routeMatch()->getParameter('node');
  if ($node) {
    $variables['nid'] = $node->id();
    $variables['node_type'] = $node->getType();
  }

}

```

then took a copy of `file-link.html.twig` into our custom theme, and added:

```
{% if (node_type == 'CONTENTTYPE') %}
    <a class="filelink" href="{{ link.url }}" title="{{ description }}">
        <img src="/const8/img/icon-pdf-128.png" alt="Download PDF" title="" class="img-responsive" style="float:right;">Download PDF
        <span class="visible-xs-inline-block">({{ file_size }})</span></a>
{% else %}
  {# All other content types.... #}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: set default timezone, date first day and date format medium via drush
Is there is away to set :

1. **default timezone**
2. **date first day**
3. **date format medium**

via **drush** instead of doing it via drupal web interface ?

# Answer
There is no specific command to set default value. You need to set those variables using drushcommands.

For Drupal 7 version you can use below commands.

1. To set default timezone you can use

drush vset date\_default\_timezone 'Europe/London' -y

2. To set date first day you can use

drush vset date\_first\_day 1 -y

I hope this helps.. :)
> 2 votes

# Answer
You can get a list of variables using `drush variable-get`.

If you want list of date specific variables then you can run `drush variable-get date`

To set a variable using drush you can use this command :

`drush variable-set <variable name> <value>`.

So for example, to set `site_mail`, you can run

```
drush variable-set site_mail youremail@example.com

```

Hope that helps!!
> 1 votes

# Answer
```
**1.date first day**
drush vset date_first_day 0 -y  - set first day of week as sunday

**2.default timezone**
drush vset date_default_timezone 'Europe/London' -y

3. **date format medium**
drush vset date_format_'name' m/d/Y - H:i   - name( format name long or short or medium)

```
> 1 votes

---
Tags: drush, datetime
---


# Question
Title: Adding two contextual filters (Content : nid)
I want to display two type of contents : News and Events. So I added them in the filters criteria. This works great. Now I want them to be further filtered on the basis of the category the News and Events lie in. For example, I only want to display News and Events having category "xyz". So what I did is, I added a reverse relationship for News and a contextual filter of Content : nid having the relationship that I made. This works OK and shows the desired news. BUT when I try to add another relationship and contextual filter, all the data disappears.

Any help in this regard would be highly appreciated! Thanks!

Here are the sceenshots :

# Answer
> 0 votes
When you add two contextual filters, views expects to receive two contextual filters. Currently in your preview area you are only supplying one (you need to add the second contextual filter (article filter: content nid) as well and separate them with a `/`). If you use the `Provide nid from url` filters it might work on the page, but in the preview you still need to provide both values.

However this is not the correct way to proceed, you should be doing something like this:

Since your block should only show on the industry page, you need to obtain the nid of the industry you are looking at. Use one contextual filter, and fill if with the default value: `content id from url`. This will load the industry nid you are looking at.

Then, since this industry has two different content types attached, you need to add relations to both of them. If the content relates to the industry (likely scenario) you should be using the reversed relationship as you currently do. If the industry links to the content, you should use the non-reversed relationship. I guess you did this step right.

The biggest problem here is that you do not use your relationships for the filters. So Your `content > -365 days` is not filtering the articles or news, but applies to the industry. The same happens with your content type. You want to display nodes of `articles` or `news`, but instead you filter the node you are looking at to be of those types (which fails as it an industry).

So edit your filters and set them to use the related content's fields. You can only set one relation for each filter, so you'd have to create each filter twice (once for articles and once for news). Then use the drop down button above the Filters section to create an `And / or` group and drag the items in a way so the type is of `article` or `news`.

---
Tags: views, theming
---


title: Insert a form to a Basic Page

text:
# Question
Title: Insert a form to a Basic Page
I created a contact form in Drupal 8 and would like to use that form on several pages across my website. Can I do something like Insert / Form or use some sort of shortcode to display the form?

# Answer
> 1 votes
Create a block for your theme with formblock and in visibility settings of your block put it where ever you want.

---
Tags: forms, 8
---


# Question
Title: How can I list all the IP address and referrers of visitors of a specific node?
The tracker module is active on the website and I want to get all the Track statistics of a node created.

`www.example.com/node/3/track` lists all the redirection etc. But what I want to do, is to get all IP addresses that visited this node:

In Track Tab I can see the logs but the IP address and the referrer details are not listed here, to see this info I have to visit the link (`www.example.com/admin/reports/access/24488` etc.) for per log listed in Track page.

**How can I list all the IP address and referrers of visitors of a specific node via Drupal interface, Views or via PHPMyAdmin etc.?**

# Answer
> 1 votes
Have a look at the Visitors module. It comes with various reports, such as reports about pages that have recently been visited, or that have been hit frequently, or about pages count per month, day of month, day of week, hour. And it also includes a ***Referrers report*** (for referrer type either internal, external, or both).

One of the included reports is the Recent hits report, a table with columns Date of visit, Title, Path and User ID of the visitor. If you follow any of the "details" links in that report, you'll get something that looks as in this example:

The demo site contains some sample reports (charts) available to anonymous users also.

You may also want to look at the visitors\_schema to get an idea of the data that actually get logged (recorded) by this module.

In case the delivered reports are not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module, and co-maintainer of the Forena module.

---
Tags: 7, views, nodes
---


# Question
Title: How to define an image style where images are the exact same dimensions (e.g. grid of square images), without cropping or distorting the image?
On my site, images of any shape can be uploaded, for example:

I want these to display in a grid where every image is the same size and shape (in my case, square) - due to the nature of the images, I don't want to use cropping and I don't want any distortion of the aspect ratio, but the backgrounds can be extended. This also needs to be applied to **the image itself**, not a CSS wrapper.

For example, I'd like the end result to look like this:

Everything I've tried using various combinations of "scale" and "resize" either doesn't give consistent final sizes depending on whether the original was tall or wide, or distort the image. Cropping isn't an option. How can I do this?

# Answer
If you don't mind applying a block background colour, this seems to be possible with Imagecache Actions module.

1. Download and enable the Imagecache Actions module and its `imagecache_canvasactions` submodule.
2. Add a normal "scale" action to the desired size (300 x 300). This keeps the aspect ratio.
3. After, add a "Define canvas" action, then set to the same dimensions under "exact size".
4. Make sure "Resize canvas under image" is ticked, choose an appropriate background colour, and go. This fills in any gaps to the desired size with whatever colour you choose (or transparency if you choose no colour).
> 2 votes

---
Tags: 7, media
---


title: Login success but logout fails

text:
# Question
Title: Login success but logout fails
I'm trying to customize login, logout functionality in my drupal site. My custom login function works fine by using the below code:

```
function my_module_custom_login() {
  $username = $_POST['username'];
  $pass = $_POST['password'];
  $uid = user_authenticate($username, $pass);
  $form_states = array('uid' => $uid);
  if(!empty($uid)) {
    $user_login = user_login_submit(array(), $form_states);
    return 'user is logged in';
  }
  else {
    return 'user is not logged in';
  }
}

```

After calling this function I checked the "Recent Log message" in my drupal reports it tells "Session open for user abc".

Here is my logout code:

```
function my_module_custom_logout() {
  module_load_include('inc', 'user', 'user.pages');
  user_logout();
}

```

Whenever I called this function the recent log message shows "Warning: session\_destroy(): Trying to destroy uninitialized session in user\_logout()" That call went as an anonymous call. So the current user can't be able to logout from the site. How can I overcome from this.

# Answer
> 2 votes
The way you've structured the logic, your function will return "user is logged in" as long as your credentials are correct, not if the user session was created (i.e. the user logged in). Your subsequent error about an uninitialized session confirms that a session isn't being created (i.e. an entry being inserted into the `sessions` table) or your session key/cookie isn't persisting on the subsequent logout call.

You need to debug why this isn't happening. Check the `drupal_session_regenerate()` function call to make sure a session entry is created and that your browser/client is receiving `SetCookie` header with the newly created session key. If the session is created, you need check why your browser/client isn't storing and persisting the session key made on your subsequent logout call.

---
Tags: 7, users
---


# Question
Title: how to show date filter by next 5 months via expose filter in drupal?
I have a content type with date fields . For date I am using date module. I have created a views in drupal 7 and using exposed filter. I need to show filter my data via month , Means I need to show months(next 5 months including current) in dropdown.

# Answer
> 0 votes
What you're wanting is *Grouped Filters*. It will let you set pre-defined discrete filters for your date.

Under the Views UI for your exposed data filter set **Filter type to expose** to *Grouped Filters*. You can set your arbitrary **label**, set your **operator** to *is between*, and **Value type** to *An offset from the current time...* in the date fields, you can use a relative PHP `strtotime()` format to specify a filter between the current date ("now") and 5 months into the future ("+5 month").

---
Tags: views
---


# Question
Title: Install a module that creates a content type with fileds via YAML
I am new to drupal 8, I have been using drupal 7 for quite some time and I used to write the code that creates content types and fields in hook\_install / hook\_update.

Now I am creating a module that creates a new content type with a few fields. I tried to do it with YAML config files but it does not create my fields. The code I have so far:

/module/custom/mymodule/mymodule.info.yml

```
name: My Module
description: Applies customizations for my website.
package: Custom

type: module
core: 8.x

dependencies:
    - breakpoint # toolbar dependency
    - image
    - link
    - taxonomy
    - toolbar

```

/module/custom/mymodule/config/install/node.type.article.yml

```
type: article
name: Article
description: 'Use <em>articles</em> for time-sensitive content like news, press releases or blog posts.'
help: ''
has_title: true
title_label: Title

settings:
    node:
        options:
            status: true
            promote: true
            sticky: false
            revision: true
        preview: true
        submitted: true

status: true
langcode: en

new_revision: true
preview_mode: 1
display_submitted: true

dependencies: {  }

```

And one of my fields: /module/custom/mymodule/config/install/field.field.node.article.image.yml

```
langcode: en
status: true
dependencies:
  config:
    - node.type.article
  module:
    - image
id: node.article.image
field_name: image
entity_type: node
bundle: mymodule
label: Image
description: 'A representative <em>image</em> for the current article.'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  file_directory: '[date:custom:Y]-[date:custom:m]'
  file_extensions: png
  max_filesize: ''
  max_resolution: ''
  min_resolution: ''
  alt_field: true
  alt_field_required: true
  title_field: true
  title_field_required: true
  handler: 'default:file'
  handler_settings: {  }
field_type: image

```

What am I missing? Why don't the fields get created at install time?

# Answer
> 4 votes
For a node type + fields + formatter/widget settings, you need:

* The node type, you already have that
* The field.storage.node.\* config entities for your fields. If they are shared with other node types/modules then it gets a bit complicated. You can't define the same default config as another module. You could make it optional config, but then all your config needs to be optional
* The fields themself, like the example the one that you already have.
* The core.entity\_form\_display.node.article.\* config entities for the different form displays, for node, probably just default.
* The core.entity\_view\_display.node.article.\* config entities for all the view modes you want. default, teaser, ...

Also, note that tis is *install* configuration. It will only get created when you install the module. There is no standard mechanism to update configuration when you change the files and the module is already installed. There are modules for that, like config\_update, features possibly also contains that.

If this is a custom module that you just need on a single site and want to use it for dev -\> staging -\> production (or whatever you call your environments) deployments, it's easier to use the global config folder for that. Create your config, export it, commit it, and then import again. That also does updates and deletions.

---
Tags: entities, 8
---


title: HREFLANG attribute add

text:
# Question
Title: HREFLANG attribute add
I am working on a multilingual site. I have to add **HREFLANG attribute** so that search engines like Google provide the proper response according to the language of the user and the region.

To implement this, I am using Alternate HREFLANG module which basically add HREFLANG attribute like this :

for all the three languages.

But I want to add language as well as region like this:

In the description of Alternate HREFLANG module description, they mentioned that if you want to alter this attribute, you can use **hook\_language\_switch\_links\_alter()** and **hook\_html\_head\_alter()** these hooks.

But when I dsm these, I didn't get the HREFLANG attribute.

Can someone help me to achieve this?

# Answer
I cant see what is in your "...which basically add HREFLANG attribute like this" and "But I want to add language as well as region like this."

I bet you want to replace, let's say, "en" to "en-GB" right? If so, you need to alter Drupal language ISO. Current is ISO 639, language+region is ISO 3166-1 alpha 2.

BTW for your question, you need something like this to locate the hreflang:

```
function YOUR_THEME_OR_MODULE_NAME_html_head_alter(&$head_elements) {
  drupal_set_message('<pre>' . print_r($head_elements,1) . '</pre>');
}

```

Clear cache and reload the page.

**UPDATE**

An easier way is by adding a custom language. E.g. visit `admin/config/regional/language/add`

Expand **Custom language** fieldset.
Enter your desired ISO 3166-1 alpha 2 language code to **language code** & **path prefix language code**.
Fill the rest (language name in English, native language name & Direction) as usual.
> 0 votes

---
Tags: 7
---


# Question
Title: User order views does not display orders for user despite permission
The user order views' access permission is "View own orders of any type". I have given this permission to authenticated users yet the user sees only this message "You have not placed any orders with us yet.". What am I missing?

# Answer
> 1 votes
You've most likely edited the View to include a new relationship - perhaps from line items to products - that adds an access check to the View's results that the user doesn't pass. If this is the case, open your View's "Advanced" fieldset, edit the "Query settings", and check the box to "Disable SQL rewriting".

---
Tags: 7, commerce
---


# Question
Title: How to display the summary (teaser) over the body in a full content view
I want to display a teaser on the top of each article under the title, as in following “full content” layout:

1. Title
2. Teaser (article summary)
3. Image
4. Body

Moreover the teaser should have its own formatting (for example italic and a bigger font)

I did not find any way to do that without editing tpl files or core files.

A solution would be to add a new field "article\_teaser" to my content type, then manage display in order to get my layout in “Full content” view. This works, but I do not like to have two teaser-fields in my input content form, because I should type two times the same text.

It seems that I cannot split the field body in its “text” and “summary” parts, but I can only display one or the other, but not both!

Is there any way (a module?) to do that?

(My environment: Drupal 7 with Zen sub theme.)

# Answer
> 10 votes
You can do this with Views. Create a view that overrides the paths for your content type. Set the display to *Fields* and then add the body field twice; set the first instance to display the teaser and the second instance to display the body. You can add the images in between. Views will also allow you to customize the CSS of the teaser/body fields easily (by default, Views provides a number of classes, and you can add additional classes if necessary).

For reference: Node One series of video screencasts on using Views

# Answer
> 4 votes
on drupal 7:

In the field Body you can use 'rewrite result' and use in the 'replacement patterns' this:

```
[body-summary]

```

and this this will display the full summary.

# Answer
> 3 votes
Views can definitely do the job. But I think it is a little bit overkill for this requirement.

Another way to achieve that is implement hook\_field\_extra\_fields() and hook\_node\_view() in your custom module.

```
/**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {
  // Put the content type you want to display summary field here.
  $content_type = 'page';

  $extra['node'][$content_type]['display']['body_summary'] = array(
    'label' => t('Body summary'),
    'description' => t('Display body summary.'),
    'weight' => 0,
  );

  return $extra;
}

/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {
  // Put the content type you want to display summary field here.
  $content_type = 'page';

  if ($node->type == $content_type) {
    $summary = field_view_field('node', $node, 'body', array(
      'type' => 'text_summary_or_trimmed',
    ));

    $node->content['body_summary'] = array(
      '#markup' => $summary,
      '#weight' => 0,
    );
  }
}

```

Clear the cache and you can go to the content type "Manage display" settings to drag and drop to place the "body summary" field. For example `admin/structure/types/manage/page/display`.

# Answer
> 0 votes
For content type redefinition you need to look at Panels because one of the function of Panels is exactly redefining the basic look of certain Content Types (or information based on other selection criteria) Csaba

# Answer
> 0 votes
As Arjan noticed Cityreader's snippet produces the result but it does not render properly.

This variation worked for me:

```
 /**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {
  // Put the content type you want to display summary field here.
  $content_type = 'page';

  $extra['node'][$content_type]['display']['body_summary'] = array(
    'label' => t('Body summary'),
    'description' => t('Display body summary.'),
    'weight' => 0,
  );

  return $extra;
}

/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {
  // Put the content type you want to display summary field here.
  $content_type = 'page';

  if ($node->type == $content_type) {
    $summary = field_view_field('node', $node, 'body', array(
      'type' => 'text_summary_or_trimmed',
    ));

    $node->content['body_summary'] = array(
      '#markup' => $summary['#items'][0]['safe_summary'],
      '#weight' => 0,
    );
  }
}

```

# Answer
> 0 votes
If you are interested in no-code solution using Views and Display Suite module you can:

1. Create Views block with summary field on it. Under Contextual filter option in advanced settings you can set "Provide default value" option with type Content ID from URL.
2. Under Content Types -\> \[your content type\] -\> Manage display select Custom fields option (menu at the bottom) and create Custom block field from View you created in step 1.
3. On save Custom field will appear in the node type field list where you can choose in which region will it appear.

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