title: how to insert an array in another one?

text:
# Question
Title: how to insert an array in another one?
This is an index (of module services) I created a resource that index books on a home page of a mobile app( this is not the most important in my question) I want to get books that have same tid (from table taxonomy) and put them on an array ($livres) at this time when I return $livres it's ok, books are grouped well and no duplications, but after putting them on array $livres, i want to put the $livres on the array $sections, sections contain the "header" that is the name of the section, and the array $livres of every section : the result i want is : \[ { 'section' : 'A', 'livres':\[{'id\_book' : '1','title':'great book'},{'id\_book' : '2','title':'great book too'}\]},{'section':'B','livres':\[{...ect

```
function my_module_home_index(){
$sections = array();
$livres = array();

$home_livre = db_query("SELECT tax.name as section,field_categorie_tid as tid,field_title_value as titre ,field_prix_value as prix ,t.entity_id FROM {field_data_field_title} as t
    join {field_data_field_prix} as pr on pr.entity_id = t.entity_id
    join {field_data_field_categorie} as cat on cat.entity_id = t.entity_id
    left join {taxonomy_term_data} as tax on tax.tid = cat.field_categorie_tid
    ")->fetchAll();

foreach($home_livre as $book){
    if(!isset($livres[$book-> tid]))
    $livres[$book-> tid] = array();

    $livres[$book->tid][]= array(
        'id_livre'=>$book-> entity_id,
        'titre' => $book-> titre,
        'prix'=> $book-> prix
    );
    $sections[]= array(
        'categorie'=> $book-> section
        'livre'=> $livres[$book->tid]
    );
}
return $sections;
  }

```

This is a part of what postman returns :

```
{
"categorie": "A",
"livre": [
  {
    "id_livre": "109",
    "titre": "F",
    "prix": "4"
  }
]
  },
{
  "categorie": "A",
  "livre": [
    {
     "id_livre": "109",
    "titre": "F",
    "prix": "4"
  },
  {
    "id_livre": "110",
    "titre": "G",
    "prix": "43"
  }
 ]
},
{

"categorie": "A",
"livre": [
  {
    "id_livre": "109",
    "titre": "F",
    "prix": "4"
  },
  {
    "id_livre": "110",
    "titre": "G",
    "prix": "43"
  },
  {
    "id_livre": "111",
    "titre": "H",
    "prix": "6"
  }
  ]
 },

```

As you can see; Book number 109 appears every iteration of foreach, how to avoid that ?

This is what return $livres shows (just a part, whent tid : 41, array is grouping all books with this tid so it's ok):

```
"41": [
{
  "id_livre": "109",
  "titre": "F",
  "prix": "4"
},
{
  "id_livre": "110",
  "titre": "G",
  "prix": "43"
},
{
  "id_livre": "111",
  "titre": "H",
  "prix": "6"
},
{
  "id_livre": "115",
  "titre": "L",
  "prix": "4"
},
{
  "id_livre": "118",
  "titre": "O",
  "prix": "5"
}
  ]
  }

```

Thank you

EDIT : this is the result postman returns when i "range" the query with 0,5 : i want 5 books (livres) in every sections, did anyone knows how to range the first array (not the second one that contains livres)

```
"response": [
{
  "section": "roman policier",
  "id_section": "31",
  "livres": [
    {
      "couverture": "http://localhost/drupal/sites/default/files/Etude_en_rouge.jpg",
      "id_livre": "113",
      "titre": "Une étude en rouge",
      "auteur": "Arthur Conan Doyle",
      "prix": "8",
      "categorie": "30",
      "section": "31"
    },
    {
      "couverture": "http://localhost/drupal/sites/default/files/fables.jpg",
      "id_livre": "119",
      "titre": "Fables",
      "auteur": "Jean de La Fontaine",
      "prix": "0",
      "categorie": "30",
      "section": "31"
    },
    {
      "couverture": "http://localhost/drupal/sites/default/files/couverture-livre_2.png",
      "id_livre": "120",
      "titre": "lire_latin",
      "auteur": "ecri_latin",
      "prix": "33",
      "categorie": "30",
      "section": "31"
    }
  ]
},
{
  "section": "roman drole",
  "id_section": "32",
  "livres": [
    {
      "couverture": "",
      "id_livre": "114",
      "titre": null,
      "auteur": null,
      "prix": "444",
      "categorie": "30",
      "section": "32"
    }
  ]
}

```

# Answer
You could try this:

```
function my_module_home_index(){
  $sections = array();

  $home_livre = db_query("SELECT tax.name as section,field_categorie_tid as tid,field_title_value as titre ,field_prix_value as prix ,t.entity_id FROM {field_data_field_title} as t
    join {field_data_field_prix} as pr on pr.entity_id = t.entity_id
    join {field_data_field_categorie} as cat on cat.entity_id = t.entity_id
    left join {taxonomy_term_data} as tax on tax.tid = cat.field_categorie_tid
    ")->fetchAll();

  foreach($home_livre as $book){
    if (!isset($sections[$book->section])) {
      $sections[$book->section] = array(
        'categorie' => $book->section,
      );
    }

    $sections[$book->section]['livre'][] = array(
      'id_livre' => $book->entity_id,
      'titre' => $book->titre,
      'prix' => $book->prix,
    );
  }

  // The above will set up $sections as an associative array, but you need
  // to return an indexed array, so run it though array_values()
  return array_values($sections);
}

```

Basically, The first book that comes along with category "A" will create a new child the in $sections array with a key of "A". The book will then be nested in that child. If another book is found with category "A" then instead of creating a new category child, the book is nested inside of the same "A" category.

Note that I've not tested this code live so might need some tweaking
> 2 votes

---
Tags: database
---


# Question
Title: How do I place content in a user-profile.tpl.php, based on whether a boolean field is true?
I am trying to display certain content in the user profile pages of a site based on whether my boolean field 'member' is true. I am currently trying to solve this with an if statement like so.

```
    if ($user_profile['field_member']['und']['0']['value'] == '1') {

        print ('<p>This is working</p>');

    }

```

However this is returning an

'Undefined index: und in include()'

error on the if statement line. I'm not very well versed in working with drupal template files and would appreciate any help.

EDIT: The syntax was incorrect I should of written '#items' instead of 'und'. I discovered this with advisement, through the use of the devel kpr() function which allowed me to view the array contents more easily than a var dump.

# Answer
> 0 votes
You shouldn't access data that way, especially in template files as it's the raw data.

You should use the functions field\_get\_items & field\_view\_value

---
Tags: users
---


# Question
Title: How to overwrite /modules/user/user.module text?
I am trying to override the text outputted on the user login block:

"A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail."

I have copied "/modules/user/user.module" to my site's theme folder and overwritten the text in question however I'm not seeing the change.

Any help greatly appreciated :)

Thank you,

Andrew

# Answer
If it's just this one string you want to change have a look at the String overrides section in `settings.php`:

> To override specific strings on your site with or without enabling the Locale module, add an entry to this list. This functionality allows you to change a small number of your site's default English language interface strings.

The string you'll need to replace is `'A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'`
> 2 votes

# Answer
You can use hook\_form\_alter to change this text

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_profile_form':
    case 'user_register_form':
      $form['account']['mail']['#description'] = t('My text');
      break;
   }
}

```
> 2 votes

---
Tags: 7, theming, users
---


# Question
Title: How to update record programmatically with ECK?
I'm playing with Entity Construction Kit (ECK) on a Drupal 7 site. In a custom module I need to add, update and get ECK record.

By admin panel I created my entity "company" and his bundle "company". In my module I already built add and get method for the entity record (methods are working).

But how can I update a specific record ?

Thanks.

# Answer
After thousands of research, according to the page Creating and Modifying Entities this is the way to update an entity :

```
$entity = entity_load_single('entity_name', $entity_id);
$entity->title = 'new name';
$entity->save();

```

This will load the entity 'entity\_name' with the id 'entity\_id', then the title will be replace by 'new name'.

I hope its help.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Different permissions after node publishing
I have a role (Creators) where users can create/edit/delete nodes of some content types but they can't publish it, publication is done by other role (Publishers), I'm using Workbench and Workbench Moderation modules.

Now I need to disable Creators role to edit/delete content (even their own) after someone from Publishers role published node, so if user from Creators role create node and user from Publishers role publish that node, than node creator from Creators node can't edit or delete it.

How can I achieve something like this?

# Answer
I resolve this with small custom module. I checking user role as well because I need to apply this only on one role.

There is my code:

```
/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account = NULL) {
    global $user;
  if (
    // The $node argument can be either a $node object or a machine name of
    // node's content type. It is called multiple times during a page load
    // so it is enough if you perform the check once you get the object.
      is_object($node) && array_key_exists(6, $user->roles) &&
      // Operation on which you want to act: "create", "delete", "update", "view".
      ($op == 'update' || $op == 'delete')
  ) {
    // Check if the node is published.
    if ($node->status == 1) {
      return NODE_ACCESS_DENY;
    }
  }
}

```

My role's ID is 6, so I used this part `array_key_exists(6, $user->roles)` because of that.
> 0 votes

---
Tags: 7, users, workbench
---


title: How to create a flyout menu with Views?

text:
# Question
Title: How to create a flyout menu with Views?
I am trying to achieve the following output- id like a view with two images- each displaying a corresponding menu on hover- I've looked at using rewrite result for an image field in views for this- but I don't think I am using it properly. I would be tremendously grateful if anybody could take the time to give me some tips or tutorials on how to do this?

Note: I am a drupal-newbie.

# Answer
> 3 votes
Views maybe isn't the best solution to your problem. Drupal has a built in way to create menus. When you created your two menus and maybe placed them on your site with Menu Block, you then may apply the flyout functionality with CSS or jQuery or have a look at Superfish maybe.

---
Tags: views, routes, theming
---


title: Refer to Term ID from $content field

text:
# Question
Title: Refer to Term ID from $content field
I'm attempting to get the taxonomy term id from a field in the node template for a content type. I'm currently rendering the names of the terms using this

```
render($content['field_tags'][value]);

```

This works fine for grabbing the names of the terms. However I would like to be able to grab the actual term ids from those fields instead of just the names. Using devel I do see that that information exists, however I'm not sure how to refer to it.

# Answer
Updating the Answer:You can use template\_preprocess\_node. in your theme template.php

```
function YourTheme_preprocess_node(&$variables) {
  $variables['tags_tids'] = array();
  foreach ($$variables['field_tags'] as $key => $tag) {
    $variables['tags_tids'] = $tag['tid'];
  }
}

```

then in your node.tpl you could loop through the "$tags\_tids"array, and do whatever you want.
> 1 votes

# Answer
Simply double click the value you called in Devel and you will be offered the concrete path to your value. It then may be displayed like `$content->field_tags[LANGUAGE_NONE][0]['tid']`
> 1 votes

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


# Question
Title: How to make a comment only visible to the commenter before approval?
There is **no** registered users (apart from user/1 of course ...) in the website and anonymous visitors **have the permission to comment** on the website.

***Comments are not shown before approval***.

What I want to do is to display a comment to commenter **only** before I **approve** it. So this is what I'm looking for:

> Only display a comment posted by 'X' to 'X' (nobody else) for as long as the comment has not been approved by a reviewer, AND on condition X is using the **same browser** as the one the comment got posted with.

I couldn't use "userid" etc. for (anonymous) visitors. What can be used for that (session, IP address etc.)?

---

The feature I asked for is similar to the ***peer review*** feature you see on any SE site, which is like so:

**How can I do it?**

# Answer
Things you need to know:

1. hook\_node\_view
2. hook\_query\_TAG\_alter
3. db\_or

Step I read code.

**Step 1**: find function comment\_node\_view this function define element comment in array render of node.

**Step 2** find line 711

```
$node->content['comments'] = comment_node_page_additions($node);//define comment

```

**Step 3** go to function comment\_node\_page\_additions see code.

```
if (($node->comment_count && user_access('access comments')) || user_access('administer comments')) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
    if ($cids = comment_get_thread($node, $mode, $comments_per_page)) {
      $comments = comment_load_multiple($cids);
      comment_prepare_thread($comments);
      $build = comment_view_multiple($comments, $node);
      $build['pager']['#theme'] = 'pager';
      $additions['comments'] = $build;
    }
  }

```

**Step 4** If user is anonymous $node-\>comment\_count = 0. so condition is **false**. Don't add comment. (**Problem 1**)

**Step 5** function comment\_get\_thread

```
if (!user_access('administer comments')) {
    $query->condition('c.status', COMMENT_PUBLISHED);
    $count_query->condition('c.status', COMMENT_PUBLISHED);
  }

```

this function return array store cids (all comment of node) with condition status is published (don't get comment of user is anonymous) **Problem 2**.

## **Problem solving**

**Problem 1**: Use hook\_node\_view to set $node-\>commentcount != 0 (require this function run before function comment\_node\_view. You can set weigh of module (sure test with value is -1) or name of module start with a or b (not sure)).

```
/**
 * Implements hook_node_view().
 */
function ModuleName_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($user->uid == 0 && $node->comment_count == 0) {
    $node->comment_count = 1;
  }
}

```

**Problem 2** You need alter this query to get comment published or current user is author of comment. To do it i need hook\_query\_TAG\_alter. You can write a custom module with code:

```
/**
 * Implements hook_query_TAG_alter().
 */
function ModuleName_query_comment_filter_alter(QueryAlterableInterface $query){
  global $user;
  if (!user_access('administer comments')) {
    $conditions = &$query->conditions();
    foreach ($conditions as $key => $condition) {
      if (is_array($condition) && is_string($condition['field'])
        && $condition['field'] == 'c.status'
        && $condition['value'] == COMMENT_PUBLISHED) {
        unset($conditions[$key]); // unset condition comment is public
        $or = db_or();
        $or->condition('c.status', COMMENT_PUBLISHED);
        //$or->condition('c.uid', $user->uid); this case for require use login to comment
        $or->condition('c.hostname', $user->hostname); // Ip of user
        $query->condition($or);
        return;
      }
    }
  }
}

```

**NOTE:** **All the users have the same IP are seeing comment**.
> 6 votes

# Answer
# Try the Comment Access module

Maybe you should look at the Comment Access module.

It seems to not exactly match what you're looking for, but possibly with some tweaks you can get it to work somehow for anonymous users also.

The issues about "Still display a message to anonymous users after they post an unpublished comment." might inspire you to create such tweaks.

# Investigate the Comment Trust module

The Comment Trust module can be used to **auto-approve** comments from **trusted** visitors. Here is a quote from its project page (bold markup added here):

> Comment Trust auto-approves comments by users with previously-approved comments. It rewards trusted commenters with immediate approvals, while requiring you to approve the comments by new visitors. Works for both **anonymous** and authenticated users.

Even though that is not really what you want in this question, you may want to investigate how this module does its magic for anonymous users. It might be straight forward to clone its magic in what you are looking for.

# Use cookies

Since this is about anonymous users, we don't have "a lot" to connect our logic to. But using a technique based on cookies might work. Here are the main steps that would be required:

* including the jquery.cookie.js file (part of Drupal core), which includes some utility functions for working with cookies.
* set a cookie using a Drupal function in PHP.
* do something with that cookie in a JavaScript.

So this cookie should keep track of the comment Ids somehow, so that by using some jQuery you could apply some CSS to hide or show comments.

I'm not an expert in these kind of things, but maybe the answer(s) to these questions may help to complete this:

# Look at other modules from old Drupal releases

Maybe you want to look at the answers to drupal 7 comment moderation modules also (it may help to get some more inspiration). In there you'll find suggestions for contributed modules also, though none of them have a D7 version:

Maybe somebody wants to make a D7 version available for either of those modules?

# Remark

In a prior version of this answer I suggested using the Privatemsg module. However after you refined (clarified) the question, that is not what will help you solve your question.
> 3 votes

# Answer
This would be easily achieved using views if your users were logging in.

If you look at this question you see how you can use the current user in a view. All you'd then do is to create a view of comments where status is not approved and **user=user** and **nid=the node you're on**. You can then use that in a block.

---

To get a 'user like' token for an **anonymous user**, you can only really use the the **session**.

So extending the view idea further. I'd approach this problem as follows

1. Create a field in the comment called `session`.
2. Hide this from display.
3. Populate this on submit (use a form alter in a module), so it gets created on save - you might be able to use rules.
4. Add this logic into your view for filtering - you'll do that with a contextual filter again:

* add a PHP contextual filter.
    * get the user (global $user).
    * return $user-\>sid (the users session id).
> 3 votes

---
Tags: 7, comments
---


# Question
Title: How to create authentication token in the HTTP header request for Json view
I have a view listing some fields from a content type then i made it in a Json format using View DataSource module, all is ok with me tell now

i want to add authentication token in the header request to restrict any user to access this json view

any module or code help me, thanks

# Answer
> 1 votes
views\_datasource uses the standard drupal session to authenticate.

First set the permissions on the view to what you want. And test this in the browser.

then you can go onto your user authentication. Im assuming that you're using ajax to call the view, in a headless mode ?

then you've got 2 options

1) Make the users log into the Drupal site somehow first - that will then give them a session , and when they call that ajax request, the session will be sent.

2) Authenticate the user from your code - you can do this with the services module. you can follow this post https://www.drupal.org/node/910598 for more information

---
Tags: views, users, tokens
---


# Question
Title: How to use node reference to link images of referenced node?
I created a blog content type. In this content type I added a field "blog detail". I have a custom module to fetch data using `node_load()` in blog page. Now I want, when I click on a particular image, that this image's basic page would open using `node_reference()`.

How can I do it?

# Answer
I'ld suggest you use References. Add a node reference field into your blog content type. Finally when creating a blog node you'll reference a basic page (the one with your image).

Then check the display settings of your node reference field. Check the field formatters where you can choose

* Title (linked)
* Rendered Node
* NID
* etc...

Exactly there you have to add a field formatter now. Best by writing a small custom module. You may take the following code as a starting point:

```
/**
* Implements hook_field_formatter_info().
*/
function MY_MODULE_field_formatter_info() {
  $info = array(
    'linked_image' => array( // Machine name of the formatter
      'label' => t('Image (linked)'),
      'field types' => array('node_reference'), // Scope (this one will only be available to node reference fields)
      'description' => t('Display linked image if available'),
    ),
  );
  return $info;
}

/**
* Implements hook_field_formatter_view().
*/
function MY_MODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
    foreach ($items as $delta => $item) {
      // get the nid,
      // do a node_load(),
      // get your image,
      // rework it
      // $linked_image = what ever you got
      $element[$delta]['#markup'] = $linked_image;
    }
  return $element;
}

```
> 1 votes

---
Tags: 7, hooks, nodes
---


# Question
Title: How to manage a field collection in a table?
I have a field collection called *My links*.

*My links* contains these fields:

1. Organization Name (*Text Field*)
2. Description (*Long text with summary*)
3. Link Url (*Link Field*)

This is a pain to manage because I need to scroll down really often since I have at least 45 links in there.

Is there a way to manage these link in a table format?

Thanks a lot

# Answer
Yes, with the Field Collection Table module:

> Provides a table formatter for the Field Collection module.
> 2 votes

# Answer
If you are looking for a frontend solution, Clive answer is probably the good one. If you search for a backend solution (node edit form), Field Group module is probably the solution.

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

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
> 1 votes

# Answer
You could also try the Field Collection Fieldset module. This wraps each field collection "row" in a collapsed fieldset.

You can set one of your fields to be the label of the fieldset (e.g. Orgainisation Name) and if you do that then your admin screen would appear as a vertical list of expandable titles and when you click on any of them it opens up to reveal the 3 fields for that particular row.
> 0 votes

---
Tags: entities
---


# Question
Title: Does anyone know solution for adding pure javascript filter for View?
As in queston. I was googling and searching forum, but found nothing useful.

I want to setup dynamic filter for a view. Eg. http://silverwareconsulting.com/index.cfm/2008/10/2/jquery-autofiltering-table. One difference is that I need to take filter value from textfield.

Maybe this functionality is built-in in Views, but I missed that?

# Answer
> 0 votes
I'ld suggest you choose views format `Table` and then add your JS from `hook_page_build()`.

---
Tags: 7, views, javascript
---


title: Show Entity Reference items as table

text:
# Question
Title: Show Entity Reference items as table
I have two Content Types (Country, City). I want to display full contents of City in Country, so I did like this: \- create a field in World Content type \- set this field as entity reference (City).

Drupal print the two City contents in World successfully but I want put the city content in horizontal tabs.

I tried the module references\_tabs, but it can put only one field reference at time.

How can I do so?

Thanks

# Answer
> 1 votes
According to the description of the References Tabs module

> This module allows to render nodes referenced via a node reference field in tabs, with node titles as tab titles and rendered nodes as tab content.

it is only support **Nod referenced** not **entity reference** ,you can see here that it is not support `entity reference` , you can change your field from entity reference to node reference type.

---
Tags: nodes, entities
---


# Question
Title: How to use Commerce Feeds to Import Stock for the Commerce Stock module?
I have the Commerce Stock module enabled for my products in Drupal Commerce.

But I cannot import data to the stock fields: When I set up the correct product processor, I can't see the Stock field which is present in my product variation type.

# Answer
> 2 votes
Your problem sounds similar to the issue: Not recognizing product variants fields.

The solution is most probably to upgrade the Commerce Feeds module to 7.x-1.x-dev, or if you don't want to use a dev version you could downgrade the Feeds module to 7.x-2.0-alpha9.

# Answer
> 0 votes
As for me there was only one solution: reinstall. And after reinstalling first you should add importer, set stock mapping and only after that - enable feeds tamper. If I installed tamper before mapping setup there always was same problem with mapping. So, mb it's same thing. Sorry, can't comment.

---
Tags: 7, commerce, feeds
---


title: Drupal 7 not sending emails of any kind

text:
# Question
Title: Drupal 7 not sending emails of any kind
My drupal site isn't sending email for some reason. What are some ways to debug this issue of mail sending?

# Answer
> 1 votes
The Mail Logger module will tell you if the mail is being sent by Drupal and in fact is a useful module for keeping track of outgoing e-mail.

# Answer
> 2 votes
Use a module that allows you to route email through a real SMTP server.

What is probably happening is that Drupal is sending the mail, but it's being blocked as a spammy looking email message.

edit: you can Alphabet for "drupal smtp module", but this is one I've used https://www.drupal.org/project/smtp

# Answer
> 1 votes
If you are not getting any email from any contact forms on the site or even registration emails. You might want to goto the server terminal and try to see if it has anything to do with your mail server. You can run the following command:

```
drush php-eval "print mail('myemail@addresshere.com','Test subject from drush','Test message','From: drush@exampledrupalsite.com');"

```

Just replace the emails with your own. If you still aren't receiving anything you can check the maillogs located here: /var/log/maillog

Then search for the email address you are sending to. If its working it should look something like this:

> Aug 11 10:31:56 YRELX05 postfix/smtp\[18534\]: 6222BB1: to=, relay=172.22.**.**\[172.22.**.**\]:25, delay=0.02, delays=0.02/0/0/0 , dsn=2.6.0, status=sent (250 2.6.0 \<20150811143156.627C922BB1@YRNYEELX05.localdomain\> Queued mail for delivery)

---
Tags: 7, emails
---


# Question
Title: How do I get request parameters when using fragment AND query with drupal_goto
I was successful in using fragment with drupal\_goto, but when I use it AND query, I am not able to get the request parameters using $\_GET from the query.

I can see the request parameters in the URL, but it returns NULL. The URL is constructed as http://mydrupalsite/?code=success#overlay=admin/vendor/auth-stripe.

I am attempting to use $\_GET\['code'\] to get the parameter. I also tried $\_REQUEST

# Answer
> 2 votes
I'm guessing you're trying to access the $\_GET from the *page that's loaded in the overlay* (admin/vendor/auth-stripe). If that's the case, then you've constructed the url wrong. It should be: http://mydrupalsite/#overlay=admin/vendor/auth-stripe%3fcode%3dsuccess

That said: where are you actually constructing this URL? If you're doing it properly, all of that should be taken care of for you automatically.

---
Tags: http-request
---


# Question
Title: How can I create a custom view other than content types?
How can I create a view that's based on a custom table from a custom module.

Actually in creating views path I can see options of view types as:

> **View type**:
>
> Node: Nodes are a Drupal site's primary content.
>
> Comment: Comments are responses to node content.
>
> File: Files maintained by Drupal and various modules.
>
> Node revision: Node revisions are a history of changes to nodes.
>
> Term: Taxonomy terms are attached to nodes.
>
> User: Users who have created accounts on your site.

But when selecting the node option I can only select from `node table` and selecting user I can select from the `user table` for displaying the data from these tables. But if I need to display data from the custom tables how can I select that table on creating the query and display them on the view pages?

# Answer
You need to implement `hook_views_data` to tell Views about your tables and how the data in your tables relates to other tables defined to Views (if it does). Here's a good tutorial to get you started: http://www.grasmash.com/article/demystifying-views-api-developers-guide-integrating-views

Depending on the nature of your data, you may, alternatively, consider defining your custom data as a custom entity type. If you do that through the Entity API module, then it will provide Views integration "for free".
> 1 votes

---
Tags: views, 6
---


# Question
Title: Can I edit Content Y within Content X Edit Form using Rules?
I have created a content type VIP PAGE, and another content VIP IMAGE. Now I want to allow the user to upload 5 VIP IMAGES at the same time as creating the VIP PAGE content.

So what I did was to add 5 Image fields to the VIP PAGE content type, then I created 5 Rules, which trigger when content type of VIP PAGE is created and it takes those 5 images and creates 5 VIP IMAGES content and uses Entity Reference field to connect the IMAGES to the PAGE.

Now this all works fine, until a user decides to Edit one of their images. I want to still use a single page (VIP PAGE Edit Form) to handle images being edited. Can anyone recommend a good way to achieve this?

I can't figure out how to tell Rules which of the images it is that was edited.

# Answer
Entity reference and Inline entity form could help you.

* **Entity Reference:**

> Provides a field type that can reference arbitrary entities:
>
> + A generic entity reference field
>     + Four widgets:
>
>     - Two implemented on top of the Options module (Select and Radios/Checkboxes)
>         - Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)
>     + Two formatters:
>         - A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
>         - A "Rendered entity" formatter, that renders the references entity using a configurable view mode.
>     + Integration with Views (for both forward and backward references).
>     + Integration with Entity Metadata (and as a consequence with Search API and the like).
>     + Integration with Devel generate.
>     + Integration with Feeds and Migrate (\>= 2.3) for painless data import.
* **Inline Entity Form:**

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced. Supports commerce\_product\_reference, commerce\_line\_item\_reference and entity reference fields. Read the documentation here.
> 3 votes

---
Tags: views, rules
---


# Question
Title: In which table should I save the value of system_settings_form in Drupal 7?
I am using Drupal 7 and creating a form with some fields like position.

```
function mycustom_form($form, &$form_state){
  $form = array();
  $form['position'] = array(
   '#type' => 'textfield',
   '#title' => t('Position for the magnifier'),
   '#options' => array('left' => 'Left', 'right' => 'Right','up'=>'Up','down'=>'Down'),
   '#required' => TRUE,
  );
  return system_settings_form($form);
}

```

When I click on save with any position selected, these values are saved. So I am not getting where these values are saved and how to use these values in a JavaScript file... I am saving these values in a database.

# Answer
> 6 votes
If you use system\_settings\_form function your data will be saved in 'variable' table. To get saved data you may use variable\_get function.

To show saved value in form

```
       function mycustom_form($form, &$form_state){
         $form = array();
         $form['position'] = array(
           '#type' => 'textfield',
           '#title' => t('Position for the magnifier'),
           '#options' => array('left' => 'Left', 'right' => 'Right','up'=>'Up','down'=>'Down'),
           '#default_value' => variable_get('position', ''),
           '#required' => TRUE,
         );

         return system_settings_form($form);
       }

```

If you want to use saved data from your form in the javascript, you may use next code

```
drupal_add_js(array('myModule' => array('position' => variable_get('position', ''))), 'setting');

```

Then this data will be available in javascript in `Drupal.settings.myModule.position` variable

---
Tags: 7, configuration
---


# Question
Title: Not able to map all the product variations fields in commerce feeds importer
I have one content type and added one field Product Variations' as product reference with widget 'Inline entity form - Multiple values'. But when I used Node Processor, I am not able to map other fields of the product variations. It only shows SKU and Product ID fields in target drop-down. It shows all the fields from node but not from the product variations.

Because of this I am not able to add more fields in my CSV file except title and sku. Does anyone have any ideas on this? Thanks

# Answer
Another user gave me this to answer my question:

How to use Commerce Feeds to Import Stock for the Commerce Stock module?

The user https://drupal.stackexchange.com/users/8943/watergate suggested this:

1. If you're using commerce\_feeds 7.x-1.3, uninstall it.
2. Make sure you've updated the standard Drupal feeds to 7.x-2.0-beta1
3. Download commerce\_feeds 7.x-1.x-dev

After I did that, I could use mapping and see all the target fields for my product variation, including those fields enabled when you use commerce\_stock.
> 1 votes

---
Tags: commerce, feeds
---


title: How to set attribute for checkbox field

text:
# Question
Title: How to set attribute for checkbox field
I want to add the attribute `data-toggle="toggle"` to a checkbox field.

I thought I could use the hook theme\_checkbox which is:

```
function theme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

```

So I customised it to:

```
function mytheme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }

  //*******Added 3 lines below*******
  if ($element['#attributes']['id'] = 'edit-profile-carer-field-profile-active-und') {
      element_set_attributes($element, array('#attributes' => 'data-toggle="toggle"'));
  }

  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

```

However, instead of just adding the attribute `data-toggle="toggle"` to the checkbox field with the id *edit-profile-carer-field-profile-active-und*, it is adding the attribute to all the checkboxes on the form.

Can someone tell me what I am doing wrong? How can I target just the the checkbox I want? Or do I need to use another approach to do it?

# Answer
I'd recommend you do this via a form alter. But that aside, the reason your code doesn't work is that you're not doing your comparison correctly.

```
if ($element['#attributes']['id'] = 'edit-profile-carer-field-profile-active-und') {

```

Should be:

```
if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {

```

And you're also not setting the attribute correctly. So the final function should be:

```
function mytheme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }

  //*******Added 3 lines below*******
  if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {
      $element['#attributes']['data-toggle'] = 'toggle';
  }

  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

```
> 0 votes

---
Tags: theming, forms
---


# Question
Title: How to see the filenames imported by the Feeds module?
Is there any way to see the past filenames that have been imported by the Feeds module (using Drupal 7)?

I am trying to warn people if they try to import a file that has already been uploaded by Feeds.

# Answer
> 1 votes
I added this patch and it saves the filenames in the log now https://www.drupal.org/files/issues/1045818-feeds\_log\_filename.patch

# Answer
> 1 votes
Imported files are stored in `default/files/feeds` by default I think so you could test on that first.

Feeds does create a watchdog event but it doesn't persist.

If you attach feeds to a node then you have several advantages. You can re run the import. And more interestingly you can access the node via Views and probably Rules. With those two you could build something with a Rules trigger event on the node save or Feeds import that would check for an existing node with a matching file.

If you can't get that working then post back and I'll try to make an example.

---
Tags: feeds
---


# Question
Title: Save me from changing the look of CKEditor using Javascript
I see that code is being rendered to produce this CKEditor (via the CKEditor module) contains an inline style that creates a height of 200 pixels. I'd like to change this value to 100px to save a bit of screen space.

I would like to change this or override this is a maintainable way. In the hopes it was in a tpl.php I tried `find . -name '*.php' -exec grep -lin 'presentation' {} \;` with little luck.

**Can anyone point me to where can override this value?** Or better put, how can I do better than this:

```
jQuery(function() {
        console.log('Resizing ckeditor')
        jQuery('#cke_1_contents').attr('style', 'height: 100px; max-height: 100px;');
  });

```

# Answer
> 0 votes
You can use a **CSS override** in your stylesheet to achieve this:

```
.cke_contents {
  max-height: 100px;
  height: 100px !important;
}

```

And, of course, if you only want to change one instance of the editor, just use an ID selector instead.

---
Tags: 7, wysiwyg
---


# Question
Title: How can I write users table data in custom file?
I have a number of users in my site,I have developed custom module for drupal mail functionality.

But I want to write test cases for custom module.

then here is the problem is how can I get the (`db_select`) users table data and write down in `.test` file.

for example in `.module` file we use like this:

```
$select = db_select('{users}', 'users');
$select -> addField('users', 'name', 'users_name');
$select -> addField('users', 'uid', 'uid');
$select -> addField('users', 'mail', 'users_mail');
$select -> addField('users', 'created', 'users_created');
$select -> addField('users', 'access', 'users_access');
$select -> addField('user_relationships', 'requester_id', 'requester_id');
$select -> addField('users_roles', 'rid', 'role_id');
$select -> addField('users_user_relationships', 'mail', 'users_user_relationships_mail');
$select -> leftjoin('user_relationships', 'user_relationships', "users.uid=user_relationships.requestee_id");
$select -> leftjoin('users', 'users_user_relationships', "user_relationships.requester_id=users_user_relationships.uid");
$select -> innerjoin('users_roles', 'users_roles', "users.uid = users_roles.uid");
$select -> condition('users.status', 0, '<>');
$select -> condition('users_roles.rid', array(
  '4',
  '5'
), 'IN');
$subresult = $select -> execute();

```

and i have wrote .test file like this

```
<?php
class BiTestMailsTests extends DrupalWebTestCase {
protected $privileged_user;
public static function getInfo() {
  return array(
    'name' => 'Test Mails',
    'description' => 'Tests for the mail module.',
    'group' => 'Test Mail Group',
 );
 }
public function setUp() {
   parent::setUp(array('mails'));

   }

public function testmail() {
    // Create an administrative user.
    $account = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($account);

      //database files
    $results= db_select('users','u')->fields('u',array('uid','name','mail','created','access'))->execute()->fetchAll();
    if($results){
     foreach($results as $res){
     $user_fields = user_load($res -> uid);
     $this->verbose('language:'.$language);
     $string= 'uid:'.$res->uid.' ,name:'.$res->name.' ,mail:'.$res->mail.',created date:'.$res->created.',Access:'.$res->access.'\n\r';
     $this->verbose($string);
    }
    }
    }
    }

```

but temporary user created and that values are getting. i don't want temp values,i want database USERS table values. **How can I write down `users` information(name and email) in `.test` file?**

# Answer
> 1 votes
Your just need get your select put it in `FOREACH` and write down in file.(something like below code can help you\_

```
$results= db_select('users','u')->fields('u',array('uid','name','email'))->execute()->fetchAll();
if($results){
     $fh=fopen(drupal_get_path('module',   'yourcustommodulename').'/usertest.txt','w+');
     foreach($results as $res){
     $string= 'uid:'.$res->uid.' ,name:'.$res->name.' ,email:'.$res->email.'\n\r';
    fwrite($fh,$string);
  }
  fclose($fh);

```

}

---
Tags: 7, database, testing
---


# Question
Title: What's the difference between 'commerce-line-item-unchanged' and 'commerce-line-item'
In drupal commerce rules there are selectors like 'commerce-line-item' and 'commerce-line-item-unchanged' – what is the differnece between them? When should i use the one or the other?

# Answer
Commerce line items are Drupal Entities (enhanced a bit by the Entity module) and, like other entities, the "entityname-unchanged" is present in some rules just so you can see what the entity was like before it got changed.

There isn't a specific use case intended for it but there are cases where being able to see the original state of an entity would be good. Specific to a commerce line item, maybe you'd want to reset the line item's quantity to its old value if they chose some crazy number like 10000.
> 2 votes

---
Tags: commerce, rules
---


# Question
Title: How to format the display of webform_select_options_info to include an image?
Looking for some guidance on how to approach the formatting of the results of webform\_select\_options\_info. What I want to present to the users is a dynamically populated list of items they flagged along with a checkbox. What I'd like to do is show a thumbnail of the image, the node title and a checkbox in my list.

The function as I have it now is as follows

```
 function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
   $options = array();
   if ($view->result) {
     $row_class = $view->style_options['row_class'];
     $attributes = $row_class ? " class='$row_class'" : '';
     foreach($view->result as $item) {
    $options[$item->product_id]= $item->commerce_product_title;
      }
       }
   else {
     $options[0] = t("Nothing");
   }
return $options;
      }

```

I'm not sure how to change the foreach loop to include additional fields?

# Answer
> 1 votes
Well, I still didn't get a good answer on modifying the syntax here but here is working result. I have a check box, thumb, and title all showing as a list in webform. Still not completely functional as the function doesn't seem to work for anonymous users, although the Flag is anonymous and I'm using sessions.

```
 <?php
    /**
     * Implements hook_webform_select_options_info().
     */
     function webform_hook_webform_select_options_info() {
       $items = array();
       if (function_exists('webform_hook_user_flag_sample_requests')) {
         $items['webform_hook_user_flag_sample_requests'] = array(
          'title' => t("Sample Requests (User Flag list)"),
          'options callback' => 'webform_hook_user_flag_sample_requests',
         );
       }

       return $items;
     }

     function webform_hook_user_flag_sample_requests() {
       $view = views_get_view('webform_flag_views', TRUE);
       $view->set_display('webform_options');
       $view->execute();
    // dpm($view);
       $options = array();

       if ($view->result) {
     //    $row_class = $view->style_options['row_class'];
     //    $attributes = $row_class ? " class='$row_class'" : '';
         foreach($view->result as $item) {
        $options[$item->product_id]= $item->commerce_product_title . render($item->field_field_image[0]['rendered']);
          }
           }
       else {
         $options[0] = t("Nothing");
       }
    return $options;
          }

```

# Answer
> 0 votes
You can't. Drupal's FAPI won't allow markup in the labels of checkboxes. It gets sent through check\_plain which escapes your html.

What you could try instead is writing a custom render function for that form element.

---
Tags: views, webforms, flags
---


# Question
Title: View which filters based on URL matching field value
I'm trying to create a view for solr search results, what I'd like to do is have have a page in the view each of which pull data from the same set of results but filter them based on matching part of the URL to a field in the content type being indexed.

The problem is the part of the URL used for matching won't match the value of the field in content type, so I was thinking of having a list of some sort which would match the URL with the corresponding field value.

Is this even possible? If it's not I could always create a new view page for each possible URL & manually set a filter criteria. I was just hoping that rather than creating multiple view pages I could do it with one.

# Answer
I wasn't able to do exactly what I wanted but what I did instead was create an exposed filter for the field in the content type being searched & use the URL parameter it created when in use to filter search results.

The exposed form itself is hidden with CSS as just including the filter without exposing it won't allow it to be activated via a URL parameter.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to allow a role to add user without adding user name, password, roles, etc
I created a role. I would like the users of the role be able to add some people without entering user name, password, roles, active, etc. These people that the role will add are actually customers. When we get new customers, specific role users will login to the system and add the customers to the system and these people/customers do not need to access the system.

I did search google and i found this site link but I could not follow it.

Do you know how I can do it?

---

I thought about it. Here is the problem. After I add the customers, I need to be able to link each customer to another module content(e.e. xxx.com/module/add). The module that I am using it has a field which allows to select a user only exists in the system. If I create a content type 'customer' like you said, module field does not see these customers when i go to xxx.com/module/add. Module field only sees these customers if they are users of the system. Not sure how to proceed?

---

Other module name is simple reservation which has a field 'This reservation is for'. This field is only takes users names from the system.

sr\_week.tpl.php has the below code to get the users ( i guess)

```
<div id="srFor">
          <?php if (($reservation["for_uid"] > 0) && ($reservation["uid"] != $reservation["for_uid"])) {
              print(" (". t("for") ." ". l($for->name, 'user/'. $for->uid)) . ")";}
              else print(" ");?>
        </div>

```

# Answer
> 0 votes
It sounds like these people you're adding should not be added as users to the system. You should only add users if they are going to be actually logging into Drupal.

If you're just trying to keep a record of clients then you should store them as nodes. Configure a new content type called something like "customer" and add and configure the appropriate fields that you wish to store about these customers.

---
Tags: users
---


# Question
Title: Sass error with zen 5, 'it is not clear which file to import
So, I'm getting what seems to be a common error in working with SASS in a windows environment. "Error: It's not clear which file to import @import'print';" using zen 5.

I have tried changing the sass-globbing versions, and even tried different variations of the @import statements syntax (e.g. @import "print/*", "print/**", "print/**/*" etc, nothing seems to affect the error.

The issue is that while there are plenty of people reporting this issue, there doesn't seem to be a clear picture of how to fix or address the issue, suggesting changing developing environment is not helpful.

At it's face, the issue is that the SASS parser can't seem to tell the difference between the partial \_print.scss and the other empty print.scss files in the same folder.

Do I need the empty print.scss file, or can I rename it? Or can I rename the partial \_print.scss to something else? Is there a non-hack way to fix this?

# Answer
So, this ends up being more of a environment/sass issue I post this here because I encountered in working with Omega, and I figured someone else would bump into this. Depending on your set up, especially if you're using a task manager, SASS file globbing might not be functional.
> 0 votes

---
Tags: theming
---


# Question
Title: add a class to page depending on order total (Drupal Commerce)?
I want to add a class to a page when the order total reaches a certain level.

# Answer
I came up with this piece of code, which seems to work:

```
function class_price_preprocess_html(&$variables){
  global $user;
  $order = commerce_cart_order_load($user->uid);
  if ($order) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper->commerce_line_items;
    $total = commerce_line_items_total($line_items);
    if($total['amount']>5000){
        $variables['classes_array'][] = "class-pr";
    }
  }
}

```
> 1 votes

---
Tags: commerce, theming
---


# Question
Title: Access image alt attribute in field template
I have copied the field.html.twig Template to field--node--field-image--article.html.twig, to specialize the template for my needs. In this case the template would be called for content type article and field type image. (This content type uses the *Responsive Image* module.)

As default, with the image field, you must define an alt-value for the image. But the alt-value is processed in the template image.html.twig.

Is it possible, to access the alt-value in the field--node--field-image--article.html.twig (the copy of field.html.twig), which calls the image.html.twig via the responsive-image templates.

I want to display the alt text in a div near the image.

I also have tried to access it in `hook_preprocess_field()`, but all I have for now is the following code.

```
function mytheme_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#field_name'] == 'field_image') {
    foreach ($variables['element']['#items'] as $item_key => $item) {
      // code to write
    }
  }
}

```

# Answer
With twig a preprocess function won't be necessary to get at this data (yay). Unfortunately we still have some weird "drupalisms" to deal with due to the render API. At any rate, here's how you get to it:

```
{{ item.content['#item'].alt }}

```

And here's the issue on d.o accounting for the drupalism (linked directly to comment with the above solution and explanation): https://www.drupal.org/node/2160611#comment-9358305
> 6 votes

---
Tags: 8, theming
---


# Question
Title: Is it possible to create content and link it to an existing menu item?
I have a menu tree with links all directing to 'front'.

On creating content I don't want to create a new menu item but want to have an extra option under the Menu settings saying 'Add content to existing menu item'.

What is the best way to achieve this or is there a module available that handles this situation (D7)?

# Answer
> 1 votes
I guess you have to write a custom module. This may be a similar situation.

# Answer
> 1 votes
I think you need just go to admin panel -\> Structure -\> Menus. Find the menu you want to add the link to and and hit "List links" Then find the menu item you want to link content to and hit "edit", and change it's url from to the url of corresponding content.

# Answer
> 1 votes
Default Drupal behavior allows you to create a new link, under a menu tree item of your choice, at the time of saving a node, as below.

Have I understood right? - What you want to do is, be able to select a menu tree item, just like in the above image, but not have to enter title and description etc. You don't want new menu item created, but use the existing one, and have its path value changed from `front` to the path of the new node?

^ If that is the case, you have to create a quick custom module to do so. A good idea would be to form alter (the fields, the submission behavior) the same form in the image above. That way you do not have to code the menu tree loading and selecting parts etc.

Hope this helps.

# Answer
> 1 votes
Your solution is the Menu editor module. Make sure you enable the `me_node_creation` submodule.

You create the menu links as placeholders, with `<new>` as the link path. Then on visiting any such item, you get to a page that allows you to create a real node attached to this menu link.

---
Tags: 7, routes
---


# Question
Title: When creating a Panel Page and selecting a layout, the page layout is not overidden
I'm using *Omega* theme and have built 4 custom layouts for my sub-theme. If I activate layouts and select one in the admin my *Omega* sub-theme, everything is fine.

Now I want to use those layouts as the base for a *Panel Page*. When I do that, it injects the layout into the content section of the main (default) `.tpl` theme file.

My expectation is that it will completely replace that theme file the same way it does if I activate and use the layout in my sub-theme admin.

I've made sure to check disable *Drupal* `blocks/regions` when starting to build the layout.

I even tried using the stock layouts that come with *Omega* and no luck.

I can't think of anything else to try, especially since the layouts work outside of *Panels*.

# Answer
> 0 votes
Yes, that's how Panels is designed to work. It can only take over the content rendered to the main content region. If you want Panels to take over all regions then you need to use Panels Everywhere which is, incidentally, compatible with Omega 4.

---
Tags: panels, theming
---


title: How to add content type to front page

text:
# Question
Title: How to add content type to front page
I created a content type **Carousel**. I created a region **Huge**.

On the front page, I want the content type to be placed in the region **Huge**.

Current process:

1. Create content
2. Specify `publish to front page`.

Even though I specify this:

`render($page['carousel'])`.

All of the content is being loaded in:

`render($page['content'])`.

What is the drupal way of doing this on the front page?

The use case is for marketing to create new **Carousel** content type \>\> **publish to front page** \>\> the **HUGE** region is updated with new content.

This should be different than regular blog's posts that appear on the front page.

Thanks for any help! noah

# Answer
> 2 votes
You can use Views module to create a block and place that block in your custom region

1. Here is the step by step process to create a slide show with slide show module
2. And placing block in the region can be done here `admin/structure/block`

To create custom block and template

```
/**
  * Implements hook_theme().
 */
function YOUR_MODULE_theme() {

$theme = array();

$theme = array(
    'my_custom theme' => array(
        'variables' => array('items' => array()),
        'template' => 'my-custom-theme'
    ),
return $theme;
}
/**
* Implements hook_block_info().
*/
function YOUR_MODULE_block_info() {
   $blocks = array();
   $blocks['slideshow'] = array(
   'info' => t('Block Name'),
);
return $blocks;
}
/**
 * Implements hook_block_view().
*/
function YOUR_MODULE_block_view($delta = '') {
   $block = array();
  switch ($delta) {
        case 'slideshow':
        $block['subject'] = '';
        $block['content'] = _YOUR_MODULE_slideshow_callback();
        break;
     }
   return $block;
 }
function  _YOUR_MODULE_slideshow_callback() {
  $result = "Your query to fetch content";
   foreach($result as $row){
       $items[] = $row;
       }
   $output = $output .= theme('my_custom theme', array('items' => $items));;
    return $output;
 }

```

and write html code for your slide show in `my-custom-theme.tpl.php` file

# Answer
> 0 votes
You can done it using editing **template**. Render your **Carousel** content in **Huge** region of **page--front.tpl.php**.

# Answer
> 0 votes
Just follow the below mentioned steps:

1. Make one block with content type 'Carousel'.(You can make simple block from views.)
2. Goto block section. Select 'Huge' region. Then In block configuration, jump into visibility settings, In that go to Pages section, And select show to specific page and add in that text area.

That can solve your problem.

---
Tags: nodes
---


# Question
Title: What is the purpose of sites.php and how does it relate to settings.php?
What is the purpose of sites.php and how does it relate to settings.php?

I have done a lot of web searches and looked at the comments in these files, but cannot find a simple explanation.

# Answer
Looking at `conf_path()` should help clarify the relationship here. `conf_path()` builds the default subdirectory (inside the **sites** directory) Drupal will goto for **settings.php** (and other site-specific configurations). It's default search behavior can be overridden with **sites.php**.
> 1 votes

---
Tags: configuration
---


# Question
Title: REST Post creating entities with relations
I am having trouble creating comments on nodes ( articles etc. ) with the Rest module.

I have enabled the endpoint in `rest.settings.yml` :

```
resources:
  'entity:node':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie
    POST:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - basic_auth
  'entity:comment':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie
    POST:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - basic_auth

```

I have followed the information here rest tutorial - headless drupal 8 and on drupal.org I used this tutorial as a base to build my request, noting that there have been changes since the article was posted.

I am using basic\_auth, setting the CSRF token as per issue and I have set permissions for the test user to edit, delete and create articles, basic pages and comments.

I am using `application/json+hal` because of the outstanding issue with application/json

What is happening is the server is reponding :

`403 Forbidden :` `{"error":"Access denied on creating field entity_id"}`

The request is failing where checking access on read only fields, which return `AccessResult::forbidden();`

Clearly I am missing something from my request ? I thought that the hal `_links` reference points to the `entity_id` ?

My request so far :

```
{
   "_links":{
      "type":{
         "href":"http://d8.dev/rest/type/comment/comment"
      },
      "http://d8.dev/rest/relation/comment/comment/entity_id":[
         {
            "href":"http://d8.dev/node/1?_format=hal_json"
         }
      ],
      "http://d8.dev/rest/relation/comment/comment/uid":[
         {
            "href":"http://d8.dev/user/1?_format=hal_json",
            "lang":"en"
         }
      ]
   },
   "_embedded":{
      "http://d8.dev/rest/relation/comment/comment/entity_id":[
         {
            "_links":{
               "self":{
                  "href":"http://d8.dev/node/1?_format=hal_json"
               },
               "type":{
                  "href":"http://d8.dev/rest/type/node/article"
               }
            },
            "uuid":[
               {
                  "value":"c4b5b929-3ccb-4cfd-8200-0ec8f9170926"
               }
            ]
         }
      ],
      "http://d8.dev/rest/relation/comment/comment/uid":[
         {
            "_links":{
               "self":{
                  "href":"http://d8.dev/user/1?_format=hal_json"
               },
               "type":{
                  "href":"http://d8.dev/rest/type/user/user"
               }
            },
            "uuid":[
               {
                  "value":"76555fc7-c4c4-4e1f-a053-83ab818bba4f"
               }
            ],
            "lang":"en"
         }
      ]
   },
   "comment_type":[
      {
         "target_id":"comment"
      }
   ],
   "comment_body":[
      {
         "value":"Hello world this is a comment",
         "format":"basic_html"
      }
   ],
   "subject":[
      {
         "value":"A comment test"
      }
   ],
   "name":[
      {
         "value":"admin"
      }
   ],
   "thread":[
      {
         "value":"01/"
      }
   ],
   "entity_type":[
      {
         "value":"node"
      }
   ],
  "field_name": [
    {
      "value": "comment"
    }
  ]
}

```

# Answer
Okay so this issue is actually a bug. For me the issue was fixed by applying the latest patch for now, likely the patches will need work and tests.

There were issues with my request and I have changed them above to reflect how an actual comment request should look like ( at the time I am writing this ).
> 1 votes

---
Tags: 8
---


# Question
Title: Remove number and reference list from mime mail plaintext emails
Mime mail converts urls from "www.google.com" to "www.google.com \[1\]" in the plaintext version of email, and adds a reference list to bottom, "\[1\] www.google.com ". How do i remove this number and the reference list from the bottom of the plaintext email?

Edit: The mail itself has both, html and plaintext-version in itself. I want the users who view the plaintext-version of the email to not see the numbering.

# Answer
I have found the solution. Mimemail creates the plaintext version of the mail in mimemail.inc, in the beginning of the function mimemail\_html\_body():

```
  if (empty($plaintext)) {
    // @todo Remove once filter_xss() can handle direct descendant selectors in inline CSS.
    // @see http://drupal.org/node/1116930
    // @see http://drupal.org/node/370903
    // Pull out the message body.
    preg_match('|<body.*?</body>|mis', $body, $matches);
    $plaintext = drupal_html_to_text($matches[0]);
  }

```

And here the `drupal_html_to_text()` creates the plaintext mail with the footnotes and the url numbering. The plaintext is created here if one is not provided already. So, the simple solution is to provide the plaintext version ourselves.

My email templates are defined by my implementation of hook\_mail, as text without html (and mimemail in itself creates a html version of my emails, and in the above function, creates again a plaintext version of the mail, with the footnotes and url-numbering). So, I can provide a plaintext version of the email in my implementation of hook\_mail\_alter:

```
    function mymodule_mail_alter(&$message) {
        $message['params']['plaintext'] = drupal_html_to_text(implode("\r\n\r\n", $message['body']));
}

```

(The `$message['body']` is the array containing the message, with message rows as entries in the array). This might not need to be wrapped around the `drupal_html_to_text()` function, but in case i go nuts and start inserting html into my messages, that function will strip it off. If i start to write my emails in html, I need to write a custom function (almost a straight copy of the `drupal_html_to_text()` function) to create the plain text version of my mails, but without the footnotes and url numbering.

Thanks for your help, I would not have found this solution by my self.
> 1 votes

# Answer
You need to write a new implementation of `MailSystemInterface`. You'll want to extend the `DefaultMailSystem` class. You just need to override the `format()` method on that class. It's that method's call to `drupal_html_to_text()` that makes that replacement. So you'll need to copy that function to a custom function of your own and remove the part that you don't like. Then, to get Drupal to use your new class you'll need to change the `mail_system` system variable to the name of your new class by calling variable\_set or setting it in settings.php.

You'll end up with something like this in your custom module's .module file:

```
class ModulenameMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    // Join the body array into one string.
    $message['body'] = implode("\n\n", $message['body']);
    // Convert any HTML to plain-text.
    $message['body'] = _modulename_drupal_html_to_text($message['body']);
    // Wrap the mail body for sending.
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

function _modulename_drupal_html_to_text($string, $allowed_tags = NULL) {
 // Function too long to put here but copy it from drupal_html_to_text() and remove the part that creates the footnotes; it's clearly commented
}

```

You could automatically set the new mail system when the module's enabled by putting this in your module's .install file:

```
function modulename_enable() {
  variable_set('mail_system', 'ModulenameMailSystem');
}

```
> 0 votes

---
Tags: uri, emails
---


title: Select option in Drupal form API

text:
# Question
Title: Select option in Drupal form API
I've created a drupal custom form. I've used a select option for bank which get its value from the bank table. I want to store bankID in bankbranch table and which is a foreign key and display bank name in select box but it shows me an error:

> Undefined property: stdClass::$bankID in bankbranch\_form() (line 40 of C:\wamp\www\emp\sites\all\modules\bankbranch\bankbranch.module).

My code is below:

```
/**
* Implements hook_permission().
*/
function bankbranch_permission() {
  return array(
    'submit bankbranch' => array(
      'title' => t('submit bank branch'),
      'description' => t('submit bank branch form'),
    ),
  );
}

/**
* Implements hook_menu().
*/
function bankbranch_menu(){
  $items = array();
  $items['bankbranch'] = array(
    'title' => 'Bank Branch Entry Form',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit bankbranch'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('bankbranch_form'),
  );
  return $items;
}

/**
* Bank Branch Form
*/
function bankbranch_form($form, &$form_state){
  $query_bank = db_select('bank', $alias = NULL)
    -> fields($alias = NULL, array('bankID', 'bankname'))
    -> execute()
    -> fetchAll();
  $options_bank = array();
  foreach($query_bank as $value) {
    //bankID as key
    *$options_bank[$value->bankID] = t($value->bankname);* /** line for which it shows notice*/
  }
  $form['bankID'] = array(
    '#type' => 'select',
    '#title' => t('Select Bank Name'),
    '#options' => $options_bank,
    '#size' => 1,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchName'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Name'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchaddress'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Address'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchcode'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Code'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['ifsccode'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch IFSC code'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
  );
  return $form;
}

/**
* Submit handler for the bank_form. Insert entry into the database.
*/
function bankbranch_form_submit($form, &$form_state){
  $branchID = db_insert('bankbranch')
    ->fields(array(
      'bankID' => $form_state['values']['bankID'],
      'brachName' => $form_state['values']['brachName'],
      'branchaddress' => $form_state['values']['branchaddress'],
      'branchcode' => $form_state['values']['branchcode'],
      'ifsccode' => $form_state['values']['ifsccode'],
    ))
    ->execute();
    drupal_set_message(t('Your form entry has been added'));
}

```

Any suggestions?

# Answer
Your lacking some code.

Try changing your code above with:

```
 $query_bank = db_select('bank', 't1',array('target' => 'import'));
 $result = $query_bank
   ->fields('t1',array('bankID','bankname'))
   ->execute();

 foreach($result as $value){
      *$options_bank[$value->bankID] = t($value->bankname);
 }

```

The `import` keyword above is your database settings. It must be declared in your `settings.php`. Assuming you are using an external database where your `bank` table is located, It must look like the code below:

```
$databases = array (
    'default' =>
        array (
            'default' =>
                array (
                    'database' => 'Name of Your Drupal Database',
                    'username' => 'Username of Your Drupal Database',
                    'password' => 'Password of your Drupal Database',
                    'host' => 'Host of Your Drupal Database',
                    'port' => '',
                    'driver' => 'Driver of Your Drupal Databas', //It can be mysql/pgsql depends whether you are using Postgres or Mysql
                    'prefix' => '',
                ),
            'import' =>  // This Part is where your database that contains `bank` table should be declared.
                array (
                    'database' => '',   //Fill it up according to your database settings.
                    'username' => '',
                    'password' => '',
                    'host' => '',
                    'port' => '',
                    'driver' => '',
                    'prefix' => '',
                ),
       ),
);

```

For more clarification, please refer to this link.
> 1 votes

---
Tags: forms
---


# Question
Title: How to create a content type that incorporates a batch upload and body field, with a gallery output
I'm working on a client site that needs to include event recaps with a gallery of photos for each event under the text recap and event results. They're not very tech savvy so the standard method of creating a view through individually uploading images is going to be too complicated for them, So what I want for them to be able to do

Log in \> Click add content \> Click event recap or similar \> Add a title and a date \> Upload a thumbnail image \> Put in their event results, who won what etc, probably just in a wysiwyg field \> Batch upload images \> Click save

And then for the front end, have a teaser sorted by date under an event recaps parent menu link, and on click the 'page' itself with the text recap, the thumbnail and the images in gallery format.

Is there some way I can combine taxonomy, views, and a batch upload module to make this come together for a less tech friendly user or a module that already does something similar?

# Answer
You could make an image field accept multiple values and set its display to be gallery using one of that two modules galleryformatter, field\_slideshow

And build a view list nodes ordered by the date field selecting one image image from the image field as a thumbnail (using relationships) by setting the delta to be just 1

take a look at how-control-display-multi-value-fields-drupal
> 0 votes

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


# Question
Title: Site name cannot be changed for different languages and domains Drupal 7
I have installed Domain Access, Domain Variable, Variable + i18n integration, etc. I have been able to change the value of site\_lema for different domains and languages, but I cannot override the value of site\_name, which is taken, apparently, from the Domain Access human readable name. I don't understand if that is a limitation, if I have something wrong in my Drupal (I have tested in two different installations), or there is some conflict with other module? Someone has achieved to have site\_name changed for every possible domain/language combination?

# Answer
> 0 votes
It seems that the option in Domain Access "Override site name with name of domain." was causing all the problems. It was so simple, but was driving me crazy. It was checked and thus if I tried to change the value elsewhere (in the Variables section or in the Site info section), nothing happened, the value was not changed. Unchecking this option ("Override site name...") in the Domain Access configuration, this variable "site\_name" can have multiple values depending on language and domain combinations.

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


# Question
Title: Column multiplication and keep the result in separate column
I am trying to create a report where in I want to perform the column multiplication and keep the result in separate column, say column name as "**total**" and finally need to calculate the sum of the total column. So far I have tried with view calc module and searched for other option but I am stuck I am not able to achieve this! I have attached a simple report also. Can anyone help on this please?

# Answer
Have you looked at the Matrix field module? It provides a table with fields in each cell, it's possible to define calculations in some of the field.

I'm the co-maintainer of the module if you have any problems.
> 0 votes

---
Tags: views
---


# Question
Title: Is there a real-time inline field validation module?
Currently I'm using the Clientside Validation module for field validation, but I want to have per field real-time validation, like a check thingy showing if it's correct or a small inline error when there's an error in there. I searched a bit and I couldn't find a proper module.

Is there a module for this?

# Answer
> 1 votes
Have you tried RichForm ?

> **The module has two actions:**
>
> Validation: The validation has a client-side and a server-side routine.The first one is linked to the onChange JavaScript event: after the user modifies the selected field, the validation action is triggered. If there is any error, inline feedback is provided. There is another client-side routine, which is triggered after clicking on the submit button. If there is no error, the server-side validation routine is triggered.

# Answer
> 0 votes
Inline Form Errors I thinks it is better for you

> IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.
>
> IFE provides three behaviours for the configured forms
>
> Leave the messages in place, this option will copy the error messages and place them inline. The original error messages set by Drupal will remain in place Show an alternative message, this option will replace the original messages with a generic error message such as 'Please correct all errors.'. This message can be set in the IFE configuration page. The original error messages are placed inline with the form elements Remove all messages, this option will remove all error messages and place them inline with the form element In all cases only the messages related to the form will be touched. All other messages will remain in tact.

---
Tags: forms
---


# Question
Title: Conditional fields not working with hierarchical select module
**Case:** I am using the Hierarchical Select module for allowing users to choose taxonomy terms from a particular vocabulary. Based on the chosen terms (deepest level), I want to display a field using the Conditional Fields module.

Currently, the Conditional Fields module is working for simple select widget. But not for Hierarchical Select. Is there any hook or patch available?

# Answer
> 0 votes
Actually I found Conditional field to work with HS but you must enter numeric value of the dependee. For Example if you want to display the field only when term "abc 1" is selected then you check what is the numeric value of that field in the database .lets say the value is 12. That's all you need to enter an its working

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


# Question
Title: Configuration page in Modal Forms not working
I already install Modal Forms in my localhost website and it worked perfectly, but now when I installed for my online website I can’t make any change in the configuration page, always forbidden page coming when I change the configuration and save it while I am admin user \[Uid=1\]

# Answer
In *Drupal 7*, the installer tests for compatibility with *Clean URLs* as a part of the installation process. If the environment is tested as compatible with *Clean URLs*, it will be enabled as part of the installation process and no further action is required to enable *Clean URLs*.

If you need to enable *Clean URLs* post installation, *Drupal* will run the clean URL test automatically when you navigate to the *Clean URLs* configuration page;

`Administer > Configuration > Search and metadata > Clean URLs`, show the results, and allow you to save configuration.

You can enable or disable it at a later time by following these steps:

Navigate to the Clean URLs configuration page;

`Administer > Configuration > Search and metadata > Clean URLs`.

Wait for the automated Clean URLs test to run.

Check or uncheck the *Enable clean URLs* checkbox.

Click "*Save configuration*".

Even if *Clean URLs* are successfully enabled at install-time, if you have a dedicated server you may still want to follow the steps (below) to enable the more efficient `httpd.conf` rewrite method for clean URLs. If you choose to do that, you might want to turn off *Clean URLs* while you are working on the server.

If your *clean url* is not working enable `rewrite_module` from server.
> 1 votes

---
Tags: chaos-tool-suite
---


# Question
Title: How to create a renewal request from the subscription page?
I have 2 content types: a **subscription** and a **renewal\_request**.

I would like to have the possibility for the user to **create a renewal request from the subscription page** (or from a *view of subscriptions using VBO*).

The renewal needs to be a content type, as there is a workflow associated to it (*manual verification of user details*).

What would be the best solution? Create a link passing the **nid** of the subscription and use the Entityreference Prepopulate module? Or overriding the form?

# Answer
> 1 votes
If I understand your question correctly, you are using the Entity reference module on you `subscription` content type to point to a (new) node of the type `renewal_request`.

The Entity connect module extends the Entity reference field by providing an add and edit button:

> The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.
>
> The "edit" button will take the user to the edit form of the referenced entity. Once the user is done editing, he is sent back to the previous form.

You could also use the Inline Entity Form module:

> Provides a widget for inline management (creation, modification, removal) of referenced entities.

---
Tags: forms, entities
---


# Question
Title: How to alter default ajax_view default ScrollTop?
In `ajax_view.js`, the code responsible of smooth Ajax View ScrollTop when changing the exposed filters is the following :

```
Drupal.ajax.prototype.commands.viewsScrollTop = function (ajax, response, status) {
  // Scroll to the top of the view. This will allow users
  // to browse newly loaded content after e.g. clicking a pager
  // link.
  var offset = $(response.selector).offset();
  // We can't guarantee that the scrollable object should be
  // the body, as the view could be embedded in something
  // more complex such as a modal popup. Recurse up the DOM
  // and scroll the first element that has a non-zero top.
  var scrollTarget = response.selector;
  while ($(scrollTarget).scrollTop() == 0 && $(scrollTarget).parent()) {
    scrollTarget = $(scrollTarget).parent();
  }
  // Only scroll upward
  if (offset.top - 100 < $(scrollTarget).scrollTop()) {
    $(scrollTarget).animate({scrollTop: (offset.top - 10)}, 500);
  }
};

})(jQuery);

```

I tried to alter this behaviour from a custom module, but no way to get it working. How can I proper change the values of `offset.top - 10` to `offset.top - 100` ? Here's one of my several tries...

```
function MYMODULE_init() {
  drupal_add_js( drupal_get_path('theme', 'MYTHEME').'/assets/js/MYSCRIPT.js');
  //...

//IN MYSCRIPT.js
Drupal.behaviors.events = {
  attach: function(context, settings) {
    $('.my_view', context).ajaxStart(function(){
      $('.my_view', context).fadeTo(500, 0.7);//this works
    });
    $('.my_view', context).ajaxSuccess(function(){
      $('.my_view', context).fadeTo(300, 1)//this works
          .animate({scrollTop: (offset.top - 100)}, 500);//this doesn't
  //...

```

# Answer
> 1 votes
Thanks to @Clive comments, I solved it

* copying the whole `Drupal.ajax.prototype.commands.viewsScrollTop` in my js script
* editing that copy with my own values
* adding a heavy weight to that script :

```
function MYMODULE_init() {
  drupal_add_js( drupal_get_path('theme', 'MYTHEME').'/assets/js/MYSCRIPT.js', array('weight' => 25));
  //...

```

# Answer
> 1 votes
As @Clive mentioned it is because your `JS` order load is wrong(your JS loaded before than views JS) I suggest you instead add JS in `hook_init` put it in `hook_form_alter` or in `hook_page_preprocess`

```
drupal_add_js( drupal_get_path('theme', 'MYTHEME').'/assets/js/MYSCRIPT.js',array(
            'type' => 'file',
            'scope' => 'footer',
            'weight' => 100,
        )
);

```

---
Tags: views, ajax, javascript
---


# Question
Title: Load Javascript Conditionally Based on Form Value
I have two different kinds of webforms, one I'll call "type 1" and one I'll call "type 2". Depending on the type of webform, I want to conditionally add either type1.js or type2.js. The type of webform is has a hidden field called formtype that an admin would set either to "type1" or "type2," and then, theoretically, I would pull in the proper Javascript based on that value when the form loads.

My hook\_form\_alter() function looks like this:

```
<?php
/**
 * Implements hook_form_alter().
 */
function module_name_form_alter(&$form, $form_state, $form_id) {
  if($form['submitted']['formtype']['#default_value'] == 'type1'){
    drupal_add_js($js_path . 'type1.js');
  }
  elseif($form['submitted']['formtype']['#default_value'] == 'type2'){
    drupal_add_js($js_path . 'type2.js');
  }
}
?>

```

This *does* actually cause the proper javascript to load, but I get a Drupal message saying:

```
Undefined index: submitted (etc.)

```

My question is: why would I be receiving this error message even though the logic appears to work? I'm also open to other ways of handling this use-case.

FYI, I'm using Drupal 7.

# Answer
> 2 votes
You applied this code for all forms on your site, but only webform has `$form['submitted']` element. To fix this issue you may use next code snippet

```
<?php
/**
 * Implements hook_form_alter().
 */
 function module_name_form_alter(&$form, $form_state, $form_id) {
   if (!empty($form['submitted'])) {
     if ($form['submitted']['formtype']['#default_value'] == 'type1'){
       drupal_add_js($js_path . 'type1.js');
     }
     else if ($form['submitted']['formtype']['#default_value'] == 'type2'){
       drupal_add_js($js_path . 'type2.js');
     }
  }
}
?>

```

---
Tags: webforms
---


# Question
Title: What are the advantages or disadvantages of using reference based modules instead of taxonomy module?
**I wonder how to decide either to use core Taxonomy module or Entity Reference module?**

I didn't use Entity Reference module before but I've used the taxonomy module (and some related modules) on 10-15 websites.

**What are the advantages or disadvantages of using reference based modules instead of taxonomy module?**

---

Recently, I've started to build a magazine archive website.

There are lots of magazines. These magazines have issues. Each issue has articles.

The smallest (and deepest) part here is the **articles**.

## Article

* Page number (range):
* Title:
* Author:
* Article type:
* Keywords:
* *Magazine:*
* *Issue:*

## Issue

* Issue number:
* Cover image:
* Date (published):
* *Magazine:*

## Magazine

* Description:
* Cover image:

Here, there are (at least) **2 methods** to implement this website:

**1.** There will be a content type called `article` and all others (issue, magazine, author) will be taxonomy terms (hierarchical). There would be a hierarchy between issue and magazine etc.

**2.** There will be lots of content types: article, issue, magazine, author. While creating articles; issue, magazine and author could be referenced etc.

**So, theoretically both ways are seem very similar.**

## Is there anybody who faced similar situation and could you please say which method you preferred, why?

# Answer
There are also other solutions to your problem.

# Field Collection

You can use field collection and field collection views modules to store and organize contents. Using this approach the `Issue` and `Magazine` are going to be Field Collection type, `Issue` is a field of `Article` and `Magazine` is a field of `Issue`. I have experience of implementing such structure. In my case the requirement was a `Library` that should contain books (with Title, Publisher and ... fields), Every book contains multiple volumes (Number of pages, translator, ... ) and each volume also contains unlimited number of some other items (like the scan of some pages that are not the same among the books).

I implemented this using Field Collection approach and it is very nice. You can easily create a link to edit every individual items of every field collection and you can also filter by items of field collection. I posted an answer to Group items in Views by value in Field Collection which shows how to work with Field Collection Views

# Entity View Attachment

Also known as EVA module.

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

*You can use EVA to display only fields values for a particular piece of content, giving incredible control over the display and formatting flexibility of the fields. For example you may desire to have two fields concatenated in some special way. You can add your fields to your EVA display, set the contextual filter to NID, add a Global: Text Field, and using tokens format your fields with HTML. Don’t forget to exclude your fields from display if you are going to use them together in a Global: Text Field. Example: You may have a city, state, and zip fields. You can combine them in a Global: Text Field in Views to display as “City, State ZIP”. When you manage the display for your content type add the EVA just created to the display and whenever a node the type is displayed it will pass its nid to the EVA and the EVA will return the fields you select, formatted as you desire. (source : EVA and Entity Reference Use Case How-to)*

This module is perfect, It attaches a View as a field to nodes of a content type. I used this module to create an `Album`. The album contains `singer` (with some information about each one) and `songs` that contains a File, Title, Rate and ... . So I created a View of type *EVA* and I attached it to a node. So on the node page of every Singer, I displayed this View which gets it's appropriate information from the node. The Views with Entity Reference is a perfect tutorial of how to use this module.

# Taxonomy Terms V.S Entity Reference

I recommend you to read Entity reference vs. taxonomy and Are there any benefits/caveats with using Entity Reference over Term Reference? , As it says *Taxonomies are best used when organizing similar items in a hierarchical fashion. Like tags*.

Taxonomy allows you to use free tagging (it can be disabled using **Content Taxonomy** module), which enables the creation of new tags on-the-fly. It is very easy to modify the skeleton of contents. Using this approach, regular or at least some authenticated users (who have no knowledge of programming) can change this skeleton. Hierarchical Select module is perfect example of such approach.

Even though Taxonomy is easy to use but I myself prefer Entity Reference, it opens up lot's of possibilities and scalability and allows of creation very complex structures. The concept of entity in this context is not limited to content. It can be comments, users, taxonomies and ... . It is much more scalable so you will not be worry about the customizing content types, or modifying it in the future (as it was pointed out in *Entity reference vs. taxonomy*). I believe the Entity approach is more powerful than Taxonomy.

There are also some other combinations of these approaches which it is unnecessary to mention them.

Anyway I recommend you fully understand Entity approach and it's related modules. If you use it in multiple projects, despite of it's complexity it will be very easy to you to use it. Not only in the yours current requirement but also in the future it is going to be a **Very Reliable Tool** for you.
> 9 votes

# Answer
You could also have some other combination, like articles and issues are nodes an magazines are taxonomies.

There isn't really a right or wrong answer for this it comes down to personal preference, specific project requirements, etc.

It is best to use nodes for content and taxonomies for categorisation of that content, however sometimes it can get a bit murky as to whether something is just categorisation or its own content.

For example, your article type and keywords fields would seem to more obviously be taxonomies, but issue and magazines could really go either way.

One thing that could influence your decision is out of the box functionality. For example, there are a lot more add-on modules for nodes than there are for taxonomies but for taxonomies you get out of the box listing pages (if you want them). There might also be hierarchy related functionality that is easier to get out of the box with one solution or the other.

Content type definitions are only part of the picture. You should definitely fully consider how you intend the content to be presented to the user, how you want the user to navigate through the hierarchy of content, how does this content relate to other content on the site, how do you want admins to administer this content, etc. For example, do you want some sort of hierarchical menu system, do you want people to be able to go to magazine or issue pages or is content related to those only visible on the article pages. Do you want to have a single search that lists all 3 types of content (this may be less trivial if some are nodes and some are taxonomy terms).

Plan all that out and then see what modules are available to help you achieve that. You might find one way will make it easier to achieve what you want. If not then you just have to go with the one you think is best for whatever reasons you have.

Sometimes you may go one way and then find something that makes it difficult to achieve your requirements. If you plan it up front as much as possible you lessen that risk.
> 8 votes

# Answer
One other consideration when using taxonomy terms for things like "Magazine" is that you will lose out on functionality such as revisioning and comments on those items. Granted revisions can be added with a module such as Taxonomy revision but that's a module with a very low install base. Personally I'd trust core's on revision handling on nodes over this.

I can think of at least one occasion when I've had to change something from a taxonomy term to a node after a project has gone live due to changes in the requirements, and this involves a fair bit of restructuring and migration.

You'll probably find that if you do move to using other entity types such as nodes with entity\_reference then there you won't have any trouble making the change as everything works in much the same way but it will give you more flexibility.
> 5 votes

# Answer
I won't say this is the most accurate answer, but it is how I think about it. I will explain with some examples.

I usually use taxonomies to categorize nodes based on an abstraction. For example, news can be categorized into sport, political, etc.

But when I want to have a reference like a magazine I am thinking about the future. Think about when you want to help the user decide which article to choose. Magazine rank (Impact Factor maybe) is a possibility. Or maybe I want to contact that magazine. A term would not help me in this situation, where if it were a node or entity it would.

On the other hand you have to do some stuff by yourself. For example, clicking a taxonomy term would lead you to a page filled with categorized nodes of that term. So now a view and a contextual filter is needed, etc.
> 3 votes

# Answer
I was sure someone asked why I would stay away from field collections, but the comment appears to have been removed. Either way my 2 cents:

Taxonomies should be used for classification and categorisation. Not for content relationships. By linking 2 pieces of content via a taxonomy term you are using 3 entities where you only need 2.

In my experience, whilst taxonomies are now fieldable, they are not fully fledged entities, and so should not be used as "content".

In this particular case, if your Magazine has content (a description of what is it, details on ordering it etc.), or a "page" of its own, then it should be a content type, because it is content.

The issues are are a little ambiguous, but odds are you have an overview etc, so they likely have a page, and are likely content too. So another content type.

The articles are obviously content types.

In building the admin for this you can use the Entity Reference to link these pieces of content, but you can go one better.

In the same way that @Drupalist suggested using Field Collections, you can use inline entity forms (I think part of Entity Reference). Field Collections are one of these old modules that where a great idea, not very well implemented, and with many collisions with other modules. Whilst they are now entities, they still have issues, and you would be better using fully fledged entities (even content types) for things like you authors etc.

Inline entity forms lets you create and edit referenced entities, from inside the entity you wanting to reference from... so, create/edit author from inside an article, or just reference one that has already been created.

Add in CER and you will automatically get a reference from the author back to the article, the article back to the issue, and the issue back to the Magazine, or whatever direction you are going. This has advantages in how your views perform, but also lets you show a list of articles on the author page, and the author info on the article page, all without views at all.

Full circle back to taxonomies, you would then use these to "tag" articles etc. with... "fishing", "car", "computers" etc./whatever... so you can find any issue, magazine, article or author that has content/written about that tag.

Tried to make that brief, so hopefully it helps and makes sense. I have done this on dozens of sites. Global sporting events, travel/holiday booking sites, international broadcasters, beverages, charities etc. Robust powerful, and covers you for unforeseen requirements.
> 3 votes

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