title: Menu items visible based on checkbox

text:
# Question
Title: Menu items visible based on checkbox
I want do show/hide menu items based on a checkbox that the user selects when he/she registers.

I use profile2 for register. Should I use an external jquery script that calls on page load or should I use a hook\_menu\_alter() in my template file? I am not too familiar with Drupal code yet and appreciate any input.

# Answer
> 1 votes
# Solution 1

Add a custom access callback to your paths, that will then determine whether or not the user should have access to a path.

**Important**: the code below will deny access to those paths. If you just wanted to show a slightly different menu and not block the access to those pages, see solution #2.

For example:

```
function YOUR_MODULE_menu_alter(&$items) {
  $items['your_path']['access callback'] = 'YOUR_MODULE_menu_access_callback';
}

function YOUR_MODULE_menu_access_callback(){
  global $user;
  if ($user->uid) {
    // Load user's Profile2 profile.
    $profile = profile2_by_uid_load($user->uid, 'NAME_OF_YOUR_PROFILE');
    // Allow access only if the user selected the checkbox.
    if (isset($profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) && $profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) {
      return TRUE;
    }
  }

  // This assumes that anonymous users should not have the access to a
  // particular menu.
  return FALSE;
}

```

This code would go in a custom module.

---

# Solution 2

Add a simple `theme_menu_link()` override in your front-end theme, and skip rendering of those links.

**Important**: this will not prevent the access to those pages, it will just skip rendering of those list items. Also, you must be rendering the links using a menu, e.g. place a menu block somewhere in your theme, and not render the menu directly (e.g. `theme('links__system_main_menu', ...)` or `theme('links__system_secondary_menu), ...)`).

For example:

```
function YOUR_THEME_menu_link($variables) {
  global $user;
  $element = $variables ['element'];
  $sub_menu = '';

  // Exclude certain paths.
  if ($user->uid) {
    // Load user's Profile2 profile.
    $profile = profile2_by_uid_load($user->uid, 'NAME_OF_YOUR_PROFILE');
    // Allow access only if the user selected the checkbox.
    if (!isset($profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) || !$profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) {
      // Define the list of paths that should be excluded.
      $paths_to_exclude = array(
        'sample',
      );
      if (in_array($element['#href'], $paths_to_exclude)) {
        // Stop processing here, meaning this list item will not be included in
        // the menu.
        return;
      }
    }
  }

  if ($element ['#below']) {
    $sub_menu = drupal_render($element ['#below']);
  }
  $output = l($element ['#title'], $element ['#href'], $element ['#localized_options']);
  return '<li' . drupal_attributes($element ['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

This code would go in the `template.php` file of your front-end theme.

---
Tags: 7, routes, forms
---


# Question
Title: Disable double confirmation for Simplenews
I have a simplenews registration block on my site. If people sign up for a newsletter, they receive a mail with a confirmation link. When they click on the link they come to a page with another confirmation button, which must be clicked if you realy want to register.

Thats the default behavior called Double-Opt-In in simplenews.

What I want for registration ist that you receive a mail with a confirmation link, if you click it you come to the page which says something like 'You are registered!'. I want to disable the need of this second button, any ideas?

Thanks in advance

# Answer
You need override the functionality of the simplenews module. Modify the simplenews confirmation form with a custom module using `hook_form_alter()`:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'simplenews_confirm_add_form') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'mymodule') . '/simplenews_autosubmit.js',
    );
  }
}

```

Then create a JS file, **simplenews\_autosubmit.js** in your custom module:

```
(function($) {
    window.setTimout(function(){ $('#simplenews-confirm-add-form').submit(); }, 3000);
})(jQuery);

```

You can set the 3000 to however long (in milliseconds) you want to wait between load and submit.

That should trigger a JS form submission upon loading the confirmation page.
> 1 votes

# Answer
There's a considerably easier way to do this, which is also documented in the README.txt for 6.x-2.x, but apparently not in 7.x-1.x.

In short, just change the confirmation mail templates and append /ok to the URL token.
> 2 votes

---
Tags: 7, emails
---


# Question
Title: How to translate products with Drupal commerce module?
I'm using Drupal commerce module. I don't see the Multilingual tab in the product type: product at admin/commerce/products/types/product/edit.

How do I make the product translatable? If that is not posible (hard to believe...) how can I just translate the product title?

# Answer
Entity translation allows to to translate products. To be able to translate the title, you will need to replace it with a field and use that instead. There is the Title project to help with that, but I haven't yet tried if it is compatible with Commerce products.
> 5 votes

# Answer
You need to enable the translation for the "product" content type.

**Enabling translation support for a content type**

1. Navigate to the Content types administration page (Administration \> Content \> Types in Drupal 6, or Administration \> Structure \> Content types in Drupal 7).
2. Select a content type you want translated, (in your case 'products') and select "edit", then "Workflow settings" for Drupal 6 or "Publishing options" for Drupal 7.
3. At the "Multilingual support" section, select "Enabled, with translation". Be sure to save each content type after enabling multilingual support.

For more information on this procedure and more I18N tips, see this page.

Hope that helps, happy coding friend.
> 0 votes

# Answer
Unfortunately, Entity Translation coupled with Title don't take you the whole way if you're using Commerce Kickstart, there's a bug that makes it a real bother to translate product fields. I've constructed a small guide for this purpose which also includes some code to work around that bug: http://storleden.se/blogg/how-translate-products-drupal-commerce
> 0 votes

# Answer
You can use the Internationalization for commerce product module.

Here is a quote about it (from the project page):

> ... allows you to translate commerce products. You need it if you have multilingual site with e-commerce via commerce module.
> 0 votes

---
Tags: commerce, i18n-l10n
---


# Question
Title: How to use different entity info per entity bundle?
I have three specific vocabularies that reside on different URIs and I need to have the Field UI configuration available for those URIs instead of only at one specific URI.

How could I configure this? The entity info is cached so alteration would not yeald the required result.

Bundle info only allows altering the label and some other unimportant value at this time.

This should basically act just like the entity uri override done by Forum module(although I think this is still not implemented yet).

Edit: As I have mentioned I have three vocabularies A, B and C. I have three routes for each of those vocabularies and in there I am calling the Drupal\taxonomy\Form\OverviewTerms form with vocabulary argument which is the name of the vocabualry that I want to display.

This gives me the vocabulary term list overivew. Now I want to add the vocabualry edit form as local task on those paths which I still can do(manually).

The issue is that I would also like to have the Field UI(ie. manage fields, manage form display, manage display) available at those routes/paths. And this is problematic since the field ui route is defined in the vocabulary entity annotation and is universal for all vocabularies.

The only way I think I can do this is by somehow duplicating what \Drupal\field\_ui\Plugin\Derivative\FieldUiLocalTask does but I was hoping for more simpler way by just having a different per-bundle information.

For more context/information see https://www.drupal.org/node/2460207

# Answer
> 0 votes
I don't really understand what you are asking, but it's not possibly to have different entity type definitions per bundle. The only exeption is the uri callback, that forum.module is using, as you mentioned yourself.

As I said, I don't understand/you don't explain what you're actually trying to achieve. Try to explain that, maybe there's a way to achieve your goal, just not in the way you imagined it.

---
Tags: entities, 8
---


title: Link's href value gets lost

text:
# Question
Title: Link's href value gets lost
I am trying to make a link on node by returning this array(The array is being formed in the function by the name buildLinks() ):

```
     $links[$key] = array(

    'title' => $definition['title'],

    'href' => $this->urlGenerator->generateFromRoute('module.show_format.' . $entity->getEntityTypeId(), array('module_format' => $key, 'entity' => $entity->id())),
  );

```

but on the page the link title is appearing but the link's href value gets lost(I mean title is appearing but it is not appearing as link).What am I doing wrong?

Update: The above array is being returned over here:

```
    return array(
    '#theme' => 'links__entity__module',
    '#links' => $this->linkBuilder->buildLinks($this->request->attributes->get($entity_type)),
  );

```

So is there is a possiblity that I am doing something wrong over here?

# Answer
Looks like the documentation around that theme function is out of date. Please open a bug report for that.

Have a look at template\_preprocess\_links, it is using `url`, not `href`. Also not that `url` is a `Drupal\Core\Url` object, not a path, so your code should look like this:

```
$links[$key] = array(
  'title' => $definition['title'],
  'url' => Url::fromRoute('module.show_format.' . $entity->getEntityTypeId(), array('module_format' => $key, 'entity' => $entity->id())),
);

```
> 1 votes

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


# Question
Title: How to establish a relation among two content types in drupal 7
Consider there are two CCK's **Products** and **Reviews**(reviews for a product) how to relate them?

There can be any number of reviews for a product. Hence i may want to **retrieve** all the reviews that belongs to a particular product OR **Create** a Review OR **Delete** OR **Update**.

Is there any module in drupal to accomplish this?

**UPDATE**

I tried this using **Entity Reference** module

First I created a **REVIEWS** CCK with the following fields **Name**, **Email**, **Review**, **Rating**, **Product**(This is the Entity Reference, So that it helps to determine the Product to which the review is belonged to).

**Products** CCk

Product Name, Product Description, Product Cost

Consider there are 3 products **A**, **B**, **C** and i want to review for Product **A**. I must add all the fields such as Name, email etc and have to select a Product from Drop down

This is Better. But the interesting point is How can i Retrieve all the reviews that belongs to Product **A** ?

If i create a **VIEW** to list all the Products i cannot get It's **reviews**.
Similarly if i create a view to list all Reviews i will get only **product name but not its details**.

Do any one have any Idea how to solve this?

Many Thanks.

# Answer
> 1 votes
It looks like you need Entity reference module:

> Provides a field type that can reference arbitrary entities

Just add product reference to review content type.

# Answer
> 0 votes
Entity reference is preferred choice as it's in D8 core and uses entity's architecture. For some reason Entity Reference module has less functionality then References module. I needed to filter referenced users by role and this can only be done with References.

# Answer
> 0 votes
In view add a relationship of product entity and select as required, after this add fields of product cck and select use the relation ship dropdown in field settings and in this way you should get all the needed data.

---
Tags: entities, nodes
---


# Question
Title: Custom module 'managed_file' variable info keeps disappearing
I have a custom module which allows a 'managed\_file' upload in the settings/config page. This works fine and displays as expected after uploading (with the filename linked, and a "Remove" submit button) but the value of the field keeps disappearing after some time. What am I missing?

Here's the code from the custom module:

```
  $form['custom_managed_jpg'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_managed_jpg',
    '#title' => 'Custom Image (JPG)',
    '#default_value' => variable_get('custom_managed_jpg', ''),
    '#upload_location' => 'public://custom_directory/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg'),
    ),
    '#description' => t('This is a custom image (jpg format).'),
  );

```

It appears to be a problem with the file\_load function. The variable is indeed saved, as I get a file ID when I `dpm()` the `variable_get('custom_managed_jpg')` (a number -- the `fid`). However, when I `dpm()` the result of `file_load($fid)` it is empty.

The strangest part is that this works as expected to start with, and the file will even remain between page loads and cache clears, but then after a few hours it just disappears as described above without any warning.

**UPDATE:**

It seems that the reason `file_load` doesn't return anything is that the directory (`public://custom_directory/`) is empty. At some point these files are being deleted from the directory but I have no idea why.

**UPDATE2:**

When I watch the `file_managed` table, I can see a new file added after uploading. The one difference between files uploaded here and those already in the table is that the `status` field is set to 0 instead of 1. I am guessing that could be part of the problem? How/where do I set the status to 1 programmatically?

# Answer
Scott's code is right (and is nearly identical to what I had) but the final step I was missing is in the form's submit handler, where I needed to grab the file that was uploaded and mark it as permanent, and add a file usage to tell Drupal the file was in use. By default Drupal treats uploaded files as temporary and they are deleted from the database and filesystem after 6 hours (when cron runs).

Here's the submit handler code.

```
function MODULE_admin_settings_submit($form, &$form_state) {
  global $user;
  if (isset($form_state['values']['custom_managed_jpg']) && $form_state['values']['custom_managed_jpg']!="") {
    // Load the file via file.fid.
    $file = file_load($form_state['values']['custom_managed_jpg']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    // Record that the module (in this example, "custom module") is using the file.
    file_usage_add($file, 'custom_module', 'custom_managed_jpg', $user->uid);
  }
}

```
> 2 votes

# Answer
If you're using Drupal 4.7 this will not work for you (hook\_settings is from Drupal 4.7).

Set up the menu item:

```
function MODULE_menu() {
  $items = array();

  $items['admin/config/PATH'] = array(
    'title'             => 'TITLE',
    'description'       => 'DESCRIPTION',
    'page callback'     => 'drupal_get_form',
    'page arguments'    => array('MODULE_admin_settings'),
    'access callback'   => 'user_access',
    'access arguments'  => array('administer site configuration'),
  );

  return $items;
}

```

Page Callback Function must return `system_settings_form($form)`:

```
function MODULE_admin_settings() {
  $form['fieldset_homepage']['custom_managed_jpg'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_managed_jpg',
    '#title' => 'Custom Image (JPG)',
    '#default_value' => variable_get('custom_managed_jpg', ''),
    '#upload_location' => 'public://custom_directory/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg'),
    ),
    '#description' => t('This is a custom image (jpg format).'),
  );

  return system_settings_form($form);
}

```

`system_settings_form` will save all form fields to the variable table and I think is the part you are missing.
> 1 votes

---
Tags: files
---


title: how do I activate the INSERT module?

text:
# Question
Title: how do I activate the INSERT module?
i want to use the INSERT module, to be abel to insert images into my content in a WYSIWYG style. I have downloaded & installed colorbox, have added a new field to my content type that allows me to upload images, I have installed CKEditor and Insert but when I upload a image in my added field, I do not get an *insert* button to place the image into my content. What am I missing?

# Answer
I was missing to check `Enable insert button` under the **INSERT** settings in my image field configuration where yo also select the **Enabled Insert styles**
> 2 votes

---
Tags: 7, media, javascript
---


# Question
Title: Colorbox Slideshow not Working on Mobile Devices
I have a Colorbox slideshow that doesn't want to work on mobile devices. Instead of opening up the slideshow modal on an image click, the browser opens the image in a new tab.

# Answer
The default behavior of Colorbox is to disable mobile functionality when the device's max width exceeds 480px. This functionality can be disabled with the Mobile detection option in ***Configuration \> Media \> Colorbox \> Advanced settings***.
> 2 votes

---
Tags: media, javascript
---


title: Embed view block with JSON data output

text:
# Question
Title: Embed view block with JSON data output
How can I embed the output of a view in another page, as a JSON Data Document, without stopping the page processing ?

I have a view with format set to *JSON data document* and am attempting to embed the block output in a node with `views_embed_view('nec_map_data','block')`.

This embeds the block but with *Views API mode* unchecked page processing is stopped at the JSON and the page doesn't render.

If I enable Views API Mode then the block output is wrapped in a div.

I would like the JSON output from the view to be assigned to a javascript variable in the node. How can I achieve this ?

# Answer
> 2 votes
You can do that by adding this function ( a customized version of the original views\_json\_get in the view\_datasource module ) in your template or custom module

```
/**
 * Gets JSON data from a View rendered in the JSON data document style.
 *
 * This is useful for when working with a JSON view in code.
 *
 * @param $name
 *   The name of the view.
 * @param $display_id
 *   The display of the view to use.
 * @param $args
 *   The arguments to pass to the view.
 * @param $raw
 *   If TRUE, the JSON data is returned as a string.  Otherwise, an object
 *   representation is returned.
 * @return
 *   The JSON data in the form of an object or a string or NULL otherwise.
 */
function views_json_noheader_get($name, $display_id = 'default', $args = array(), $raw = FALSE) {
  $view = views_get_view($name);
  if (!is_object($view)) {
    return NULL;
  }

   $view->display[$display_id]->display_options['style_options']['using_views_api_mode'] = 1;

  $preview = $view->preview($display_id, $args);
  $start_pos = strpos($preview, '{');
  $finish_pos = strrpos($preview, '}');
  $length = $finish_pos - $start_pos + 1;
  $json = trim(substr($preview, $start_pos, $length));

  if ($raw) {
    return $json;
  }

  return json_decode($json);
}

```

and get the result of your view by typing in your function:

```
$json = views_json_noheader_get('yourviewname', 'yourview json display id', null, true);

```

---
Tags: views
---


# Question
Title: How to keep theming of a view after changing type of view?
I am using a Drupal distro(Recruiter). The distro has a view of type "Rendered entity". However I am interested to change the type of the view to "Fields". However when I make the change,the default theming of the view dissapears.So I am interested to keep the default theming of the view. How can I do that?What shall I inspect?I am not a theming/css guy so any help would be appreciated. thanks!

# Answer
> 2 votes
Use the Theme:Information link in the edit view page

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

---
Tags: views, theming, distributions
---


# Question
Title: How can I rewrite the values of facets shown in the Current Search block?
I am using the Facet API for Solr search on my site.

The Facet API Bonus module provides a **Rewrite items** filter:

> Filter "Rewrite Items": Filter plugin to rewrite labels or other data of the facet items by implementing a new dedicated hook\_facet\_items\_alter (in a structured array, before rendering). Very handy to rewrite list field values or totally custom encoded facet values for user friendly output.

My site has three facets for boolean fields that have "Yes" or "No" options by default. Using this filter, I have rewritten them so that what is being selected is more clear:

```
function mymodule_facet_items_alter(&$build, &$settings) {
  switch ($settings->facet) {
    case 'field_friends':
      foreach($build as $key => $item) {
        if($item['#indexed_value'] == '1') {
          $build[$key]['#markup'] = t("Wants friends");
        }
        else {
          $build[$key]['#markup'] = t("Doesn't want friends");
        }
      }
    break;
    case 'field_money':
      foreach($build as $key => $item) {
        if($item['#indexed_value'] == '1') {
          $build[$key]['#markup'] = t("Wants money");
        }
        else {
          $build[$key]['#markup'] = t("Doesn't want money");
        }
      }

```

This works for the facets. But the problem is, if the user clicks **Wants friends** and **Doesn't want money**, then the Current Search block shows **Yes** and **No** (the unmodified facet values).

How can I rewrite the values of the facets show in the Current Search block too? As it is now, if a user selects multiple **Yes** and **No** values, they will have no idea what is actually being applied.

# Answer
> 0 votes
The feature is not available by default, but there is a patch to add this to Facet API.

---
Tags: search
---


# Question
Title: How to unpublish content when form submitted and notify a user by eMail?
In my Drupal 7 site I have content type `Job`.

Recruiters post information about open positions. Registered users can apply for any position by flagging node using the Flag module. I have built custom form for recruiters where they can manage applications. With this form recruiters can review profile and select candidate for position by submitting the form.

I want to hide/unpublish content when form is submitted and notify user via email that his application was confirmed. How can this be done programmatically?

Also I'm using Rules. If these actions can be implemented via `Rules`, how can I create event and conditions to perform actions against specific `user id` and `node id`?

# Answer
The Rules module is, for sure, your best bet for addrerssing this (therefor +1 for this question already ...).

Can you further enhance (edit) your question to explain what you have tried already using Rules? And what worked, or failed, and what the remaining questions are while using the Rules module? I.e.:

* which events?
* which conditions?
* which actions?

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.
> 1 votes

# Answer
If you want to keep it within your custom form, you can modify the `hook_form_submit()` to include a call to drupal\_mail() to send the message, and then the content un-publishing really depends on what content you want to effect.

I haven't used it before, but you could also take a look at Rules Forms Support if you want to keep it in Rules:

> Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.
> 1 votes

---
Tags: 7, nodes, forms, rules, flags
---


# Question
Title: Where is comment admistration template located?
I have a `Drupal 7` sub-theme based on `Bootstrap 3` theme, the comment admin page (http://www.example.com/comment/46849/edit?destination=admin/content/comment/approval) looks as shown below. It is however missing the ability to edit `Author` and `Url` fields. I would like to know which template file I need to edit to get this functionality.

# Answer
Following custom css in my sub-theme fixed this:

```
.region-content .comment-form fieldset.collapsible {
  float: left;
  position: relative;
  display: block;
  width:100%;
}

body .region-content .comment-form div fieldset.panel.panel-default .panel-heading {
display:block;
width:100%;
}
body .comment-form div .panel-collapse.collapse.fade {
display:block;
}

.comment-form div .form-item.form-item-subject.form-type-textfield.form-group {
  clear: both;
  display: block;
}

```
> 1 votes

# Answer
If, for some reason, the whole Author fieldset is hidden, be sure to check the HTML first, then you can also use the devel module for some dpm-ing in `yourtheme_form_comment_form_alter`.

Something like this should force the fieldset to be rendered:

```
function yourtheme_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['#access'] = user_access('administer comments');
}

```
> 2 votes

# Answer
As a partial alternative to the "comment admin page" which is "missing the ability to edit Author and Url fields": how about using something like the "Seven" theme as your "Administration theme"? By using that theme, and navigating to `admin/content/comment`, you can use the "edit" link to the right, so that you'll be able to edit fields like "Author" from there.

For the sake of completenes, be aware that there is a Bootstrap issue about styling comments which I believe is somehow related to this question (current status = postphoned). And it has this related issue: Add a comment.tpl.php to base theme, in which it says "There is no comment.tpl.php in the base themes, so it is pulled from core."

According to the first issue, it seems that it might be a good idea to use some of the typical alternatives for styling comments using bootstrap, or any of its sub-themes. I.e. something like Panels or Display Suite.
> 2 votes

# Answer
You can't edit author of the comment. Why would you want to change the name of the person who wrote the comment anyways? Unless... you want to allow anonymous user's to post comments, you would have to go into user permissions and check box that field.

If you want to add the ability for urls, you need to install a module for that.

Such as Wysiwyg or my personal favorite CK Editor
> 0 votes

---
Tags: comments, theming
---


# Question
Title: Integrating html code into existing Drupal 6 webform
I was provided some custom html code by my client’s email provider in order to automate getting the submissions into the client’s email system instead of the client having to enter them manually. The code provided looks like this:

```
    <form method='get' accept-charset='UTF-8' name='oi_form' action='http://suivi.lnk01.com/xyz'>
    Email: <input type='text' name='email'/><br />
    First Name: <input type='text' name='firstname' /><br />
    Last Name: <input type='text' name='lastname' /><br />
    <input type='hidden' name='Source' value='Newsletter Website' /><br />
    <input type='hidden' name='goto' value='' />
    <input type='hidden' name='iehack' value='☠' />
    <input type='submit' value='Subscribe' />
    </form>

```

I originally tried adding components (one for the first line and another for the 3 input lines after the fields) to the existing webform but it would not create a submission.

I then installed the webform remote post module, entered the target url value for the form, entered some data on the form, and submitted. It created a submission but on the client’s side, the first name, last name, and source fields are all blank. Has anyone had this same experience before ??

# Answer
> 0 votes
The submission made might be reaching client's side as POST variables, can you try to alter your form's submission method to "GET" instead of "POST".

From

```
$form['#method'] = 'post';

```

to

```
$form['#method'] = 'get';

```

---
Tags: webforms
---


# Question
Title: How to add multiple terms to a taxonomy reference field via feeds?
I would like to import a node with multiple taxonomy terms referenced in one of node fields. How can I do this with Feeds and Drupal 7 ?

# Answer
> 11 votes
Use the Feeds Tamper module to "explode" the comma-delimited list of taxonomy terms into individual references.

> Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below.
> Additional plugins can be added in separate modules or through the issue queue.

# Answer
> 0 votes
In my situation, the list is not a comma separated list. It is as follows:

```
<product>
    <category>Ship</category>
    <id>000032</id>
    <Description>The description comes here</Description>
    <list>
        <Destination>
            <DestinationName>Dest 1</DestinationName>
            <DestinationCountryISOAlpha3>US</DestinationCountryISOAlpha3>
        </Destination>
        <Destination>
            <DestinationName>Dest 2</DestinationName>
            <DestinationCountryISOAlpha3/>
        </Destination>
    <list>
</product>

```

I have a taxonomy called destinations and the list is already imported. Now how can I import Destinations list of a product as a term reference for the product node. I am using feed module, Feeds XPath Parser, and Feeds Tamper modules?

# Answer
> -2 votes
I'd like to suggest the Manage Multiple Terms module.

> Manage Multiple Terms provides a simple mechanism to add, update, delete many terms in the same time easily and quickly.

---
Tags: 7, feeds
---


# Question
Title: Feeds module is stripping html tags from xml
I tried my best to find an answer, but now I am finally stuck.

I am using Drupal 7.36, Feeds 7.x-2.0-alpha8 and used already 7.x-2.x-dev.

I am trying to **import a XML file** using the Feeds module with a simple structure:

```
<?xml version="1.0" encoding="UTF-8"?>
  <persons>
    <person>
      <number><p>12</p></number>
    </person>
    <person>
      <number><ul><li>2</li></ul></number>
    </person>
</persons>

```

But all I get after the import is the plain text 12 without any HTML tags.

I created a **custom Content type named Persons** and added one field to it, which accepts as text processing '**filtered text**'.

For this purpose I checked, that my **filtered text is accepting p, li and ul tags**. For that I edited all relevant text formats at: admin/config/content/formats

Anyway, after for the purpose of solving this issue I do actually just use Full HTML now, without any restrictions. If I type in HTML **manually** into a Person content entity the **HTML tag stays there** properly.

In the **Feeds module** I added an importer and chose under **Processor** (in my case node processor) 'texte-format' Full HTML. Here I added as a bundle my Person content type.

As **parser** I use XPath XML parser.

**Fetcher** is File-Upload.

The importer is properly attached to Persons content type under basic settings.

Anyway, always, when I import my XML, it strips off the HTML tags.

I do not use any WYSIWYG module.

What am I doing wrong?

# Answer
> 0 votes
I would suggest that you switch to QueryPath XML parser (you need Feeds extensible parsers and QueryPath) which supports RAW input which should solve your issue.

# Answer
> 0 votes
I appears to me that the issue you are trying to resolve, might be related to the issue described in issue # 2224643 (on D.O).

If that's the case, then you might want to try the commit mentioned in #22 in that issue (or the patch attached to #20 there).

---
Tags: importing-exporting, feeds
---


# Question
Title: Get node field image in " hook_node insert "
I'm getting the values of the node that I'm about to create with my custom module and the function " hook\_node\_insert " but I'm not receiving the data of my image like the path and name.

I'm just getting the fid, is that useful?

Is there any other method to get the data?

Thanks guys !

# Answer
Yes, the fid is a foreign key into Drupal's `file_managed` table. You can use the `file_load()` function to retrieve the file object which contains the name & path.
> 2 votes

# Answer
Drupal gives this by single file load from database:

```
$objFile = file_load($fid);
$imgabspath = objFile->uri; //getting file page (Example of image file absolute path)
print file_create_url($imgabspath);  //This is your file absolute url
$filename = objFile->filename; //getting file name

```

Still you are not getting result proper then there is some problem into $fid so confirm it by:

```
$node = node_load($nid);
// assuming file field has been added to the node has field_example_file machine name.
if (!empty($node->field_example_file)) {
  // $img will contain an array, which has the data of a file (file object converted to array I suppose..)
  $img = $node->field_example_file['und'][0];
}
$fid = $img['fid'];//This is your fid...

```

NOTE : file\_create\_url() always creates an absolute URL, either using the global $base\_path that you have defined, or using the one that Drupal guessed during bootstrap. Also note that file\_load() doesn't return title and alt attributes of field\_image.

Thanks!
> 3 votes

---
Tags: nodes
---


# Question
Title: Define a Panels visibility rule programatically
I'm trying to define a Panels visibility rule (access plugin) programmatically but I'm running into a problem.

My code is below. **This code works as a Selection Rule (on the Access tab), but when I try to add my access plugin as a Visibility Rule (on the Content tab), the plugin is added to the panel pane, but it doesn't show up in the UI under "Visibility rules." So there's no way to delete it, and the title isn't shown.**

I assume I failed to declare something that makes it show up in the Visibility Rules, but I haven't been able to figure out what. I was following this guide, but my plugin is simpler than the one in the example (no configuration necessary).

```
<?php
/**
 * @file
 * Plugin to check whether the value matches the proximity query string
 * https://drupal.stackexchange.com/questions/33336/what-are-ctools-plugin-content-type-access-etc-and-how-does-one-create-them/33337#33337
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Check proximity query string"),
  'description' => t('Returns FALSE if the proximity search query string is set'),
  'callback' => 'mymodule_checkproxquerystring_ctools_access_check',
  'settings form' => 'mymodule_checkproxquerystring_ctools_access_settings',
);

/**
 * Settings form for the 'term depth' access plugin.
 */
function mymodule_checkproxquerystring_ctools_access_settings($form, &$form_state, $conf) {
  return $form;
}

/**
 * Check for access.
 */
function mymodule_checkproxquerystring_ctools_access_check($conf, $context) {
  if (isset($_GET['d']) && (is_numeric($_GET['d']))) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

```

# Answer
I think probably that is due to the missing `'summary'` key from your `'$plugin'`. A simple access plugin to check if the current page can be defined as :

```
$plugin = array(
  'title' => t('Front page'),
  'description' => t('Is this the front page.'),
  'callback' => 'ctools_front_ctools_access_check',
  'default' => array('negate' => 0),
  'settings form' => 'ctools_front_ctools_access_settings',
  'summary' => 'ctools_front_ctools_access_summary',
);

/**
 * Settings form for the 'by parent term' access plugin
 */
function ctools_front_ctools_access_settings($form, &$form_state, $conf) {
  // No additional configuration necessary.
  return $form;
}

/**
 * Check for access.
 */
function ctools_front_ctools_access_check($conf, $context) {
  if (drupal_is_front_page()) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Provide a summary description based upon the checked terms.
 */
function ctools_front_ctools_access_summary($conf, $context) {
  return t('The front page');
}

```

The canonical reference of this could be found in the access plugins defined in the ctools module itself.
> 2 votes

---
Tags: panels, chaos-tool-suite
---


# Question
Title: How can I get a custom number of posts on the front page without views?
I need to have 16 nodes on the front page. Drupal only allows 1-10, 15, 20, etc. I'm using views now but it breaks the AJAX of the rate module.

# Answer
> 6 votes
The default front page article count is on the Site Information admin page @ **admin/config/system/site-information**. For some reason you can't select 16 as a value. If you have drush you can manually set the `default_nodes_main` value:

```
drush vset default_nodes_main 16

```

If you don't have drush you can set its value in the `variables` table.

# Answer
> 3 votes
Yet another option is available if you have the Variable module installed / enabled. That module is typically used/required for multilanguage sites using the i18n module, but of course you can also use the Variable module without using the i18n module.

When the Variable module is enabled, you should navigate to `/admin/config/system/variable`, and then select the tab "*Site Information*". There you'll find an option to specify "The maximum number of posts displayed on overview pages such as the front page."

Consider this option if (eg) you don't have Drush available (or can't use it for whatever reason), or as an alternative to modifying the settings.php file (2 possible alternatives mentioned in the prior answer/comments already).

---
Tags: 7, nodes
---


# Question
Title: Why cannot anonymous users vote, even though they have permission for it?
I installed the Fivestar module and added the *Stars (rated while viewing)* field in a content type.

I gave to the *rate content* permission anonymous users. They can see all the content and the voting widget, but they can't vote. Why?

# Answer
A possible explanation for this might be what is described in this issue on D.O: Fivestar Not Working for Anonymous Users with Cache Enabled.

A possible workaround for it is mentioned in Comment #9 of that issue, which states:

> ... When I set the author to anonymous on the field also set the field to allow users to vote on their own content, this appears to work as a crude work around.

Curious to hear if this somehow helps ...
> 0 votes

---
Tags: 7, rating
---


# Question
Title: Can't get "time ago" date format to work
From this blog post http://drupalmotion.com/article/time-ago-date-format-drupal

Function:

```
/**
 * Format date implementing hook_preprocess_node().
 */
function YOURTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $vars['date'] = format_date($node->created, 'custom', 'M jS, Y');
  $vars['time_ago'] = format_date($node->created, 'custom', 'c'); // 'c' is the ISO 8601 date format. Since PHP 5
}

```

Markup:

```
<abbr class="timeago" title="<?php print $time_ago; ?>"><?php print $date; ?></abbr>

```

with the jQuery TimeAgo plugin loaded.

```
/**
 * Timeago is a jQuery plugin that makes it easy to support automatically
 * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
 *
 * @name timeago
 * @version 1.4.1
 * @requires jQuery v1.2.3+
 * @author Ryan McGeary
 * @license MIT License - http://www.opensource.org/licenses/mit-license.php
 *
 * For usage and examples, visit:
 * http://timeago.yarp.com/
 *
 * Copyright (c) 2008-2015, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
 */

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function ($) {
  $.timeago = function(timestamp) {
    if (timestamp instanceof Date) {
      return inWords(timestamp);
    } else if (typeof timestamp === "string") {
      return inWords($.timeago.parse(timestamp));
    } else if (typeof timestamp === "number") {
      return inWords(new Date(timestamp));
    } else {
      return inWords($.timeago.datetime(timestamp));
    }
  };
  var $t = $.timeago;

  $.extend($.timeago, {
    settings: {
      refreshMillis: 60000,
      allowPast: true,
      allowFuture: false,
      localeTitle: false,
      cutoff: 0,
      strings: {
        prefixAgo: null,
        prefixFromNow: null,
        suffixAgo: "ago",
        suffixFromNow: "from now",
        inPast: 'any moment now',
        seconds: "less than a minute",
        minute: "about a minute",
        minutes: "%d minutes",
        hour: "about an hour",
        hours: "about %d hours",
        day: "a day",
        days: "%d days",
        month: "about a month",
        months: "%d months",
        year: "about a year",
        years: "%d years",
        wordSeparator: " ",
        numbers: []
      }
    },

    inWords: function(distanceMillis) {
      if(!this.settings.allowPast && ! this.settings.allowFuture) {
          throw 'timeago allowPast and allowFuture settings can not both be set to false.';
      }

      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow;
        }
      }

      if(!this.settings.allowPast && distanceMillis >= 0) {
        return this.settings.strings.inPast;
      }

      var seconds = Math.abs(distanceMillis) / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      function substitute(stringOrFunction, number) {
        var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
        var value = ($l.numbers && $l.numbers[number]) || number;
        return string.replace(/%d/i, value);
      }

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 42 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.round(days)) ||
        days < 45 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.round(days / 30)) ||
        years < 1.5 && substitute($l.year, 1) ||
        substitute($l.years, Math.round(years));

      var separator = $l.wordSeparator || "";
      if ($l.wordSeparator === undefined) { separator = " "; }
      return $.trim([prefix, words, suffix].join(separator));
    },

    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/\.\d+/,""); // remove milliseconds
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      s = s.replace(/([\+\-]\d\d)$/," $100"); // +09 -> +0900
      return new Date(s);
    },
    datetime: function(elem) {
      var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
      return $t.parse(iso8601);
    },
    isTime: function(elem) {
      // jQuery's `is()` doesn't play well with HTML5 in IE
      return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
    }
  });

  // functions that can be called via $(el).timeago('action')
  // init is default when no action is given
  // functions are called with context of a single element
  var functions = {
    init: function(){
      var refresh_el = $.proxy(refresh, this);
      refresh_el();
      var $s = $t.settings;
      if ($s.refreshMillis > 0) {
        this._timeagoInterval = setInterval(refresh_el, $s.refreshMillis);
      }
    },
    update: function(time){
      var parsedTime = $t.parse(time);
      $(this).data('timeago', { datetime: parsedTime });
      if($t.settings.localeTitle) $(this).attr("title", parsedTime.toLocaleString());
      refresh.apply(this);
    },
    updateFromDOM: function(){
      $(this).data('timeago', { datetime: $t.parse( $t.isTime(this) ? $(this).attr("datetime") : $(this).attr("title") ) });
      refresh.apply(this);
    },
    dispose: function () {
      if (this._timeagoInterval) {
        window.clearInterval(this._timeagoInterval);
        this._timeagoInterval = null;
      }
    }
  };

  $.fn.timeago = function(action, options) {
    var fn = action ? functions[action] : functions.init;
    if(!fn){
      throw new Error("Unknown function name '"+ action +"' for timeago");
    }
    // each over objects here and call the requested function
    this.each(function(){
      fn.call(this, options);
    });
    return this;
  };

  function refresh() {
    //check if it's still visible
    if(!$.contains(document.documentElement,this)){
      //stop if it has been removed
      $(this).timeago("dispose");
      return this;
    }

    var data = prepareData(this);
    var $s = $t.settings;

    if (!isNaN(data.datetime)) {
      if ( $s.cutoff == 0 || Math.abs(distance(data.datetime)) < $s.cutoff) {
        $(this).text(inWords(data.datetime));
      }
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (!element.data("timeago")) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if ($t.settings.localeTitle) {
        element.attr("title", element.data('timeago').datetime.toLocaleString());
      } else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
        element.attr("title", text);
      }
    }
    return element.data("timeago");
  }

  function inWords(date) {
    return $t.inWords(distance(date));
  }

  function distance(date) {
    return (new Date().getTime() - date.getTime());
  }

  // fix for IE6 suckage
  document.createElement("abbr");
  document.createElement("time");
}));

```

It just prints "May 18th, 2015" which reveals a more specific date when hovered over.

# Answer
> 2 votes
For a non-dynamic solution (doesn't change unless the page is refreshed) you can use the format\_interval() function like this:

```
$vars['time_ago'] = format_interval(REQUEST_TIME - $node->created) . t(' ago');

```

# Answer
> 1 votes
The Timeago module (available for both D6 and D7) can be used for this. Here is an excerpt from its project page:

> Uses the jQuery timeago plugin to create dynamically updating "time ago" dates. That is, the plugin turns static dates like "October 10, 2011" into "10 minutes ago" and updates the time ago every minute. This allows you to include "time ago" dates in cached content for most users while degrading gracefully for users with JavaScript disabled.
>
> Features included:
>
> * An option to turn node created times into timeago dates
> * An option to turn comment created/changed times into timeago dates
> * Tokens for node created time and comment created/changed times
> * A timeago date formatter option for use with dates anywhere
> * An API to turn any UNIX timestamp into a timeago date

Obviously, in this case you're looking for the feature mentioned in the first bullet above.

---
Tags: 7, datetime
---


# Question
Title: Sort a related products view based on product features
Hi I followed the intructions here for createa a view of related products for my commerce kickstart website, those related products are selected based on taxonomy vocabularies like texture, color, size, etc...

Right now the products are sorted by the title, but I do not want to sort them like that, I want to sort them based on a feature like color, texture, etc..

Allow me give you an example:

if I go the the product display of the product X that is of gray color, in the related products block I want to display first those that match the same color, so other related products that also have gray color will be displayed first.

Thanks for your help

# Answer
If you want to display those product first that matches the current product features, include all those fields in view accordingly and then apply views\_query\_alter function to override the order and sort according to current product.

For example, If you want to sort according to product color taxonomy term, Include the field (Products referenced) Commerce Product: color (desc) in sort criteria of view. Then write following code in module file

```
function MYMODULE_views_query_alter(&$view, &$query) {
  // condition for current view
  if($view->name == 'related_products') {
    //Get current node product color tid & override order query to sort according to that id
    $node = node_load(arg(1));
    $product_id = $node->field_product_reference[LANGUAGE_NONE]['0']['product_id'];
    $product = commerce_product_load($product_id);
    $query->orderby[0]['field'] = "commerce_product_field_data_field_product_reference__field_data_field_product_color.field_product_color_tid = '".$product->field_product_color[LANGUAGE_NONE]['0']['tid']."'";
  }
}

```

Let me know if you face any query regarding this.

Thanks!
> 1 votes

# Answer
I think contextual filters will help you. You can filter a view based on some arguments coming from the node on which the view is included. I don't have any experience with commerce kickstart, but this is a pure views functionality. See here: http://dannyenglander.com/blog/using-views-contextual-filters-create-related-content-block-drupal-7
> 0 votes

# Answer
I think this is not sort issue. It's not a normal sort. Also I can't imagine how to do that in views UI. You may need to write your own code by using entityfieldquery.
> 0 votes

---
Tags: 7, views, commerce
---


# Question
Title: How to create a view showing the products from a user's company?
I'm trying to create a relationship between a field on a user profile and a field on a content type.

User Profile Company Name - This is an entity reference that pulls names from a Company content type. Product - contains a field company which also pulls from a Company content type.

I'm trying to create a view which will show a user products his company carries. So the view is a user view. Contextual filter is the UID of the logged in user. Now trying to create the relationship to pull in fields from the product content type.

Basically, I'm trying to create a query that will show products where the `product.company` is equal to the `user.companyname`.

# Answer
> 2 votes
To achieve it with the current content architecture:

1. Create view of users.
2. Add a relationship `Entity Reference: Referenced Entity`. Mark it as required. This will make a connection between the user and the company.
3. Add another relationship `Entity Reference: Referencing entity`. Before saving add the value of the **Relationship** select list and select the relationship created in step #2. Mark this relationship as required too. This will make the connection between **user** company and the product.
4. You should now get the fields of products you could add to the view using the relationship you have built at step #3

# Answer
> 1 votes
The tutorial about Using Entity Reference in Views is about using Entity Reference in Views, primarily how to use with Views relationships. Some of the topics covered are:

* Entity references available as a relationship.
* Entity references available as a reverse relationship.
* Using relationships will give you duplicate rows – because that is how relationships work.
* Use entity references as contextual filters.
* When Entity API is enabled, you can choose the "show" setting entity, in addition to fields and content.
* ...

---
Tags: 7, users, views
---


# Question
Title: Why does my admin menu link for my custom module not get created?
I am creating a module in Drupal 7. The module is working well now, but I doesn't create an admin menu link.

I used the following code:

```
<?php
function question_mark_menu() {
    $items = array();

    $items['admin/question-mark'] = array(
        'title' => 'Question mark',
        'description' => 'Manage your question mark',
        'page callback' => 'question_mark_page',
        'access arguments' => array('administer question mark'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
?>

```

I tried to clear my cache but nothing works.

What is wrong in my code?

# Answer
The path for the configuration menu is at admin/config, so try this:

```
function question_mark_menu() {
  $items = array();

  $items['admin/config/question-mark'] = array(
    'title' => 'Question mark',
    'description' => 'Manage your question mark',
    'page callback' => 'question_mark_page',
    'access arguments' => array('administer question mark'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

```

Also, make sure your user has the 'administer question mark' permission that you have specified.
> 1 votes

---
Tags: users
---


# Question
Title: How to import multiple terms from XML into a node?
I am trying to import all the Destinations as taxonomy terms using following XML. In my situation, the list is not a comma separated list. It is as follows:

```
<product>
    <category>Ship</category>
    <id>000032</id>
    <Description>The description comes here</Description>
    <list>
        <Destination>
            <DestinationName>Dest 1</DestinationName>
            <DestinationCountryISOAlpha3>US</DestinationCountryISOAlpha3>
        </Destination>
        <Destination>
            <DestinationName>Dest 2</DestinationName>
            <DestinationCountryISOAlpha3/>
        </Destination>
    <list>
</product>

```

I have a taxonomy called destinations and the list is already imported. Now how can I import Destinations list of a product as a term reference for the product node. I am using feed module, Feeds XPath Parser, and Feeds Tamper modules?

# Answer
> 0 votes
I finally found a way to achieve this goal at least for my use case. Publish my solution here for anyone to use if required.

My Settings for XPath XML parser :

```
Context -> //product/list/Destination
Product id -> ../../id
List of ports -> DestinationName # This is a term reference field which well have multiple terms per product

```

Then mapped all required fields as normal.

I created a small module with `hook_feeds_after_parse()` hook (I will use "My module").

My module has one `.info` file and the `.module` file.

```
function my_module_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
    $current_id = -1;
    $cuurent_destination_list_final = '';
    foreach($result->items as $key => $row) {
        if($current_id !== $row['xpathparser:0']){
            $cuurent_destination_list_final = '';
            $current_id = $row['xpathparser:0'];
        }
        if($cuurent_destination_list_final === ''){
            $cuurent_destination_list_final = $row['xpathparser:1'];
        }else{
            $cuurent_destination_list_final = $cuurent_destination_list_final . ',' . $row['xpathparser:1'];
        }
        $result->items[$key]['destination_list_final'] = $cuurent_destination_list_final;
    }
}

```

What this module does is it creates a comma separated list of destinations. Once we set $result-\>items\[$key\]\['destination\_list\_final'\] (This builds a comma separated list of terms) using this module, we can refer destination\_list\_final from Feeds Tamper (Refer this).

Install and enable Feeds Tamper PHP. Add 3 pluggings to `xpathparser:1 -> List of Destinations`

1. Execute php code (This come from above installed module) -\> `return $item['destination_list_final'];`
2. Find replace - Use to remove double quotes (`"`)
3. Explode - Use to explode the comma separated list we created from the custom module.

That's it. It worked for me.

---
Tags: 7, feeds
---


# Question
Title: How can I import multiple taxonomy terms using Feeds and the Feeds XML Parser
Currently the xml feed looks something like this

```
<hotel>
    <hotel_facilities>
        <facility>Gym</facility>
        <facility>Restaurant</facility>
        <facility>Bar</facility>
    </hotel_facilities>
...
</hotel>

```

I've trying to import all the facilities as taxonomy terms using the Feeds XPath Parser but I am only able to import a single facility. I'm not sure if the module supports this. What currently happens when I set the context to hotel and the xpath query as hotel\_facilities/facility it results in the error:

> SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'Restaurant', 'Bar'' at line 1

If I use the query: `hotel_facilities/facility[1]` it returns and inputs the term into my taxonomy vocabulary, but I require all the terms to be added.

Is there a query/module or setting that I need to run; or is this a limitation of the Feeds/Feeds XPath Parser parser modules?

# Answer
> 1 votes
Feeds Tamper will sort this out (I know this for a fact, as I've done this in the last week).

Set your query to `hotel_facilities/facility` which will return a comma separated list of facilities (you won't see this array as you'll be exploding it. Feel free to `dpm()` it though). Using Feeds Tamper, you can explode this array.

Go to your feed, and there will be a "Tamper" menu item at the top. If you click this, and then go down whatever xpathparser if importing these facilities. Then click *Add plugin* and find the explode plugin (you can find it under *List*)

Don't forget to set your Feeds mapping to *Search taxonomy terms by: **Term Name*** and check the "Auto create" checkbox.

# Answer
> 0 votes
You have to change the base path to /hotel/hotel\_facilites/facility

Then it should work.

# Answer
> 0 votes
Chapabu has the right answer. I went a step further and made a Tamper plugin.

When I needed to set this up myself, I ended up having to add 3 filters to make it work (remove the xml tags, trim content, & drop empty elements). Since I have ~8 similar fields that would all need the same filters, I just wrote up a simple filter for Tamper that does this for me:

Copy this code and add it to `sites/all/modules/contrib/feeds_tamper/plugins/xml_explode.inc`. You can then select it from from the list of Tamper plugins. Read the notes on this filter for help.

```
<?php

/**
 * @file
 * Return an array of text from a set of XML nodes.
 */

$plugin = array(
  'form' => 'feeds_tamper_xml_explode_form',
  'callback' => 'feeds_tamper_xml_explode_callback',
  'validate' => 'feeds_tamper_xml_explode_validate',
  'name' => 'Explode XML',
  'multi' => 'direct',
  'category' => 'List',
);

function feeds_tamper_xml_explode_form($importer, $element_key, $settings) {
  $form = array();
  $form['info'] = array(
    '#markup' => t('In order for this to work, make sure you do these things:'
      . '<ul>'
      . '  <li>Write your xpath value to the parent followed by "\*" (eg <code>"Grandparent\Parent\*"</code>)</li>'
      . '  <li>Parse this node as "raw" xml (See <a href="http://goo.gl/cTv6Sc">http://goo.gl/cTv6Sc</a>)</li>'
      . '  <li>Make sure the xml node is only one level deep.</li>'
      . '</ul>'
      . '<b>Note</b>: This plugin is not intended for production.'),
  );
  return $form;
}

function feeds_tamper_xml_explode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $out = array();

  if(is_array($field)){
    foreach($field as $k => $string){
      $subject = new SimpleXMLElement($string);
      $out[] = trim( (string)$subject );
    }
  }

  $field = $out;
}

```

# Answer
> 0 votes
I recently found a way to achieve a goal very similar to this. Refer my post here if someone else finds a solution for this.

---
Tags: feeds
---


# Question
Title: Facebook Autopost. Why I still receive download library message?
I want to use Facebook Autopost. I have downloaded the facebok-php-sdk library and I have copied it to sites/all/libraries, but in status report I still receive this message. What should i do?

>

# Answer
Please make sure that the facebook.php file is found at sites/all/libraries/facebook-php-sdk/src/facebook.php.
> 1 votes

---
Tags: social-network
---


title: Storing images as nodes

text:
# Question
Title: Storing images as nodes
I am building a Drupal 7 platform where users can share images. In a nutshell, people should be able to comment on images and like them.

The way I realized this is by creating a custom content type called "image" and adding an image field to it. And then I grant users the permission to create "image" nodes.

However, yesterday I came across this Drupal 6 article http://drupal.org/node/325688 and it's section 'Images as nodes'. It introduces the Image module, which lets you upload images as nodes automatically. Unfortunately, the Image module hasn't been ported to Drupal 7.

1. Is this the clean way to implement images?

The article also mentions the solution that I made use of:

> For example, using Imagefield, you could create a custom content type that contains one CCK imagefield, and configure that field to "contain" (refer to) only a single file. However, note that this custom CCK node type would not be compatible with Image module or its add-ons, and should be named something other than "Image" to avoid confusion.
2. Is there any point in **not** naming your custom content type "image"? I mean, it would be a super suggestive name. And the Image module which would provide a content type with the same name will most likely never be ported to Drupal 7. So there should never be confusion.

Lastly, the article mentions that

> It is theoretically possible that, for sites with **lots** (say hundreds of thousands) of images, storing them all as individual nodes could result in a performance hit from the extra database overhead.
3. Well, storing **lots** of images is exactly what image sharing platforms are aiming at, isn't it? Is there a better way (in terms of performance) to store images in Drupal 7 while still making it possible for people to comment on them?

# Answer
> 1 votes
The image module does not exist in Drupal 7 because this functionality is added to Drupal 7 core.

1. Implementing images as nodes was a clean way to do this in Drupal 7. You may still do this in Drupal 7. However, Drupal 7 has gone a long way and offers the entity alternative. At Drupal 6 'everything can be a node'. At Drupal 7, 'everything can be an entity'.

Nodes were meant to be used for publishing text. They come with a lot of functionality that you may find redundant in your use case. All this extra functionality can slow down your site if you have thousands or millions of entries.
2. I am not sure I understand why you should not do this. It was probably a suggestion and module specific. In Drupal 7 you can name your content type anything you want.
3. As I told you before, using entities for storing images is a better alternative, as far as the performance is concerned. But then you should implement your own method of commenting.

**EDIT**: In Drupal 8 there is some advances made in decoupling the comment module from node. See this issue.

# Answer
> 0 votes
If I understand your issue correctly, Bulk Media Upload or Bulk File Nodes modules will do what you want.

---
Tags: 7, entities, media, files, comments
---


# Question
Title: Panels visibility rule: Hide if value is in the query string
I am trying to use a visibility rule in Panels to hide a block based on whether the query string has a parameter (`value=5`) or not.

Panels provides a **String: URL path** visibility rule by default, but this seems to only work for the URL path, not the query string.

Is there a way to add a condition to show/hide the block based on one of the parameters in the query string?

# Answer
Using PHP code is not recommended unless absolutely necessary. You never want to store the PHP code in database, you do that in the modules :-)

I would recommend you to write an ctools access plugin for the same; check the logic there and give access to users accordingly.

Benifits:

1. The code is more maintainable, and can be version controlled.
2. You could reuse the same visibility rule throughout the site wherever necessary.

Please check my answer here, for an example of a working access plugin.
> 4 votes

# Answer
Here's the ctools access plugin I made based on AjitS's advice:

It checks for whether the 'd' parameter in the query string has a numeric value or not.

```
<?php
/**
 * @file
 * Plugin to check whether the value matches the query string
 * https://drupal.stackexchange.com/questions/33336/what-are-ctools-plugin-content-type-access-etc-and-how-does-one-create-them/33337#33337
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Check for proximity in query string"),
  'description' => t('Returns FALSE if the value is in the query string'),
  'callback' => 'mymodule_checkproxquerystring_ctools_access_check',
  'settings form' => 'mymodule_checkproxquerystring_ctools_access_settings',
  'summary' => 'mymodule_checkproxquerystring_ctools_access_summary',
);

/**
 * Settings form
 */
function mymodule_checkproxquerystring_ctools_access_settings($form, &$form_state, $conf) {
  return $form;
}

/**
 * Check for access.
 */
function mymodule_checkproxquerystring_ctools_access_check($conf, $context) {
  if (isset($_GET['d']) && (is_numeric($_GET['d']))) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

/**
 * Provide a summary description.
 */
function mymodule_checkproxquerystring_ctools_access_summary($conf, $context) {
  return t('Proximity in query string');
}

```
> 2 votes

# Answer
you could use a PHP code selection and use $\_GET\['q'\] to parse the parameters.
> 1 votes

---
Tags: panels
---


# Question
Title: How can I create a page in Drupal that doesn't appear in the Drupal configuration menu?
How can I create a page in Drupal that doesn't appear in the Drupal configuration menu? For example: admin/config/handler, but the only way is the direct link. There is no link in the configuration menu. Which hook function should I use?

```
$items['admin/config/handler'] = array(
    'title' => 'Handler',
    'description' => 'Just some info here.',
    'access arguments' => array('administer site configuration'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('handler_form'),
    'type' => MENU_CALLBACK
);

```

# Answer
> 0 votes
You want to use `hook_menu()` and define a path with the type element set to MENU\_CALLBACK. The API docs linked above has an example for the path **example/feed**.

---
Tags: hooks
---


# Question
Title: Create a list of taxonomy terms which filter specific nodes
I would like to add a list of taxonomy "links" within my view so when ever a user clicks a specific term, only nodes tagged with that term will show up in the view.

Is there a module that can create a navigation of taxonomy terms within a view, to filter for specific nodes?

# Answer
There is no need to install module. create a field of taxonomy terms, in the view create a contextual filter of that field and it will work.

---

To create a navigation you need to loop through the taxonomy terms. it is something like this code. I am not able to execute the code right now to give you the exact code but using Devel module and looping (`foreach`)throught the objects you can get the terms and use them to build the navigation.

```
$name = 'YOUR_VOCAB_NAME';
$myvoc = taxonomy_vocabulary_machine_name_load($name);
print kpr($myvoc);

```

This code will print out the list of terms and their properties.
> 0 votes

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


# Question
Title: Should I use both caches pane and panels?
this is my first post here on SE after years and years of just using the platform for researching, I hope I do it right!

On a D7 site I use several cache systems/layers, mainly filecache, views cache, panels cache and boost.

I have good results with caching the panels only, but I recently read an article (link not at hand unfortunately) that recommended to use *both* caches, the one for the *panel* and the cache for *each pane* at the *same time*.

Does this bring me any performance gain?

Or should I either use the pane or the panels cache?

# Answer
If you panel already in cache, it doesn't matter that you panes are in cache, because cache of panel are alredy include panes.

But if you panel cache have lifetime around 1 hour and some panes have lifetime around 1 day (but not all) it can be usefull and take more performance to you.

So, cache of panels and panes for the same time doesn't take more effect then cache for panels only.
> 1 votes

---
Tags: panels, caching
---


# Question
Title: How to check validity of one time login url by Drupal 7 Services module?
I am developing a client side application and using AngularJS for this. I successfully registered a user.

Now my problem is that I cannot find a way to check the validity of one time login url or any end point provided by Services module?

Anybody an idea?

# Answer
**Note:** I have not tried this solution myself, but think it should work.

Some concepts about one time login URL

1. You cannot just visit the URL (or even request it via a service, or any other request like curl or wget) to check if it is valid. As the name it is for one time use only.
2. It is valid for 24 hours from time it is generated.

These couple of things need to be taken into consideration while validating the login URL.

The URL where the check (and login) of a user happens is `user/reset/%/%/%`, where the dynamic arguments are in order : user id, timestamp of the one time login url creation, and the hash of the password.

To implement your solution, I suggest you to create a custom service endpoint and implement the logic which is implemented in user\_pass\_reset.
You can just skip the part where the function actually logs the user in.
> 2 votes

---
Tags: 7, services
---


# Question
Title: Open Outreach distribution image not displayed & unable to upload new image
I installed Open Outreach via Acquia Dev Desktop on my Win 7 machine.

I am using Firefox, but the problem is also present in IE.

I deleted the second sample blog entry that came with the distribution. When I click the remaining blog (Welcome to our new website) the image that shows on the home page does not show on the blog page. Furthermore, when I attempt to upload a new image (after deleting the old one) I get a "Destination \*" message, but no box to type in next to it. When I click Next I get "An illegal choice has been detected. Please contact the site administrator.".

In the message log I see the following.

Illegal choice public in Destination element.

http://openoutreach-7-x-1-19.dd:8083/media/browser?render=media-popup&types%5B%5D=image&activePlugins=&enabledPlugins=&schemes%5B%5D=public&schemes%5B%5D=private&file\_directory=&file\_extensions=png+gif+jpg+jpeg&max\_filesize=&uri\_scheme=public&min\_resolution=&max\_resolution=1000x1000&plugins=undefined

I am a newbie. Can you give me simple instructions as to how to fix this?

Thanks!

# Answer
It appears that, by looking at the code that causes that "Illegal choice public in Destination element" error you got, "Public" is not an acceptable choice in the element with name "Destination". Not sure if this rings any bell, but maybe it helps somehow.

After you find the solution (reason) for this problem, you probably also solved the remaining error as you mentioned about ' ... "Destination \*" message ...'
> 0 votes

# Answer
After learning some more about how Drupal works I downloaded a fresh copy of Open Outreach and installed it alongside my troublesome copy. I discovered that I had accidentally messed with the front page view. I discovered that you can export and import views so I exported from the fresh copy & imported to the troublesome copy. Problem solved!
> 0 votes

---
Tags: media
---


title: Themes, blocks, and content ... Oh my!

text:
# Question
Title: Themes, blocks, and content ... Oh my!
I am a newbie to Drupal/Acquia Dev Desktop. Please excuse me if this is a dumb question.

I'm trying to grasp the relationship between themes (the one I chose is Corked Screwer), blocks, and content. In Corked Screwer there are images on the top half of the page/node and my content is at the bottom.

Am I understanding correctly that Content/main page content is where my typed-in content is displayed? I can control this with Visibility Settings/Content Types, etc. Yes?

How do I go about customizing the top half of the page to replace the default images with my own? Can you point me to a good video tutorial?

Thanks!

# Answer
> 0 votes
The "Corked Screwer" is a theme, and slideshow is created by Views Block. You should able to change the image by modify that slideshow page, because each slide is created by a slideshow node.

# Answer
> 0 votes
Yes, the **Main page content** block is where your content will render. Yes those visibility settings control on what page/content type/role will show that block content area. Typically, you want to leave this block alone since it's the main presentation of your content (what's the point of having a page if it doesn't have any content?).

It looks like the CorkedScrewer's default home page is more a demo template to demonstrate its block regions; you can't replace the images without overwriting the existing ones in its **images** folder. It can vary based on the theme developer, but usually you can control a theme's slideshow images from its settings page in **/admin/appearance**.

# Answer
> 0 votes
OK. Now that I've learned a bit more about Drupal and got into the inside of Open Outreach I decided to use the Open Outreach theme and have learned how it works. The Open Outreach them uses Panels & Mini Panels. I don't know much about them, but I learned from http://openoutreach.org/section/blocks is that this theme uses the Context UI module. I followed the instructions to customize my home page.

---
Tags: blocks
---


# Question
Title: How put a product display on the "Shop" not the "Home" page?
I have created all suggested types and objects for a *product display* (drupal commerce module) but it only shows on the "Home" page (which I have renamed "News"). I have a page named "Shop" for this purpose i.e. where I want the products to be on. How do I tell drupal to place the product display there?

Test site: http://marius-raphaelius.com/drup

(In fact, how does one edit the content of a page in general?)

Thanks a lot.

# Answer
> 1 votes
If I understand you correctly, you want to tell Drupal to use a different node for the home page. If this is what you mean you can do this by going to

Home -\> Administer -\> Site Configuration

You can change the node for the Default front page there.

---
Tags: commerce
---


title: Local or session language variables

text:
# Question
Title: Local or session language variables
I'm building a multi-language site using the internationalization set of modules. The problem is that I've done any queries to extract for example nodes or taxonomy terms with selection of language in the code(back-end) and what language reference or defauld language value I will use to compare or execute queries? Every user that is connected on the site I think they must have each a variable that indicates the language that the user have choosen and if there isn't, uses the browser language. I've tried with the global variable $language but this is for all the web site and it's user independent. I hope you understand my question! Thanks..!

# Answer
> 0 votes
You may want to add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

**If** no option for the '*User's Current Language*' is available in the filter criteria form, **then** verify your configuration at *Configuration -\> Languages -\> detection and selection*: the order should be 'URL, Default, User', and not something like 'Default, URL, User' (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Does this help?

---
Tags: i18n-l10n
---


title: Add sitemap.xml inside a view

text:
# Question
Title: Add sitemap.xml inside a view
I already generate my xml sitemap with drupal module "sitemap" now i wanted to show that sitemap inside a view.

It is possible to do this?

Thanks

# Answer
No, or at least not, with XML Sitemap & Views module. There is no Views integration with the XML Sitemap module. Given how both these modules work (a view being defined by base table & XML sitemap trying to generate a list of all indexable site paths), I think you'd be better off looking for another solution to embed all your site paths into the site.
> 1 votes

---
Tags: views, xml-sitemap
---


# Question
Title: How can I change the display of government field in drupal commerce shipping address?
I need to change the display of the order/shipping address of drupal commerce to render the city in a select list instead of writing the city, I need to upload in the database the list of the cites relevant to the governments of Egypt.

Are there a module may help to achieve this? as I don't have a PHP developing experience.

# Answer
> 0 votes
There is not currently a way to do this with the Address Field module. One of the Address Field maintainers has addressed that this in the works for 2.x release. In the meantime, the only way to do this is with a custom module. Someone has already written up an example of how to do this, specifically using Egypt as an example.

---
Tags: commerce, entities
---


# Question
Title: Rendered node display for anonymous users?
I would like to use a view field (node reference to an og group, configured to display a teaser) as rendered node inside a view and display the view to anonymous users. Do you know how to achieve this result ?

PS. Currently I can display it for admin user but for non-admin users the view field doesn't appear.

# Answer
> 2 votes
If it is working for admins, but not for non admins, you problem is most likely permission. Do the users have permission to see the node? Maybe they need a special permission to see nodes via relationships?

To fix this, you need to tweak your permissions.

If you want to change the way a field is rendered, either on an entity or in a view, you need to create what's called a field formatter, which essentially is a theming function for fields.

# Answer
> 2 votes
If you have the field\_permissions module installed make sure you check the settings for your view field and that the "view any value for field x" is checked for Anonymous users.

# Answer
> 0 votes
Try dumping the node, and see if there are any fields that your anonymous users can't see.

# Answer
> 0 votes
The display suite extras module creates a lot of field specific permissions. If some fields are missing, maybe its because the ds permission was not properly set.

**View Title on Node** is a new permission, for example. In my installation it was not set for anonymous users.

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


title: Adding Specific CSS to View

text:
# Question
Title: Adding Specific CSS to View
How would one go about trying to accomplish the following under Views in D7:

Say I have four different content types (apples, oranges, kiwis, and mangoes) which are culminated into one view listing them all on a single page.

I'd like to try and add a CSS class to both apples and kiwis that is unique to each (for example, all apples having a class of "red" and all kiwis having a class of "fuzzy") but I do not want to add classes to mangoes or oranges.

How would I let Drupal know to add these classes based on their content types?

# Answer
> 0 votes
You can use template\_preprocess\_views\_view\_fields function in order to do it.

---
Tags: views, nodes
---


# Question
Title: Views: Display users with a gmap attachment
I have location, gmap and profile2 modules installed on my site. In a profile type I have added a location field so that the user can add his/her location on profile edit.

I want to display all users with a map in the header. The map will have the markers for the currently displaying users.

For this purpose I have created a page view where I displayed all the users with a pager.

Then I added an attachment and select the style format as "Gmap" and in the settings I have tried both for Data source "Location.module" and "lat/long". And attached it to the page.

But the view does not display any map. Any one who have some idea about this?

# Answer
> 0 votes
Try using getlocation module. In order to show gmap with views, you need google api key. Getlocation module comes up with blocks and views with api key already embeded in code.

---
Tags: 7, views, location, google-maps
---


# Question
Title: Auto remove uber cart product attributes's option
Module:
https://www.drupal.org/project/ubercart

Scenario:
Product A: (has three options)
\- blue (Expire in May) (It has node to describe more about this option)
\- green (Expire in May) (It has node to describe more about this option)
\- red (Expire in June) (It has node to describe more about this option)

Currently I use Scheduler module to auto remove the node once its expire, but unable to remove product attributes's option. As a result, I use rule to send me email once node had been remove.

Question: Can I use rule to remove product attribute's option or is there any other solution?

Many Thanks.

# Answer
> 0 votes
Try to use Commerce Product Attributes module. I haven't use this module. But I hope you will get that you want.

> This module provides some enhancements to the Drupal Commerce attribute handling.
>
> The improvement contains:
>
> * Attribute field for line item
> * Edit option for attributes

**Or**

Try this Refer Link also if you will not getting any solution from above module.

**Or**

You can do this by adding below code to Ubercart Attribute module.

```
contributions/ubercart/uc_attribute/uc_attribute.module, line 831

```

uc\_attribute\_option\_delete

```
function uc_attribute_option_delete($oid) {
  // Delete the class attribute options.
  uc_attribute_subject_option_delete($oid, 'class');

  // Delete the product attribute options (and the adjustments!).
  uc_attribute_subject_option_delete($oid, 'product');

  // Delete base attributes and their options.
  db_delete('uc_attribute_options')
    ->condition('oid', $oid)
    ->execute();

  return SAVED_DELETED;
}

```

---
Tags: 7, ubercart
---


# Question
Title: Allow users to submit content that is approved before it is published
I want to allow users to submit the content to my site, but the content must be first approved, and then it can be published.

Is there a module that do this? Which code should I write for such module, if one doesn't exist?

# Answer
> 10 votes
You might want to try: http://drupal.org/project/workflow & http://drupal.org/project/formfilter

If you create a workflow you can set it to only allow users to create content in the 1st state, something like "needs review". Then, an admin can come in and progress to the 2nd sate, say to "published".

I used an action and trigger to automatically publish any content placed into the 2nd state.

You can use the form filter to disable the ability to set the content straight as published in the normal node edit form.

Ideally you will want some type of approval queue too, you can use the default Workflow summary but I think this requires views.

# Answer
> 0 votes
Another way to do this is the Revisioning module. If you set the content type to not be published by default, you can use this module to control publication as well as any revisions. It provides a view for administrators showing all revisions that are awaiting publication.

# Answer
> 0 votes
"Workflow" or "Revisioning", depends up on your requirements.

Workflow module provides state based content control, i.e., you can make your content flow across various states (Draft, Pending, Review etc.,) and various users, before you publish it.

Revisioning module creates a new revision for every edit made on a node, and finally you can publish it.

I suggest you to use the combination of both these modules, for a cleaner impact. This slideshare presentation would be helpful for you, read this before you proceed http://www.slideshare.net/mewren/workflow-revisioning-and-rules-in-drupal

But remember, this is a back and forth task. Choose carefully between workflow\_node and workflow\_field. Also, you may need to work around this issue http://www.ionsden.com/article/problems-workflow-and-revisioning-drupal

---
Tags: 7, nodes
---


# Question
Title: How can I modify a user's last access date using Rules?
**Goal**

I want to make a Rule that automatically changes the user account last-access date to "now" for certain users.

**Use case**

I have a view that displays users by last access date, but I need some users to consistently appear near the top of the search results. Previously, I simply assigned all the users that I needed at the top to a specific role, and then sorted the view so that that role came first, but the problem with such an approach is that the same users always appear at the top in the same order. I want the order to look a bit random, so I want to update the access date with a rule that automatically re-schedules itself every *x* hours.

**Problem**

I can write a rule that re-schedules itself. However, to update the "last access" date, when I use the **Set a data value** action, I receive the following message:

> The selected data property doesn't support writing.

How can I get around this and refresh the last access date in Rules? I can write a custom rules action if necessary, but I don't know what to put in the action to reset the access date.

# Answer
> 1 votes
Two options:

1. Just as you said, a custom rules action:

```
function MY_MODULE_rules_action_info() {
  return array(
    'MYMODULE_action_update_last_access' => array(
      'label' => t('Update last accessed timestamp'),
      'group' => t('Custom'),
      'access callback' => 'rules_user_integration_access',
      'parameter' => array(
        'account' => array(
          'type' => 'user',
          'label' => t('User'),
          'description' => t('User account whose last accessed timestamp will be updated.'),
        ),
      ),
    ),
  );
}

function MYMODULE_action_update_last_access($account) {
  // There might be another way to update the last accessed date, but you can
  // also do it directly in the database.
  //
  // NOTE: the code below will update the last access to current timestamp.
  // You could also do something like this, to get a random value in the last
  // 24 hours:
  //    $timestamp = rand(REQUEST_TIME - 24 * 60 * 60, REQUEST_TIME);
  $timestamp = REQUEST_TIME;
  // Update the data in database.
  db_update('users')
    ->fields(array('access' => $timestamp))
    ->condition('uid', $account->uid)
    ->execute();
}

```
2. Use `hook_cron()` implementation in a custom module. This can be cleaner if you don't need to configure this more than once.

```
function MYMODULE_cron() {
  // Decide how often you want to do this, e.g. daily, weekly, etc.
  // Below is an example for daily trigger.
  $last_updated = variable_get('MYMODULE_var_last_time_access_updated', NULL);
  if (!$last_updated || $last_updated != format_date(REQUEST_TIME, 'custom', 'z')) {
    // Define user IDs which need to be updated.
    $accounts_to_update = array(1, 2, 3);
    // Update them.
    foreach ($accounts_to_update as $account_to_update) {
      // See #1 above; I'll use a random timestamp in last 12 hours this time.
      $timestamp = rand(REQUEST_TIME - 12 * 60 * 60, REQUEST_TIME);
      // Execute the query.
      db_update('users')
        ->fields(array('access' => $timestamp))
        ->condition('uid', $account_to_update)
        ->execute();
    }
  }
}

```

---
Tags: rules, users
---


# Question
Title: drupal_mail to users selected from database
In my Drupal 7 site I use custom tableselect form to manage some events. User can review profiles of people who applied for event and approve their participation. I want to send them email notification via `drupal_mail` on form submission. I have implemented `hook_form_submit` and added following code

```
foreach ($values as $key => $value){

    $sql = db_select('users', 'u');
    $sql-> fields('u', array('mail'));
    $sql-> condition('uid', $value['uid']);
    $mail = $sql->execute();
    }
    foreach($mail as $m){
    dsm($m);
    drupal_mail('event_manager','event_approved', $m, language_default());
    }

```

But in this case I have an error :

> Warning: explode() expects parameter 2 to be string, object given in SmtpMailSystem-\>mail()

How can I fix the code to make it work?

# Answer
> 2 votes
On a first glance, it's because you are passing the whole object instead of the email address. Try this:

```
  $sql = db_select('users', 'u');
  $sql-> fields('u', array('mail'));
  $sql-> condition('uid', $value['uid']);
  $mail = $sql->execute();
}
foreach($mail as $m){
  dsm($m);
  drupal_mail('event_manager','event_approved', $m->mail, language_default());
}

```

# Answer
> 0 votes
In `drupal_mail()` function the third parameter should be the email address to whom you want to send email to.So pass the email address of user instead of $m.

---
Tags: database, emails
---


title: Behat and custom login pages

text:
# Question
Title: Behat and custom login pages
I'm trying to use Behat and Drupal for BDD, but I'm running into some authentication issues. Simple steps like:

```
Given I am logged in as a user with the "administrator" role

```

Fail because I'm using Drupal's CAS module, which essentially customizing the /user/login page. Any idea on how I can get past custom login pages with Behat?

# Answer
You can test login form in this way:

```
When I visit 'user/login'
And I fill in "username" for "name"
And I fill in "userpass" for "pass"
And I press the "Log in" button
Then I should see the text "some text"

```
> 3 votes

# Answer
I was able to figure it out. You have to make sure the "Make CAS login default on login forms" option in the CAS settings is not checked and don't have "user" page under the "Specific pages" redirect. I still need to figure out how to disable these options through Behat, instead of manually, then my tests will truly be automated. I will post a reply once I figure it out.
> 0 votes

---
Tags: users, testing
---


# Question
Title: How to point parent menu item to a link and sub menus too
Hi I have a main menu named Home and there a sub menus in it. When I click any of the menu item of sub menu the content of the sub menu displayed. But After that I can not go to home by clicking home menu as it contains sub menu and it does not point to home link hence its non clickable. My issue is that I want parent item to points to a link and sub menus too. Is it possible?. I am using bootstrap theme.

# Answer
You can do this by using below modules :

1. Path Breadcrumb

> This module is a solution for all problems with the breadcrumbs on your site!
>
> Path Breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!

2. Menu Breadcrumb

> By default, Drupal 6+ use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.
> 0 votes

---
Tags: navigation
---


# Question
Title: Drupal Commerce or Ubercart to sell subscription for user (not for sell product)?
I want to create a website like learning lessons, and user can watch this lessons when subscribe of this website .. like lynda.com

I studied drupal commerce and ubercart modules, but I still confuse which one is the best for this type of sites.

help me please thank you

# Answer
If you want to create a site like learning site. I think you can do this by using Course module.

> Create Drupal e-learning courses with any number of requirements for completion.
>
> There's a slideshow from Drupaldelphia and a video as well.
> 1 votes

---
Tags: 7, commerce, notifications
---


# Question
Title: How do I share views on multisite in drupal 8
Is it possible to have a multisite set up in drupal 8 and create view on Site A and have that appear on Site B? I cant find anything in drupal documentation for sharing views. I can share users, content, and taxonomy, but nothing else.

# Answer
Multisite sharing works by using the same prefix for certain tables. It's dark magic, especially in 8.x, with the automatically created entity and field tables.

Since all config is stored in the same table, that's not possible.

You *could* write a custom config storage controller that stores certain config in a shared table, but that seems like a very crazy idea to me.

Configuration can be exported/imported and probably doesn't change that often. There will also be modules like features and others that will make re-using configuration easier.

I would also strongly recommend to consider other options to share your content. I can't imagine that this works reliably in 8.x.
> 1 votes

# Answer
Here's a different approach. With CMI, you could export your view (when it has changed) on site A and import it on site B (using drush config-merge or rsync). I did this already with D8 testing sites and it worked nicely IIRC. Sure it's less flexible and granular than really sharing a 'live' view between 2 sites but chances that you want to update your view frequently are equally low, aren't they?
> 0 votes

---
Tags: views, 8
---


# Question
Title: Drupal not sending emails from contact form
For some reason my Drupal website does not sends email from contact form. Can you help me where could be a problem?

It also does not send emails to administrator for newly added comments.

Just to mention, that only email it sends is when registered user requests for new password.

Thank you in advance!

# Answer
There could be many reasons but here are a few things to check.

1. Check your logs. Watchdog may tell you the source of the error. For D7, it's at /admin/reports/dblog
2. Test other mail functions like the reset password link.
3. Make sure you have a valid email address set: The site email address (used when sending notification emails, and the default for most all modules that send emails) can be set via the Site Configuration \> Site information page (admin/settings/site-information).
4. Check your permissions if you are sending email from a module like webforms.
5. If you have SSH access to your server, test the mail settings from there.

\<?php
$to = "your@email.com"; // REPLACE
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "noreply@eample.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent."; Make sure to replace the "to" address, save it as mail.php, and run it using "php mail.php". If you get email from that, then the problem is specific to Drupal, and if not, then your server isn't sending email at all and you should contact your host.
> 3 votes

# Answer
If you are sending this emails from the same email account as the destination it is posible that the email is in your spam folder.

This is because your mail client does not recognize as their own.

Solution: check emails from the main account as not spam.

```
$my_module = 'foo';
$my_mail_token = 'bar';
$from = variable_get('system_mail', 'info@test.net'); // Fill your administrator mail here!
$message = array(
  'id' => $my_module . '_' . $my_mail_token,
  'to' => $from, // the same email account!
  'subject' => 'TEST EMAIL',
  'body' => array('test'),
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
  ),
);
$system = drupal_mail_system($my_module, $my_mail_token);
// The format function must be called before calling the mail function.
$message = $system->format($message);

if ($system->mail($message)) {
  // Success.
}
else {
  // Failure.
}

```
> 1 votes

# Answer
Sometimes it confuses that email at admin/config/system/site-information will receive the email from contact form.

For the contact form you can check Recipients Email at admin/structure/contact in the respective category.
> 0 votes

---
Tags: comments, emails
---