title: drupal Newsletter based on taxonomy

text:
# Question
Title: drupal Newsletter based on taxonomy
I make a content type that called "commission". And also I have created a Taxonomy called "commission" too. In the taxonomy we have some terms like "Fun" or "sports" and etc. When the user want to create commission node, they should choose one of the taxonomy terms. Now my question is this: I want a module to make a subscribe link for people that they can subscribe on the content with the just "sport" taxonomy term or "fun" taxonomy term or something else. It means I need a subscribe Newsletter module based on the Taxonomy terms. What shall I do?

# Answer
> 0 votes
Try using Total Subscription which says :

Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.

Or you can try Simplenews module as well, which has feature of rules integration so that you can customize it with taxonomy.

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


title: Change custom entity fields

text:
# Question
Title: Change custom entity fields
I'm facing very strange problem with changing my custom entity's fields. I've a custom entity with `id`, `type`, .. , `premium`, `premium_expires_at`, .. fields. It was working without any problems with its own fields (those declared in hook\_schema()) till today, but suddenly I changed its fields, dropped `premium`, and `premium_expires_at` fields, added new fields with `HOOK _update_n` function. I see database schema changed, but those deleted fields are still being shown in `base table` key under `field_sql_storage` key.. I've already ran update.php (many times), but no luck.. I thought it's a caching problem, so I've cleared all caches manually, and with drush, no luck, cleared memcached data (with telnet), any changes.Every time I'm getting the same error, like this:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'base.premium' in 'field list': SELECT ... base.premium AS premium... в функции EntityCacheControllerHelper::entityCacheLoad() (строка 101 в файле /PATH\_TO\_MY\_PROJECT/sites/all/modules/entitycache/entitycache.module)

I don't have any `premium` field in my db schema, but still getting this error, is there any way to solve it?

(I am using EntityAPI with Entitycache and Memcache Storage modules).

# Answer
> 0 votes
I finally solved this problem somehow.. I think this is an EntityAPI's issue. So, here is my (temporary) solution:

* removed those changed fields directly from `hook_schema`, added new fields directly to it.
* removed those fields with `db_drop_field` function and added new fields with `db_add_field` function with `hook_update_n` function. By this way I managed to have the same structure in my (changed) entity and db table schema.
* flushed the caches

Error has gone, so far everything is working fine. But I'm not sure this solution will not cause any problems in future... I still can't understand why entity api doesn't see changed fields in `hook_update_n` function...

---
Tags: 7, entities
---


# Question
Title: Drupal Commerce - Update profile on order without cloning?
I understand the reasoning behind preserving integrity of data for existing orders tied to profiles, however...

I have a page where the user can edit the order contents and change their billing or delivery information. Instead of create a new profile, I would like to save the data directly to the order being viewed. I don't want it to affect new orders created later, either.

How can I do this? It would seem that every time commerce\_customer\_profile\_save is called, a brand new profile is created.

This isn't a standard commerce workflow, but most of the fundamentals are there. A customer can have many open orders at any given time, and I want the flexibility for them to change the delivery address ON a specific order and save it for that order only. Someone out there has to have done this I would believe.

# Answer
How about something like this leveraging Drupal's Entity API:

```
//assume we retrieved the $order_id via a page callback argument or something similar
$my_order = entity_load('commerce_order', array($order_id));

$billing_profile_id = $my_order[$order_id]->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'];
$billing_profile = entity_load('commerce_customer_profile', array($billing_profile_id));

// **replace this comment with PHP logic to update the profile values**

//save our customer profile object using the updated values from logic above
$success = entity_save('commerce_customer_profile', $billing_profile[$billing_profile_id]);

```

This allows us to directly edit the customer profile object associated with a particular order, and leaves the rest of the profiles unaffected.
> -1 votes

---
Tags: 7, commerce
---


# Question
Title: Copy values from taxonomy term field to new text field in content-type
I have a content-type with a certain taxonomy term field that allows **multiple** values.

I don't need this field to be a taxonomy term field anymore, but just a simple text field. So, I want to "**transform**" the nature of the field.

I do know it is not possible and that I have to create a new text field and **copy the values** of my first field into my second through a custom php script.

But I hardly think that I'm going to need some help from you guys for the SQL query that will be a bit complex.

* I need to recover all the term's names for each piece of content
* and, if there are several of them, concatenate them with a comma (for example),
* and then copy the result in the new text field before deleting the old taxonomy field.

The truth is I have no idea how to proceed. Can I run the query directly in PhpMyAdmin? Or in a PHP file? Do I need to use a simple SQL query or an EntityFieldQuery class? I'm not very familiar with this kind of stuff.

Thanks in advance for any clue...

# Answer
According to me you can achieve it by doing something like:

Creating a PHP script which: Get all terms related to a node and then create a comma separated value for them and then store this as value of your new field in database.

You need to iterate over all nodes and the run following code to get all terms

```
$result = db_query(
SELECT ttd.tid, ttd.vid, ttd.name, ttd.description, ttd.weight
FROM taxonomy_term_data AS ttd
INNER JOIN taxonomy_index ti ON ti.tid = ttd.tid
WHERE ti.nid= :nid
ORDER BY ttd.weight, ttd.name',array(':nid' =>$node->nid));

```

Or you can use Drupal code as well for doing the same

```
$node = node_load(arg(1));
if ($node != NULL) {
$field = $node->field_my_vocabulary;
$lang= $node->language;
$terms_all = $field[$lang];
foreach ($terms_all as $term) {
$terms[] = $term['tid'];
}
return implode('+', $terms);
}

```

Now assign this vale to you new field.

The above code is not tested by me, but I hope it can do what you want with no/little modification :)
> 1 votes

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


# Question
Title: How to make existing fields available to be created as instances on other content types etc.?
I have created a custom module that simply creates a set of standard fields via a .install file. It's very simple, basically:

```
foreach (my_fields_fields() as $field) {
  if (!field_info_field($field['field_name'])) {
    field_create_field($field);
  }
}

function my_fields_fields() {
  return array(
    'field_my_first_name' => array(
      'field_name' => 'field_my_first_name',
      'type' => 'text',
    ),
    ...

```

On enabling the module, I can see that the fields have tables in the database. However, if I navigate to `admin/structure/types/manage/article/fields` and drop down `- Select an existing field -` in the `Add existing field` section, the fields are not present.

I don't want to create any instances of my fields in my module (do I?) because it is for other users/systems to create field instances if they want to.

How do I get Drupal to make my fields available? Thanks.

# Answer
> 1 votes
An 'existing field' in that context is one that already has an instance, it doesn't refer to the existence of the field *type*. Until an instance is created, it doesn't exist as such.

Your field will be available to add as a new field as usual; if you want it to appear under 'Add existing field' section, you'll need to create an instance of it first.

---
Tags: entities
---


# Question
Title: Using db_select to only get the latest nodes with a certain field value
I have extending a query function for a D2D migration. The nodes have a field on them for a certain type of ID. In the old D6 site the the field did not have to be unique, but in the new D7 site the field does have to be unique.

I want to use db\_select so that I only get the newest nodes in the content\_type\_nodetype table if there are multiple nodes with the same value for that id field.

Sample table data:

```
content_type_nodetype
____________________________
| nid | field_someid_value |
|==========================|
| 1   | 12345              |
| 2   | 12346              |
| 3   | 12347              |
| 4   | 12345              |

node
____________________________
| nid | created            |
|==========================|
| 1   | 1292780734         |
| 2   | 1292780735         |
| 3   | 1292780736         |
| 4   | 1292780737         |

```

Given that data, the query I want should only return nid 2,3, and 4 as the value for field\_someid\_value for nodes 1 and 4 are the same, but the created timestamp in the node table for nid 4 is later than the timestamp for 1.

# Answer
> 0 votes
It turns out there was another (custom) table in my legacy database which held another set of data for those specific IDs and the node ID's associated. All I had to do was join with that table on the specific ID and set a condition for the nid to equal the nid above.

# Answer
> 1 votes
You might try something like :

```
$query = db_select('node', 'n');
$query->join('content_type_nodetype', 'ct', 'ct.nid = n.nid');
$query->groupBy('field_someid_value');
$query->addExpression('MAX(n.nid)', 'nid');

```

The 'nid' order must follow the 'created' order so you won't need to order the results. Just taking the biggest nid for each field\_someid\_value should do the job.

---
Tags: database
---


title: Submit data into database

text:
# Question
Title: Submit data into database
I have read a great deal and trying to learn how to get data into a table in the db. I have the below code to test entering just the first name of someone and I am getting an error. I have tried to follow the examples.module but I am missing something. I would appreciate a nudge in the right direction...

```
function ghost_form_form_submit($form, &$form_state) {
$entity_id = db_insert('field_data_field_first_name') // database table name
  ->fields(array(
    'field_first_name_value' => $form_state['values']['field_first_name_value'],
  ))
  ->execute();

drupal_set_message(t('Your form entry has been added'));
}

```

Here is the complete form code... https://gist.github.com/anonymous/f6d8dc19a3eed0f56d59

The only error I get in watchdog is the $entity\_id. However I am not sure what I am missing. Thanks

# Answer
This message is probably because you missed some database fields in your insert query (we do not know the field type and what exactly you are trying to achieve). Other than that, it is very odd that you attempt to insert a record directly in a Drupal field's table as this not how it is meant to be used. As per Clive's comment, this can lead to data inconsistencies, cache issues etc.

So I would strongly recommend you to take a good look at Drupal examples on **how to define a custom table** using Schema API, or even better take a look at this guide on using the Entity API, which you allow you to properly utilize Drupal Fields with your own custom module. Third option is to use the API of an existing module such as nodes, users etc. so that you properly save the field's value.
> 2 votes

---
Tags: forms, database
---


# Question
Title: drupal 7 parent menu item will not hide for authenticated user
Could any one give me some ideas on what i need to check please?

I wish i could just show the site, but of course it' for my company, so I can't, but I have a menu bar at top of my page home, contact, meet the authors, books;

Under "Meet the authors", i have several authors, I created an authors content type and have one for each author. When you hover over "Meet the Authors" you see the drop-down list/sub-menus of the authors - only five of them now.

so using panels and views, when you click of "meet the authors" you see a list of the authors on the page and can click in for more detail.

Using the access control module, I only want this link to appear for anonymous users, once logged-in, this link should disappear but the link will not hide itself after login, but here is what's really odd, the sub-links which are the authors, those links/sub-menu do/does hide when the user logs in and only displays for the anonymous user

so for example, this enable menu should appear for the **anonymous** user

Meet the authors \- ----Kim Fields \- ----Tony Bruewer \- ----Harris Carlton \- ----John Brown

and should be completely hidden for the authenticated user, but what is happening though, upon login, the user sees the parent menu: Meet the authors

but the sub menus have hidden themselves as they should, i just can't get the parent menu to hide itself.

I have checked the access control to make sure I have selected things properly. I even created test content type and menus to test and everything worked, so I assume there is something different, but I just can't see what and where.

Any ideas and guidance would be greatly appreciated. Thank you.

Notes: the parent menu about \[Meet the authors\] is pointing to a panel page that contains a view to display the list of authors. I do not have access setting on the panel.

***More Information***: So for my own sanity, I slowly created another content type, a view for that content type and a panel page. Saved, cleared cache, ran cron. Change settings in control access module. Here is what I now see-- The sub-menus of the parent menu \[Meet the authors\]are following the authentication rule, the top menu just displays all the time. I create this mention from the Structure-\>Menus navigation. So the top menu item is pointing to the panel whereas the sub-menu items are actually the content types.

**Still more Info:** Here is what I think the issue that I still have not found a way around. I create the view, create the panel, place the view in the panel, give the panel page a normal menu entry. So that is my menu item that appears. If I click on that top parent link, it takes me to the panel with my view, but the menu item won't display/hide as needed. So i realized that the menu I am creating in the panel has nothing to do with the content type and the content type is needed to manage the access control module. So I go into my content type, change one of it's types and change the menu to point to the panel url I created. Well when I do that, that url is assigned to that content type node, not panel, but the menu item does, now, display/hide based on the selection from the access control module.

Can anyone give me a way around this? What i think I need is a way to point one of my node content types to the panel. Does this make sense. I love Drupal, but sometimes...

# Answer
Ok, i finally resolved this issue, or figured out what is going on. This is a very specific issue, so posting my solution here, should someone else run into this exact problem.

Ok, so I am using panels in my sites, inside the panels, i have views based on the content types. My top level/parent menu item is pointing to the Panel that holds the View.

The menu item is **NOT** a menu created of/from the content type consequently, the "control access module" didn't do anything with the menu item, because it does not consider it a content type and that is actually correct.

So you know the saying "**there's a module for that**" -- there is a **menu\_per\_role** module that allowed me to update visibility based on **user role**, so I could hide that menu for the authenticated user.
> 0 votes

# Answer
The easiest way with the least amount of programming would be do it with css:

```
body.logged-in .my-menu-name-or-css-class {
  display:none;
}

```

The most standards compliant way would be to use hook\_menu\_alter and unset the menu if $user-\>uid returns true: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu\_alter/7

However, in this case you're probably looking at maybe saving 10kb of bandwidth by unsetting the menu vs. just using CSS to hide it.
> 0 votes

---
Tags: routes, users
---


# Question
Title: Fatal error: Cannot use object of type stdClass Error help!
When trying to access my image file from my database i get this error:

> Fatal error: Cannot use object of type stdClass as array in C:\wamp\www\drupal-7.25\sites\all\modules\database\database\_ex.module on line 99

note: line 99 is **$uri = $value\['url'\];**

```
function database_ex_form_submission($uri) {
  $result = db_query("SELECT myimage FROM example");
  $records = $result->fetchAll();

  $res = $result->execute();

  foreach ($records as $value) {
    $uri = $value['url'];
    $url = file_create_url($uri);
  }
}

```

What seems to be the problem?

# Answer
You say :

> note: line 99 is $uri = $value\['url'\];

So:

`$value` isn't an array and you can't write `$value['url'];`.

In fact `$value` is an object and you have to use this syntax `$value->url;`
> 1 votes

---
Tags: 7, database
---


title: Clone several nodes

text:
# Question
Title: Clone several nodes
I'm searching a module to clone several nodes automatically when i create a project node type. To explain better : When i create a new node of Project type for exemple, i need to clone some nodes and tie this nodes to my node project.

I have tried node\_clone but we should use a button to clone the node. For the moment i developped a small code to clone my node like this :

```
$p1template=variable_get('myvar_p1');
$p1=node_load($p1template);
unset($p1->nid);
unset($p1->vid);
$p1->title='Processus P1'.$projectid;
$p1->field_px_projet['und'][0]['target_id']=$projectid;
node_save($p1);

```

But i had a second problem with the field\_collection. when i cloned the nodes, the field\_collection keep the same reference and when i modify a field collection, all the nodes cloned field\_collection was modify...

How can i fix this problem ?

PS : Sorry for my english..

Thx

# Answer
> 0 votes
Node clone module has a hook for this, hook\_clone\_node\_alter(&$node, $context). When you clone nodes programmatically, make sure you alter their state and values inside this function.

```
function module_name_clone_alter(&$node, $context){
    switch ($context['method']) {
        case 'prepopulate':
          // Change field values ....

          break;

        case 'save-edit':
          // Perform operations when saving the node.

          break;
      }
    }

```

---
Tags: nodes, entities
---


# Question
Title: Batch operation for consuming data from API via drupal_http_request
I am consuming data from an API which provides a URL similar to: **http://data.something.com/api/records?pageIndex=0&pageSize=25**

The API will return XML which I will then use to create nodes. There are many thousands of records, so I will need to do this via batch. I have used batch before but never for drupal\_http\_request. What would be the best approach for this? Is batch API the best solution, or would another method be preferable?

Thanks

# Answer
> 2 votes
Hi You're probably best off using the feeds module to import from feeds it can do them as one off imports imports or periodic batch jobs and create nodes from the feeds automatically. Even though they're beta/alpha they're well used and actively developed.

---
Tags: batch-operations
---


# Question
Title: How to print a custom user field in comment.tpl.php?
I'm trying to print a custom user field (field\_avatar) image as a replacement for the user picture. Why? user picture file directory would not accept tokens. This mean, I could run into a scenario where there are 100k files in a directory slowing the website!

From googling answers for hours, this is the best solution I've read.

In comment.tpl.php placed in my custom omega 4 subtheme, I added this code.

```
<?php  print render(field_view_field('user', $user, 'field_avatar'));  ?>

```

However, above code prints the default field\_avatar picture! not field\_avatar based on the comment ID? or UID of the author?

Please shed some wisdom smart ones!

# Answer
> 2 votes
I've got it working! I've used user\_load($comment-\>uid) to load the author relationship.

I placed the code in a copy of comment.tpl.php in my sub theme.

```
<?php print render(field_view_field('user',user_load($comment->uid), 'YOUR-CUSTOM-USER-FIELD'));?>

```

Cheers and good luck!

# Answer
> 0 votes
You need to reference the $author of the comment rather than the currently logged in $user. Luckily, $author comes as a parameter to the tpl file, try this?:

```
<?php
  print render(field_view_field('user', $author, 'field_avatar'));
?>

```

---
Tags: 7, theming, entities, hooks, comments
---


# Question
Title: Menu Block - How to make a new menu automatically available?
How to automatically set a newly created menu as available so that it can immediately be used when configured for "the menu selected by the page"?

I've tried setting the 'menu\_block\_menu\_order' variable through code, upon a new menu creation, but haven't figured it out.

What's the best way to automatically set a new menu , or all menus, as available?

# Answer
> 1 votes
I'm not very familiar with the Menu Block module, but this seems to be the proper way of setting the menu\_block\_menu\_order variable when a new menu is created:

```
function mymodule_menu_insert($menu) {
  $menus = variable_get('menu_block_menu_order', array('main-menu' => '', 'user-menu' => ''));
  $menus[$menu['menu_name']] = '';
  variable_set('menu_block_menu_order', $menus);
}

```

---
Tags: blocks
---


title: views exposed filters capable for this?

text:
# Question
Title: views exposed filters capable for this?
I try to create something like questionnaire using views exposed filters. I have a content type xxx with fields:

```
field_1 (with options a,b,c)
field_2 (with options a,b,c)
field_3 (with options a,b,c)

```

I have 9 nodes, each containing only one option (node\_1 has only "a" option from field\_1 selected, node\_2 has only "b" option from field\_1 selected etc... so together 9 nodes)

Task: User chooses from 3 dropdown lists. For example choices are (field\_1 - a, field\_2 - a, field\_3 - c)

I need the result to contain :

```
node that has field_1 with option "a" checked
node that has field_2 with option "a" checked
node that has field_3 with option "c" checked

```

Is this possible to acheive using views filters or I need another solution? I would like to use any views solution Thank you.

# Answer
This seems to be a bug in the Views module. If you have an OR filter group, Views will incorrectly use INNER JOIN instead of LEFT JOIN in the query.

One solution is to patch Views - more info & patch: https://www.drupal.org/node/1766338

Another solution that is using hook\_views\_query\_alter that changes the join type by modifying the query object: Changing an inner join to a left join in views 3.3?

A third solution (see comment below) is to check the "Reduce duplicates" checkbox for the filters in the OR group.
> 1 votes

# Answer
Yep. In your view, set create a filter criteria for each of your fields.

check expose this filter to visitors, allowing them to change it.

Operator should be "is one of"

Edit ------------------------------------------------- I've recreated your issue on my local machine, and am seeing the same issues you are. I have had some success with creating group like this:

I'm only using 2 filters, but selecting \[any, a\] does give me back 1-a, 1-b, 1-c, 2-a. However, if I select ANYTHING for field 1, that seems to kill it. It's seems as though if views gets a match for the first group, it doesn't try the second... I'll keep trying to figure out what's going on here... very strange.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to flag a View's item (with AJAX) when hovering or clicking it?
In my previous question How to mark a Message as 'viewed' when a user sees it in a View?, I explained that I'd like to flag a Message when it's hovered or clicked in a View. @Geoff suggested to create an AJAX callback in his answer, but I've no idea how to accomplish that.

How can this be done? Is this the easiest approach?

# Answer
The entire process may seem a little complicated at first, but it's easy once we break it down into smaller parts and understand how it all comes together.

Basically we have two parts which we need to address. Firstly the "backend" logic where we will be implementing hook\_menu, allowing us to receive an AJAX request via a custom menu route and then flag our Message as seen. Then secondly the "frontend" logic where we'll be implementing a little bit of jQuery to trigger our AJAX calls (using the proper Drupal.behaviours way of course) :)

With this example I'm assuming you have created a Message entity and have added a boolen field to it. We'll use this to store our flag to indicate whether the Message has been "seen" or not.

Once you've done that, go ahead and create a simple custom module and implement hook\_menu using the following example:

```
/**
* Implements hook_menu().
*/
function my_example_menu() {
  $items['my_example/message/seen/%'] = array(
  'page callback' => 'my_example_flag_message',
  'page arguments' => array(3),
  'access callback' => 'my_example_message_access',
  'access arguments' => array(3),
  'type' => MENU_CALLBACK,
  );
  return $items;
}

```

Now before we start writing the page callback function which will flag our message as seen, we need to make sure that we implement proper access rights. This ensures the user accessing our custom menu route actually "owns" the message, and isn't some malicious hacker trying to annoy us and mark all the messages on your system as "seen" as some kind of lame prank haha! See below:

```
/**
 *  Access callback to ensure user has the right to message entity
 */
function my_example_message_access($msg_id) {

  global $user;

  $access = TRUE;

  //if anonymous user then throw access denied
  if(!$user->uid) {
    return FALSE;
  }

  //load our message entity and check the uid
  $msg = entity_load('message', array($msg_id));

  if($msg[$msg_id]->uid != $user->uid) {
    return FALSE;
  }

  return $access;
}

```

You can test the access callback by visiting **http://example.com/my\_example/message/seen/\[MESSAGE\_ID\]** and trying out different message id's logged in as different users. If a message doesn't belong to you, Drupal should be giving you the old "Access Denied" message.

Now that we know our AJAX route is protected by Drupal access control, we can go ahead and write the page callback function which will flag our Message entity as "seen":

```
//page callback function
function my_example_flag_message($msg_id){

  $response = array('success' => FALSE);

  //first check that the message id argument is present
  if(!isset($msg_id) || $msg_id == 0){
    return drupal_json_output($response);
    drupal_exit();
  }

  //load our message entity
  $msg = entity_load('message', array($msg_id));

  //set the flag to TRUE
  $msg[$msg_id]->field_YOUR_FIELD_MACHINE_NAME[LANGUAGE_NONE][0]['value'] = 1;

  //save our message entity
  if(entity_save('message', $msg[$msg_id])){
    $response['success'] = TRUE;
  }else{
    $response['success'] = FALSE;
  }

  //return the status of our attempt at saving our entity back to the front end
  return drupal_json_output($response);
  drupal_exit();
}

```

Great so if you made it this far and didn't fall asleep reading that wall of text, then you should now have a working route which accepts a message id, and marks that message as "seen" (as long as it belongs to you). :)

Then our final piece of the puzzle is attaching a Drupal behaviour to each View row, enabled as to fire an AJAX call to our Drupal route and trigger our backend logic. I'm assuming you know some basic jQuery, but here's the example script you'll need to add to your page using the **drupal\_add\_js()** function or something similar. We'll call it **my\_example.js**:

```
(function ($) {
  Drupal.behaviors.my_example = {
    attach: function(context, settings) {
      //you can adjust this jQuery selector to anything you like
      $('.view-row').click(function(e){
        //I'm assuming the message ID is in view row markup as a data attribe (eg: data-message-id="[MID]")
        var msgID = $(this).data('message-id');
        //trigger our jQuery AJAX call
        $.ajax({
          type: 'POST',
          url: '/my_example/message/seen/' + msgID,
          dataType: 'json',
          data: 'seen=1', //added some arb param here as an example
          beforeSend: function(){
            //if you want to do anything fancy before the AJAX call do it here
          },
          success: function(response){
            //if we successfully updated the message
            if(response.success == true){
              //do something fancy like display a message if you like
            }else{
              //if the update failed display an error message
            }
          },
          error: function(jqXHR, textStatus, errorThrown) {
            //if there was some kind of javascript / jquery error you can debug it here
          }
        });
      });
    }
  }
})(jQuery);

```

And hey presto, we now have some jQuery attaching our Drupal behaviour to each View row which when clicked, will fire off our AJAX trigger and then get Drupal to update your message.

This design pattern opened up a whole host of other ideas (think AngularJS and other exciting geeky tech) for my use of Drupal. I hope it helps you too :)

Obviously if there's anyone else out there with a better implementation please let me know!
> 6 votes

---
Tags: 7, views, ajax, flags
---


# Question
Title: How can I make the fields in my views "searchable?"
So I have several views on my website with specific fields shown in table format. The search bar only searches through specific content, like pages, and basic pages. How can I modify the views or the search function to make it so that words typed into the search bar will search through the text entered for each field displayed in the views?

# Answer
> 1 votes
I would recommend checking out the Search API module. It's an extremely powerful extension to regular Drupal search, allowing you to use many advanced search backends and also integrates with Views to allow you to search on any field you wish.

---
Tags: views, search
---


# Question
Title: Drupal 7 special chars not working in db_select
I have implemented custom search to get some values from node.

When I'm using special chars like "**/, ?, !**", no result is being displayed.

Example value : "**24/7**" or "**site?**" or "**test!**", etc...

```
$search_text = '24/7';
$query->condition(db_or()
->condition('n.title', '%' . db_like($search_text) . '%', 'LIKE')
->condition('fld.body_value', '%' . db_like($search_text) . '%', 'LIKE'));

```

I'm running my site in Drupal 7. **PHP version is 5.5.9. Using Mysql DB.** OS windows.

Note: Query is correct. Its giving proper result for other than special chars.

**Edit:** $query-\>arguments(); is returning below image.

I was running LIKE command in phpmyadmin. Please find that screen shot below.

So what is the modification do we need to do at PDO to support this issue?

# Answer
It doesn't look like anything wrong with query. I'm using drupal 7 with basic setup and one node(nid=3) has 24/7 in title & body and one node(nid=4) has only in body.

```
  // Make sure to decode, if the search string is part of URL.
  // $search_text = urldecode($_GET['query']);

  $search_text = '24/7';
  $query = db_select('node', 'n');
  $query->join('field_data_body', 'b', 'b.entity_id=n.nid');
  $query->fields('n', array('nid'))
    ->condition(db_or()
    ->condition('n.title', '%' . db_like($search_text) . '%', 'LIKE')
    ->condition('b.body_value', '%' . db_like($search_text) . '%', 'LIKE')
  );
  $result = $query->execute()->fetchAll();
  print_r(db_like($search_text));
  print_r($query->arguments());
  print_r($result);

```

and the result is:

```
// print_r(db_like($search_text));
24/7

// print_r($query->arguments());
Array
(
    [:db_condition_placeholder_0] => %24/7%
    [:db_condition_placeholder_1] => %24/7%
)

// print_r($result);
Array
(
    [0] => stdClass Object
        (
            [nid] => 2
        )

    [1] => stdClass Object
        (
            [nid] => 3
        )

)

```

**Note**: If you are getting the search string from URL as query string make sure, you have done `urldecode()` before send to SQL.
> 2 votes

---
Tags: database
---


# Question
Title: Get submitted value of a select list error on #options - Drupal 7
I have seen this block of code in a few places as the correct method:

```
$selected_index = $form_state['values']['select_field'];
$display_value = $form['select_field']['#options'][$selected_index];

```

So here is my code for it:

```
$key1 = $form_state['values']['field_setup_time3'];
$reservationStartPadding = $form['field_setup_time3']['#options'][$key1];

```

But I get this error with my code:

```
Notice: Undefined index: #options in ... blah blah blah

```

I am using a List (integer) running a select list with 4 options in it. Is options not the right choice here? I just need the numerical value from the user selected dropdown list when they submit the calendar booking.

Thanks!

# Answer
Thanks to tenken and Clive I was able to figure it out.

```
$key1 = $form_state['values']['field_setup_time3'];

```

This line outputted as a string. Since I was only using integers in my select list, the label and key value were the same. I removed both lines of code and replaced it with this (after some playing around with devel):

```
$reservationStartPadding = $form_state['values']['field_setup_time3']['und'][0]['value'];

```

This outputted the value as a number and not as a string. I was able to use it from there in my future code correctly.
> 1 votes

---
Tags: webforms
---


# Question
Title: Loading a large node body sequentially for better performance
I have a few very large nodes on my Drupal 7 site. In some cases the body field contains about 2MB of raw HTML (about 250,000 words). Despite the site performing well as a whole, the sheer size of these nodes causes a complete page render to take about 20 seconds, both due to the amount of content being downloaded and the time it takes the browser to render that much HTML.

The only way I can see to improve performance on these nodes is to load the node body sequentially in small bits, fetching bits of HTML as the user scrolls down the page. Is something like that even possible when all the data is contained in one row in the database? Perhaps this is more of MySQL question, but I'm curious if anyone has encountered this before or has alternate solutions to this problem.

# Answer
> 0 votes
It sounds like you've hit an architecture (DBMS) constraint. I'm not aware of a way to break up a node `body` into segments easily (I mean i'm sure you could use a `list of text fields` in drupal -- but ewww).

I'm also not sure of a clean way to make the paragraphs index-able for asynchronous javascript fetching, i believe you run into issues like: https://stackoverflow.com/questions/19477494/per-paragraph-commenting-system

What I would recommend is installing an `in-memory` cache like Varnish, or Memcache and storing a copy of the full page for anonymous users ... or learning Authcache for more complex scenarios.

---
Tags: 7, performance, database
---


# Question
Title: How can I NOT show the Request new password tab within the /user (login) page for one particular user
Drupal 7 /user url goes to a page that has 2 tabs Login and Request new password which is what I want for all of our users except for one. How can I NOT show the Request new password tab within the /user (login) page for one particular user ($user-\>name)?

# Answer
> 4 votes
If you just wish to hide the tab, you can do that by using the Tab Tamer module. However, the user would still be able to access the form through the URL `http://<yoursite>/user/password`.

If you wish to disable (along with hiding) the password tab, you can implement the hook\_menu\_alter().

```
function MODULE_menu_alter(&$items) {
  //condition to check the user
  global $user;
  if($user->id == '<USER_ID_OF_THE_USER>') { //can use $user->name as well
    $items['user/password']['access callback'] = FALSE;
  }
}

```

# Answer
> 0 votes
I found this looking for solutions to the same problem. However, this code will not work because hook\_menu\_alter and hook\_menu only run when the menu's are rebuilt. So, the if clause will only execute when the user, most likely admin, does a cache clear, not when the targeted user is using the site.

My solution:

```
function MODULE_menu_alter(&$items) {
  $items['user/password']['access callback'] = 'MODULE_user_access_callback';
  $items['user/%user/edit']['access callback'] = 'MODULE_user_access_callback';
}
function MODULE_user_access_callback() {
  global $user;
  // target "guest" account or "anonymous"
  if ($user->name == 'guest' || $user->uid == 0) {
    return FALSE;
  } else {
    return TRUE;
}

```

---
Tags: users
---


# Question
Title: Find the total dollar amount spent by shopper in Ubercart, using Views?
I'd like to run a report that will show info about each shopper, as well as the total dollar amount they have spent on my site. I know that the "Customer Orders" page (for instance, mysite.com/admin/store/customers/orders/1 for user #1) shows the total amount spent by an individual customer... how can I access that total amount in Views so I can build a custom report?

Thanks!

# Answer
> 0 votes
Ugh, I found that Ubercart does have this already built-in, at this URL: admin/store/customers/view. Oh well, better late than never!

---
Tags: 7, views, ubercart, log-messages
---


# Question
Title: Drupal 6 webform: send email if a checkbox is checked?
I have a webform in Drupal 6 with a checkbox component: 'Send email'. If this box is checked I would like a rule to trigger an email send. Is this possible with a Drupal 6 webform? Thanks

# Answer
You can use the rules module to send an email if the checkbox was checked

1. Install drupal \[Rules module\]\[1\]
2. Install drupal \[Webform Rules\]\[2\]
3. Create a rule
4. On condition section you need to custom PHP to check if the checkbox was checked
5. Make sure that you can access the field in data selector
6. Chose the operation equal
7. For the "Data Value" field, you can input values in two modes, make sure you are using "direct input mode". You should then be able to check the checkbox that represents TRUE for that field. Translated, what you are saying is, "Is this field equal to TRUE?" You can also negate it by leaving it unchecked or using the "negate" option below.
> 0 votes

---
Tags: 6, rules, webforms
---


title: Fetch node value in Rules

text:
# Question
Title: Fetch node value in Rules
I am trying to get option value from node in drupal rules. I have a form-group which consists of fields. The field in question is a select list - it consists of different names, with every option there is an email. They are stored in this way:

```
0|NONE
example@example.com|EXAMPLE
example2@example.com|EXAMPLE2

```

So option value for EXAMPLE is example@example.com Let us call this field operator. So I want to send/get email from this node What I have atm in rules is \[node:field-operator:value\] which does not work. \[node:field-operator\] for example just fetches the name e.g EXAMPLE. I have tried tons of ways by now but I know that solution must be simple, it's just my first time using drupal and been looking for an answer for hours. Thank you for your help.

# Answer
Make sure you already have the Token module installed in your site. The Token module.

1. on your site go to /admin/config/workflow/rules
2. Select send an email on the action section of the rule
3. Click switch to data selection
4. Click DATA SELECTORS and find your select list Eg:(node:field-select-list) token and add it into To box.

Hope it help
> 0 votes

# Answer
I duplicated your scenario and also could not get the key to be used in rules. There is no token for :key.

However, if you go to the display settings for you content type, you can change the format of your list text field to 'Key' (by default it is Default). Now your rule will use the key value of the pair, instead of the value. This means that when viewing said node it will also display the key (ie. email) part of your field, and only when editing or adding said content will the list box use the value part of the pair.
> 0 votes

---
Tags: entities, nodes, rules, emails
---


# Question
Title: How to get attributes of the form elements?
I know that it should be easy, but currently it doesnt work. In my function I want to get #title of each element in the form. My form is fieldset "add\_company". For example, when I try to get #title:

```
$msg = '';
foreach ($form['values']['add_company'] as $item)
    $msg .= $item['#title'] . ' ';

```

But I receive nothing.

Second part of question is when i try smth like this:

```
$value = $form_state['values']['add_company']['offers']['#title'];

```

I receive "O", but not "Offers".

# Answer
> 0 votes
You can do it like this:

```
function my_form_validate(OR_SUBMIT)($form, &$form_state)
{
  $msg = '';
  foreach(element_children($form[FIELDSET_NAME]) as $key => $value) {
    $msg .= $form[FIELDSET_NAME][$value]['#title'] . ' ';
  }
}

```

---
Tags: forms
---


# Question
Title: Display Ubercart Attributes and Add To Cart button in separate locations on product node page?
I need to display my product page as such:

```
[-----------ATTRIBUTES-----------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]

[------ADD TO CART BUTTON-----]

```

How can I split the attributes and add to cart button in that way? Is there a way to do so in a tpl file? I'd prefer to avoid absolute positioning.

# Answer
> -1 votes
Create a new product template for your product node type.

---
Tags: 7, ubercart
---


title: Form validate without submit action

text:
# Question
Title: Form validate without submit action
I'm developing a site that it will use Services for the CRUD operations and ANGULARJS for the comunication frontend \<-\> backend.

Now when I want to insert a new content of content type FOO I will don't use the standard form (node/add/FOO), but one of my HTML form, this because, like I said, I will use Services to store the new content.

So, is there a way (or a module) that permit me to send this form to Drupal for only validating it and give back a ok/error code? In this last case I need to receive back errors and the wrong fields.

Thanks. M.

# Answer
> 0 votes
What about this approach (these are just my thoughts)? So, create a rout which gets request and builds `$form_state` and calls drupal\_form\_submit function, actual form looks something like this:

```
function myForm($form, &$form_state)
{
  ....
  $form['submit'] = array(
    '#type' => 'submit',
    '#submit' => array(),
    '#validate' => array('myFormValidation')
  );
  ....
}

function myFormValidation($form, &$form_state)
{
  $error = false;
  if (SOME_CONDITION) {
    $error = true;
  }

  ...

  if (!$error) {
   drupal_json_output(array('ok'));
   exit;
  }
  else {
   drupal_json_output(array('error'));
   exit;
  }
}

```

**EDIT:**

I don't have an expirience with Drupal's Services module or its RESTFul services, but I usually develope my REST projects (usually backend system for IOS apps) in symfony, I think I understand how all this stuff work:), So when I wrote about a rout I meant that this will be some menu item (with hook\_menu):

```
$items['check-my-external-post-data'] = array(
  'page callback' => 'some_callback',
  ...
);
...

function some_callback()
{
  ...
  // $values - from $_POST request
  $form_state = array();
  foreach ($values as $key => $value) {
    $form_state['values'][$key] = $value;
  }
  ...
  drupal_form_submit('myForm', $form_state);
}

```

I've never tested this kind of things, but it should work (there are too many tutorials about REST APIs, request handling, and so on.. which can help OP if something goes wrong)

---
Tags: 7, forms, javascript
---


# Question
Title: How can I hide empty Quick Tab item when there is no content in it?
I don't want to show quicktab item when there is no content in it. But I can see empty divs in it.

```
 <div class="view-content">
      <div class="item-list">
        <ul>
      <li class="views-row views-row-1 views-row-odd views-row-first views-row-last">
              <!-- NOTHING IS HERE SO DO NOT DISPLAY -->
      </li>
      </ul>
     </div>
  </div>

```

How Can I remove the quick tab for above empty content.

# Answer
I already checked it. But still the 'View' I assigned to that quicktab renders some div's which I posted in my question. By the way, I found the solution, you just need to add the filter in that particular view. Suppose view of content type 'movies' then add a filter "content:movies =\> not empty (IS NOT NULL)". That's it. Hope this help others too.
> 1 votes

# Answer
Go to Quick tabs (admin/structure/quicktabs) and edit your instance, and check Hide empty tabs option. Then Empty tabs will not be displayed.
> 0 votes

---
Tags: blocks
---


title: Problem with Profile2 and NodeAccess

text:
# Question
Title: Problem with Profile2 and NodeAccess
We use Profile2 and Node Access but the profiles of users can't be show by everyone (access denied) since we have installed Node Access. The problem is the same with Content Access. Do you know how we can see profile of users and use Node Access or Content Access ( we want to limit access on pages of our intranet's ? Thank you.

# Answer
Thank you for your help. Finally we use a taxomony and Taxomony Access Control and we don't have the problem ! We create a vocabulary : Intranet with two words Private and Public. And we use Taxomony Access Control
> 0 votes

---
Tags: users
---


# Question
Title: How to give users access to the header or footer text in a view?
I have a view with a "global text" header that changes once a month. It's not easy in Drupal to give users access to only certain fields in a view. And I wouldn't want to "scare" them with the views UI either ;-)

# Answer
What I did was create a "basic page" and change the author to the user that should be able to change the text. Then I created a view with content="basic page" and a contextual filter "nid" with the nid of that page. Remove the title field and add the description field and save.

Now I just have to change my original view, remove the "global text field" from the header and add a "Global: view area" instead. Select the view just created and you are done.

Or if you have views\_PHP installed you can add a "Global:php" field and add this code:

```
<?php
$nid = 342388;
$node = node_load($nid);
print $node->body['und'][0]['safe_value'];
?>

```
> 1 votes

# Answer
One option is to create a new Views "attachment" display, and give it different permissions than the other view.
> 2 votes

# Answer
Views UI: Edit Basic Settings

> "Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or number of items to display. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.
>
> The WYSIWYG module is supported, so users may use a rich text editor when editing Views content settings.
> 1 votes

# Answer
I've used the Views UI: Edit Basic Settings module and it does what you want.

If you store your view in features it will reset every time you revert, which could be annoying for editors.

You can set views header to be a node by choosing rendered entity as the header. This should be editable.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Set a numerical field to perform Views Global Math Expression calculations
Lets say I have three fields:

* Field1 (a decimal)
* Field2 (another decimal)
* Global Math Expression

And in **Global math expression** I want to calculate **\[field1\] + \[field2\]**. How do I force Views to understand the replacement fields used in this global math expressions as numbers for calculation? As it is, it always returns the value 0.

# Answer
Another solution that worked for me is to "Strip HTML tags": Rewrite results --\> \[x\] Strip HTML tags
> 1 votes

# Answer
As your field are coming as "strings" in the replacement pattern, you must output the both fields as numeric. Go to your individual fields and then to "rewrite results" and in rewrite results section, go inside replacement patterns. There must be a "raw field format" display option . Just output both fields as "raw". This will enforce the fields to display without any strings and they appear as raw numbers. Then exclude both fields from the display and then do calculation in Math Expression field.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to display page loading time in drupal 7 for each page
I want to display page loading time in every page in the footer. I can do this through some custom php script but want to know that is there any drupal way to achieve this

# Answer
This is a custom one line php script to display the page loading time in every page.

```
<?php
 printf('<div>Page loaded in %.3f seconds.</div>',  (microtime(TRUE) - $_SERVER['REQUEST_TIME_FLOAT']));

?>

```

put this at last line in *html.tpl.php*
> 1 votes

# Answer
The Devel module will show queries and their execution time in the footer which will get you an idea of how long the page is loading.
> 1 votes

# Answer
In addition to Devel, the core statistics module has a report on pages taking the most time.

However, from your response to @ScottJoudry, I gather that you're *not* looking for a diagnostic tool, but something lightweight that just displays this data to entertain you and the site's users.

In that case, you need to roll your own PHP script.
> 0 votes

---
Tags: theming
---


# Question
Title: Howto print out the pagination for EntityFieldQueries?
I have this code that uses an `EntityFieldQuery` object:

```
$query = new EntityFieldQuery;
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'yacht')
  ->propertyCondition("status", 1)
  ->pager(3, 1);

// […] switch case defaulting to:
$query->fieldOrderBy("field_bautyp", 'value', "asc");
// […]

$query->execute();
$nodes = node_load_multiple(array_keys($result['node']));
return theme('yacht_display', array('nodes' => $nodes));

```

And in the yacht\_display.tpl.php

```
<some HTML-Code and iteration over the $nodes>
<?php var_dump(theme_pager()); # => NULL ?>

```

It apparently works; when I add `?page=2,5` to the URL I get different results.
Now I need to render the pager. Simply calling `theme_pager()` does not work; calling `theme('pager', array("element" => 1))` always returns `NULL`.

What am I doing wrong?

UPDATE: updated the code to its current state

# Answer
The `->initializePager()` part is wrong; why would you do that? Kill that line, and call `execute()` as usual. Just calling `theme('pager')` should be enough; I am not sure why it fails. (Maybe because of the call to `initializePager()`.)
> 5 votes

# Answer
Change here: -\>pager(3, 1) to -\>pager(3). It will work.
> 0 votes

---
Tags: 7, entities, paging
---


# Question
Title: Integrate the drupal distribution with already existing site
I have already existing Drupal 7 site, now I got a requirement for the jobs portal for the same site, I found there is a nice drupal distribution Recruiter which exactly satisfies my requirements.

I want to know is there any way that I can integrate this distribution with my existing site, so that i can access the functionality of this distribution from my existing site drupal dashboard, please let me know, I searched a lot on this but did not got any relevant info.

I am thinking of one more option if I will create a multisite on my existing drupal site then can I install this distribution on my multisite.

If any option among these two is possible then please let me know, otherwise I have to create a new installation of Drupal and I do not want two dashboards one of my existing site and other of this distribution.

# Answer
Have you tried the Recruiter Features module?

You can simply download and enable this feature instead of the install profile and see if it does what you need.
> 0 votes

---
Tags: 7
---


# Question
Title: "Fetch entity by property" for users that share terms with new node
I have a content type of RFP that has a term reference field named "RFP Categories". The users also have this same term reference. When I publish a node, I want to email all users who selected a category that is tagged in the node.

This SE post (Email users on node creation based on taxonomy reference) comes very close to the answer I am looking for, but I'm not quite able to follow it. I believe in their case they are setting the 'value' to a specific taxonomy term, whereas I need to fetch any use who has a term matching the node's terms.

My rule has the Fetch Entity by Property action seen below. Unfortunately, I cannot see (or maybe I'm failing to understand) how to link the "RFP Category" terms in the node to the terms in the user entities. It is broken somehow because when I publish an RFP node, I get a SQLSTATE error.

This is what my rule looks like so far.

# Answer
I think the reason for this is that the 'Value' property is asking what you want to match in what you are looking for, basically in pseudo terms, what you've got above is:

* Find the Entities of type: User
* Where the Entity's property: RFP Category
* Is equal to: **The author of the node's Categories**

This is where your selection falls down, because you're trying to search for a set of answers where the data matches an Array. If the node you create can only have 1 term entry (not multiple), I would use the action 'Add a Variable' and set it to the taxonomy term you've created on your node, something like

Add a Variable \> Taxonomy Term \> \[node:RFP-Category\] *I'm guessing to your setup*

This will create a new token for you which contains the Taxonomy term you're searching for. Then in your Entity query, you can use this as your value property

eg

* Find the Entities of type: User
* Where the Entity's property: RFP Category
* Is equal to: **\[Your New Token\]**

If your RFP category has more than 1 or unlimited values, you will have to create a loop of the categories on the node first, then use 'Add a variable' and carry on with the same method
> 1 votes

---
Tags: 7, taxonomy-terms, users, rules
---


# Question
Title: How to modify a term reference autocomplete field
I am using a term reference field but the widget type is autocomplete term widget. This term consist of many levels as parents and child. In the form I need to display only the child terms(only the lowest level in my case 3rd level) in this field. How can I do this. Please anyone help me on this. Thanks

# Answer
There's a GREAT module for this type of configurations called Hierarchical Select

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

This module has a lot to offer, but as for your need, it also does the trick. Also you might want to consider Taxonomy Term Reference Tree Widget as well, the main functionality is a different thing but you can define a permission via views to do what you are after too with this module.
> 1 votes

# Answer
Maybe the Hierarchical Term Reference Autocomplete module could help you. It seems to combine the restriction of level of Hierarchical Select module (select only level 3 for you) and the Autocomplete widget.
> 1 votes

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


# Question
Title: add custom header in term listing tpl page
I want to add some header information in header of term listing. This is my requirement.

I achieve the listing of terms (store) with the help of **term-taxonomy--store.tpl.php** template but how to add **Find stores alphabetically** portion in header, because if I add that portion in **term-taxonomy--store.tpl.php** , it repeats with every store. what i have to do for that ?

# Answer
> 1 votes
I think you're not trying to do that in the right place. The data manipulations should be made (in my opinion) in the modules part or in your template.php, not in your files.tpl.php...

If I were you, I'd proceed with Views module that allows exactly to do what you're trying to get. Answers to this question could help you to create an alphabetical pager with Views.

---
Tags: theming, taxonomy-terms
---


# Question
Title: How to sync users profiles and user tables in 2 drupal sites
I have a website with 14K registered users. There is new section of that website which has been developed as a separate Drupal installation. The users in the old website should be able to login with their username and password to the new site.

My questions are :

1. is there a way to connect new site "user registration/login/forget password" features with the old one?
2. Should i sync the databases all the time? Or when the new user registers, his information is added in to new and old site ( and Vice Versa)

What is the best practice in such cases.

thanks :)

# Answer
There are many ways you can sync Drupal accounts.

1. Using Drupal OpenID-Single-Sign on (OMniauth) which very common method for the big organisation who manage a number of drupal/websites. more on that please refer to Comparison of Single Sign On (SSO) Modules
2. You can also look into Account Sync module which I haven't tested myself yet and it has a very limited number of site "130" reported using it so you better be careful with it. The module provide basic single sign-on support.
3. The other way will be to export users from sites using User Export module. then use Feeds module to import site. You can use Rules module to to export and import users between both sites, probably by running crone on both sites in sequence.
4. Take look into Bakery Single Sign-On System, which is useful single sin-on for the sites that based on the same second-level domain "example.come, test.example.com".
5. Domain Access module which suite of modules that provide tools for running group of affiliated sites from on drupal installation and single shared database. The module allows you to share users.
> 1 votes

---
Tags: users, multi-sites, database
---


# Question
Title: Drupal Views pager shows last page when higher pager value is entered manually instead of page not found
I have a view with pager. The views pager is not AJAX and the pager id comes is the URL as `http://d7.local?page=3` There are total of 15 pages in the view. So the last page is `http://d7.local?page=14` Now if I manually enter a pager number which is higher that 14 say 30 it redirects to the last page Need to redirect the user to a 404 page under this situation.

# Answer
Found a way out!!.. I used theme\_pager and global variable $pager\_total

Here is the code

```
/**
 * Implements theme_pager
 */
function theme_pager($variables) {
  global $pager_total;
  if ($_GET['page'] > $pager_total[0]) {
    drupal_not_found();
    exit;
  }
}

```
> 0 votes

---
Tags: views, paging
---


# Question
Title: Is it possible to create a view to show a field from a user acc and content?
when i create a view in Drupal7 i have to choose what i want to display ( like Users, Content, Terms ... ) .

Is it possible to choose Users and Content?

My problem is:

I have a geofield field in the User Account and in 2 content types. I need a view where i can display this field from all Nodes and Users in one view.

Has someone a trick or a solution for this? I can't find anything about this...

Thanks Flo

# Answer
> 0 votes
To do that you need to link the user account some how to content which i assume could be possible using $node\_author, you also need to connect both the contents with each other using reference field.

In drupal view you can use Relationships tab which available above the Arguments in the center colum of the view add/edit form. To learn about Using View's relationship pleases refer to How To: Using View's Relationships

---
Tags: views
---


# Question
Title: What would be on your checklist when trying to debug a non-reverting feature?
I've lost far, far too many weeks and weekends fighting with Drupal and the Features module in the last year, and I still can't find consistently reliable approach to debugging failed feature reverts.

Now I'm sure I can't be the only person having this problem, because I've watched enough other developers on projects I work on tearing their hair out too, so I'm asking this question, in the hope of saving pain in future.

What steps should you take when troubleshooting a non-reverting feature with Drupal 6?

It's safe to assume knowledge of `drush`, to run diffs of features, and watchdog, and the `--debug` and `--verbose` when answering.

# Answer
Do you have any modules implementing `hook_strongarm_alter()`?

If you're blindly overriding Drupal system variables using `hook_strongarm_alter()` as follows:

```
function mysite_strongarm_alter(&$items) {
  $items['upload_extensions_default']->value .= ' qtz';
}

```

...some Features may incorrectly appear as Overridden.

Instead check to see whether the item is defined first:

```
function mysite_strongarm_alter(&$items) {
  if($items['upload_extensions_default']) {
    $items['upload_extensions_default']->value .= ' qtz';
  }
}

```

...and the Strongarm aspect of the Feature will no longer incorrectly appear as Overridden.
> 1 votes

# Answer
If you have Page Manager panels, those may have to be reverted separately. In many cases I've had to do things like, first revert the feature, then revert the variant or page, and then revert the feature again.
> 0 votes

# Answer
The main thing to understand is how features are generated. They always read configuration to be generated from .info file.

Since this question is from 2011, I can say that Features are far more stable now and working for the last 3 years closely with features almost never had an issue with stuck features.
> 0 votes

---
Tags: features
---


# Question
Title: View for latest articles - but able to override at page level
I have a requirement to create a view which will return the latest 4 articles added to the site to be displayed in a block on multiple pages.

This in itself is easily done - however the client has requested the ability to override the articles shown in this block on certain pages. Again this would be easy if all 4 latest articles were to be swapped for these 4 statically selected articles - but the request is to allow any number between 1-4 static choices to be made when creating content.

If a user chooses just one article manually - the other 3 in the "related" block should be the latest 3 articles from the site. Similary if 2 were manually selected, 2 latest articles should follow them. And so on.

I think I may be overcomplicating this - but having played with Views all morning trying to achieve this I'm struggling - can anyone give me some pointers?

# Answer
> 0 votes
This is possible with attached displays. You would create a view with 2 displays: manual and reverse chronological.

Manual would use a relationship with node's field (entityreference field) that allows to pick releated nodes.

Automated will always select 4 recent articles.

Attach manual to an automated to appear at the top.

You gonna end up with 4 to 8 articles.

To remove extra nodes from results, implement hook\_views\_post\_execute()

---
Tags: views
---


# Question
Title: Move Drupal to subdirectory - clean urls
There is a requirement to move site from www.test.com and make it available only under URL www.test.com/newsite.

When the clean URLs are enabled and after i click to login to the administration site, the URL changes to: www.test.com/newsite/newsite/user.It duplicates the "newsite".

The page www.test.com/newsite/user is visible...and only after the login attemp this happens.

I have set in .htacess

```
RewriteBase /newsite
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

Clean URls are working normally in the rest of the site.

# Answer
> 0 votes
Perhaps setting the $base\_url variable in the settings.php will help Drupal generate the correct urls.

```
/**
     * Base URL (optional).
     *
     * If Drupal is generating incorrect URLs on your site, which could
     * be in HTML headers (links to CSS and JS files) or visible links on pages
     * (such as in menus), uncomment the Base URL statement below (remove the
     * leading hash sign) and fill in the absolute URL to your Drupal installation.
     *
     * You might also want to force users to use a given domain.
     * See the .htaccess file for more information.
     *
     * Examples:
     *   $base_url = 'http://www.example.com';
     *   $base_url = 'http://www.example.com:8888';
     *   $base_url = 'http://www.example.com/drupal';
     *   $base_url = 'https://www.example.com:8888/drupal';
     *
     * It is not allowed to have a trailing slash; Drupal will add it
     * for you.
     */
    # $base_url = 'http://www.example.com';  // NO trailing slash!

```

---
Tags: .htaccess, uri
---


# Question
Title: In multisite environment can you have a default site?
I am wondering if multisite Drupal allows you to have a default site too. Something like `sites/default/settings.php` and `sites/mysite/settings.php` along with the proper sites.php. If yes then what should `sites.php` look like?

# Answer
For sure you can have a default site to use i case if the requested site was not available some reason the default site will be open to user. to do that you need to setup the default site setting under sites/default/setting.php

lets assume we have 3 website

1. mysite1.com
2. mysite1.com
3. mysite3.com
4. defultsite.com

In that case your file structure needs to be :

1. /sites/mysite1.com folder which will have setting.php file for mysite1
2. /sites/mysite2.com folder which will have setting.php file for mysite2
3. /sites/mysite3.com folder which will have setting.php file for mysite3
4. /sites/default folder which will have setting.php file for default site

You need to setup your .htaccess file in your root of server to point every Domain to the main drupal folder. to learn more about .htaccess please read here.

No to test if your default site is working simply rename mysite1.com folder to xxxxx and now try to access your mysite1.com using any browser it shoud take you to default site because mysite1.come folder cant be found anymore.
> 0 votes

---
Tags: multi-sites, configuration
---


title: hook_menu/MENU_CALLBACK access denied

text:
# Question
Title: hook_menu/MENU_CALLBACK access denied
I am using hook\_menu() to generate a series of MENU\_CALLBACKS for processing data at various points in my sites operations. However, while these work for the admin, when trying to access the pages I get the following error message:

```
You are not authorized to access this page.

```

I am trying to get this so that the pages can be reached by all users (one is used for submitting a form and processing the results), the other is used for logging outgoing data. The code is as follows:

```
function modulename_menu() {
  $items = array();
   $items['data/update'] = array(
    'page callback' => 'dataupdate',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
   $items['onthewayout/forward'] = array(
    'page callback' => 'register_click',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

# Answer
> 2 votes
I tested out the hook\_menu in my local. The hook seems fine. Check if you have added an access denied code in the callback function

```
function commons_menu() {
  $items = array();
   $items['data/update'] = array(
    'page callback' => 'dataupdate',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
   $items['onthewayout/forward'] = array(
    'page callback' => 'register_click',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function dataupdate() {
  return drupal_set_message("First one is working");
}

function register_click() {
  return drupal_set_message("Second one is also working");
}

```

This returns a Access Denied to me even if access callback is true.

```
function register_click() {
  drupal_access_denied();
  exit;
}

```

# Answer
> 0 votes
You are missing the title key. According to the docs:

> "title": Required. The untranslated title of the menu item.

---
Tags: users, routes
---


title: 404 blog url's delivering 403 status

text:
# Question
Title: 404 blog url's delivering 403 status
I have a blog set up on my site, when I visit a page it delivers a 200 as it should, however when I visit a page that should not be there, it delivers a 403.

Example:

domain.com/blog/good-url/ = 200

domain.com/blog/bad-url/ = 403

The second example should be delivering a 404, any ideas where this could be coming from?

# Answer
> 3 votes
After looking at the source code of the *blog* module, it appears that the path `/blog/<somestring>` is sort of *reserved* for the blog module itself.

**Problem:**

The pattern based aliases created when creating a new blog node seem to take precedence over those internal paths so if your URL alias pattern is `blog/[node:title]`, you are shown the expected blog node as long as it exists.

Once the blog node is deleted and the alias is deleted with it, `/blog/<somestring>` means "do whatever path `<somestring>` does in the blog module" which results in a `403 Forbidden` error rather than the expected `404 Not Found` error.

**Solution:**

The only solution I found is to use a different URL alias pattern such as `blogs/[node:title]` which avoids the problem.

**Tip:**

Use the Redirect module to let the Pathauto module create redirects when changing URL aliases. It also helps to keep track of those redirects so you can see which redirect URLs still receive traffic and which could be deleted.

---
Tags: 7
---


# Question
Title: Views: How to list nodes by 2 vocabularies with “%” on url path for contextual filters
I have a content type with 2 different Term references. I wanna use Views to list “Term one” with “%” on url path, and **use “Term two” as section**. See below for details.

**Vocabulary term one:**
Book type A
Book type B
Book type C

**Vocabulary term two:**
Book style A
Book style B
Book style C

## **List result: on Book type A**

Book style A
\- node 101 title, author name
\- node 102 title, author name
\- node 103 title, author name
Book style B
\- node 111 title, author name
\- node 112 title, author name
\- node 113 title, author name

Book style C
\- node 121 title, author name
\- node 122 title, author name
\- node 123 title, author name

---

**— — updated info @ Sep. 9th 2014 @ 1:16pm**

I created a content View, which has “Content: Type Book A” and set the path as “/booka/%. It came out fine except I don’t know how to use the 2nd Term as section to list all those node under their style.

# Answer
try this:

* create the view as a table with fields
* include the style field (exclude from display)
* under table settings, 'group' the results by the style field

You can tweak the layout for the headers with some simple css
> 1 votes

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


# Question
Title: Why does email attachment fail on rescheduled rule?
I have an action set component that takes a "date" param and does the following:

1. "Add Variable" saves a path string based on the date.
2. "Execute custom PHP code" saves some data to the path created above.
3. "Send HTML mail to all users of a role" sends an email with the above file attached.
4. "Schedule component evaluation" repeats the component at time +2 minutes and sends date parameter +2 minutes.

If I execute the component, the file is created and the email is sent with the attachment as intended. But when the rescheduled component executes again, the correct file is created on the server and the email is sent, but the attachment is not there.

# Answer
The problem was that I needed to allow the cron user to "Send Arbitrary Files" in the Mime Mail permissions.
> 0 votes

---
Tags: rules, emails
---


title: Custom submission handler is not called

text:
# Question
Title: Custom submission handler is not called
I have a form with a second button which should add new form elements according to this page. The callback does not get called though. The second button is set from the following code.

```
$form[ 'addTicket' ] = array(
  '#type' => 'submit',
  '#submit' => array('asdf'),
  '#value' => 'Add Ticket'
);

```

Clicking it should, as of my understanding, call this callback function.

```
function asdf() {
  error_log( 'I was called' );
}

```

It is never called though. Why? Is there a way to debug this?

This is the complete code.

```
function WPD14_menu() {
    $items = array();
    $items[ 'WPD14/anmeldung' ] = array(
        'title' => 'Anmeldung zum World Photography Day 2014',
        'page callback' => 'WPD14_anmeldung',
        'access arguments' => array( 'access content' ),
        'description' => 'Anmeldung zum WPD 14',
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function WPD14_anmeldung() {
  return drupal_get_form('WPD14_anmeldeformular');
}

function asdf($form, &$form_state) {
  error_log('asdfasdfasdfs');
}

function WPD14_anmeldeformular($form_state) {
  $form['buyer'] = array(
    '#type' => 'fieldset',
    '#title' => 'Infos',
  );

  $form['buyer']['strasse'] = array(
    '#type' => 'textfield',
    '#title' => 'Strasse + Nr.',
    '#required' => TRUE,
    '#default_value' => isset($form_state['storage']['buyer']['strasse']) ? $form_state['storage']['buyer']['strasse'] : 'Strasse',
  );

  $form['buyer']['plz'] = array(
    '#type' => 'textfield',
    '#title' => 'PLZ',
    '#required' => TRUE,
    '#default_value' => '1234'
  );

  $form['buyer']['ort'] = array(
    '#type' => 'textfield',
    '#title' => 'Ort',
    '#required' => TRUE,
    '#default_value' => 'There'
  );

  $form['buyer']['mail'] = array(
    '#type' => 'textfield',
    '#title' => 'Mailadresse',
    '#required' => TRUE,
    '#default_value' => 'test@example.com',
  );

  $nTickets = isset($form_state['storage']['nTickets']) ? intval( $form_state['storage']['nTickets']) : 2;
  $nTickets = min(20, max(1, $nTickets));

  $form['nTickets'] = array(
    '#type' => 'textfield',
    '#title' => 'Anzahl Tickets',
    '#disabled' => FALSE,
    '#default_value' => $nTickets,
  );

  for ($t = 0; $t < $nTickets; $t++) {
    $form['tickets'][$t] = WPD14_ticketformular($t);
  }

  $form['addTicket'] = array(
    '#type' => 'submit',
    '#submit' => array( 'WPD14_anmeldeformular_addTicket', 'asdf' ),
    '#value' => 'Weiteres Ticket'
  );

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

  return $form;
}

function WPD14_anmeldeformular_addTicket($form, &$form_state) {
  error_log('Callback called.');
  error_log($form_state['nTickets']);
  $form_state['nTickets']++;
  // $form_state['rebuild'] = TRUE;
  drupal_set_message($form_state['nTickets']);
}

function WPD14_ticketformular($nr) {
  $form = array(
    'vorname-' . $nr => array(
      '#type' => 'textfield',
      '#title' => 'Vorname',
      '#required' => TRUE,
      '#default_value' => 'Vorname ' . $nr
    ),
    'nachname-' . $nr => array(
      '#type' => 'textfield',
      '#title' => 'Nachname',
      '#required' => TRUE,
      '#default_value' => 'Nachname ' . $nr
    ),
    'frMain-' . $nr => array(
      '#type' => 'textfield',
      '#title' => 'Hauptvortrag Freitag',
      '#required' => TRUE,
      '#default_value' => 'Fr H ' . $nr
    ),
    'saDay-' . $nr => array(
      '#type' => 'textfield',
      '#title' => 'Nachmittagsvorträge',
      '#required' => TRUE,
      '#default_value' => 'Sa ' . $nr
    ),
    'saMain-' . $nr => array(
      '#type' => 'Hauptvortrag Samstag',
      '#title' => 'Name',
      '#required' => TRUE,
      '#default_value' => 'Sa H ' . $nr
    ),
  );

  return $form;
}

function WPD14_anmeldeformular_validate($form, &$form_state){
  if (!preg_match( '/^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+\\.[a-z]{2,4}$/', $form_state['values']['mail'])) {
    form_set_error('mail','Bitte geben Sie eine gültige Mailadresse an.');
  }

  $nTickets = intval($form_state['values']['nTickets']);
  if ($nTickets < 1) {
    form_set_error('nTickets','Kein Ticket ausgewählt.');
  }

  form_set_error('debug', print_r($form_state, TRUE));
}

```

# Answer
> 3 votes
Remove the `form_set_error()` call that always gets called in `wpd14_anmeldeformular_validate()`. This tells Drupal that the form did not validate and Drupal will not call the submission handlers.

Other changes you will need to make are in the `hook_menu()` implementation, and in the form name method. Here's what your `hook_menu()` should look like.

```
function wpd14_menu() {
  $items = array();
  $items['wpd14/anmeldung'] = array(
    'title' => 'Anmeldung zum World Photography Day 2014',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('wpd14_anmeldeformular'),
    'access arguments' => array('access content'),
    'description' => 'Anmeldung zum WPD 14',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

Note the change for 'page callback' and the addition of 'page arguments'. Finally, the arguments of wpd14\_anmeldeformular are incorrect. They should be as follows.

```
function wpd14_anmeldeformular($form, &$form_state) {
  // ...
}

```

# Answer
> 1 votes
Try adding a custom "#name" value to the button. Drupal defaults to having a name of 'op' for buttons, so it's likely thinking they're the same button and only calling the one callback.

# Answer
> 1 votes
The bug was, as already noted in the comment, that the \_validate hook failed and prevented all further callbacks. So, even for the custom submit button, the validate hook was called first.

Necessary changes were removing the last line in `function WPD14_anmeldeformular_validate( $form, &$form_state )`, changing the callback function as follows

```
function WPD14_anmeldeformular_addTicket( $form, &$form_state )
{
    $form_state['values'][ 'nTickets' ]++;
    $form_state['rebuild'] = TRUE;
}

```

and use `$form_state['values']` instead of `'storage'` everywhere; What is $form\_state used for? explained this.

```
$nTickets = isset( $form_state[ 'values' ][ 'nTickets' ] ) ? intval( $form_state[ 'values' ][ 'nTickets' ] ) : 2;
$nTickets = min( 20, max( 1, $nTickets ) );

```

---
Tags: 6, forms
---


# Question
Title: Remove "Comments" title section from node template
in my node.tpl.php i have this line:

```
<?php echo render($content['comments']); ?>

```

It works, but before comments I have a \<div\> with the text "Comments". I think that it is the section titles. I don't want it. Is there a possibility to remove it before "render" or I need to hide it via css ?

M.

# Answer
You can hide it via css or you can change the tpl file:

Look for the *comment-wrapper.tpl.php* file in your theme. If it doe not exist there, you can copy it from the modules/comment folder into your theme folder. Edit the file and remove the line:

```
<h2 class="title"><?php print t('Comments'); ?></h2>

```
> 1 votes

---
Tags: 7, comments
---


# Question
Title: Site-wide altering of access behavior in Drupal site
I have a website that has 3 different types of users: anonymous, registered, elite registered. I have setup the appropriate permissions but my problem is the following: if a user does not have the appropriate permissions to see a piece of content, the content does not appear anywhere on my listings. For example, it does not appear in the results of the Search API, it does not appear in the entity reference listings or the Views.

I want the nodes to appear in various listings but when you try to access the actual node, to get a message that prompts you to register/upgrade your account.

Is this a way to configure such a behavior site-wide? Or would I have to handle the permissions on a per-item basis (e.g. setup the views or override the entity reference permission handling to show the results regardless of the permissions and redirect the Access Denied page to an "Upgrade your account" page)?

# Answer
> 1 votes
Here's one way to do it:

1. Set up your permissions to reference a taxonomy.
2. Add a hook to change the view\_mode of a node you don't want a user to see.

Ours looks like this, we are using a taxonomy called 'Access Level' to control what level of access a node should be shown at (field\_access\_level). Roles can be given permission against any, all or none of the various taxonomy terms, really useful for segregating products on a Drupal site.

```
/**
 * Implements hook_perm().
 */
function i_security_access_permission() {
  $permissions = array();
  $terms = taxonomy_get_tree(11);
  // Define permissions using taxonomy Access Level vocabulary
  foreach ($terms as $term) {
    $permissions[$term->name] = array(
      'title' => t($term->name),
      'description' => t('Access content from '. $term->name),
    );
    $permissions['Edit Role Names'] = array(
      'title' => t('Edit Role Names'),
      'description' => t('Allows users to edit role Names'),
    );
  }
  return $permissions;
}

/*
 * Implements hook_entity_view_mode_alter
 *
 * Sets the view mode to full or teaser based on user access rights
 */
function i_security_access_entity_view_mode_alter (&$view_mode, $context) {
  if (array_key_exists("field_access_level",$context['entity'])) {
    $access_tid = $context['entity']->field_access_level['und'][0]['tid'];

    $access =  taxonomy_term_load($access_tid);
    // Checks if user has access to content
    if (!user_access($access->name) && $view_mode != 'search_index') {
      $view_mode = 'teaser';
    }
  }
}

```

You can improve upon it by adding a test for view\_mode in your node template and displaying a login button and/or your exhortation to upgrade when the node is shown in teaser mode. Same applies for views.

Some things to note:

* If you're using a taxonomy and programmatically mapping it to permissions, make sure users can't change the taxonomy terms because all of the permissions get lost
* User **can** however, add new taxonomies and remove unwanted ones with impunity. Especially since if you remove a term and then add it back in, the permissions you have set for your roles magically reappear (at least they have in my experience).
* The `&& $view_mode != 'search_index'` near the end is because I found this was interfering with Apache Solr indexing the site: it was only indexing teasers! I'm not sure what other view\_modes there are, so be careful with this.

I wonder if we have the makings of contrib module here?

# Answer
> 0 votes
you could use a simple 'flag' system...

* set a boolean field or a dropdown for simpler editing, using field permissions module to restrict who can view/edit this field
* use Rules to check on view content if the viewer role matches the 'flag' (or minimally matches - i.e. setting the field to 1 allows roles with a level '1' access or higher to access the node). Otherwise it redirects to an access denied page

In this way, the node isn't inherently restricted by the access controls of Drupal, but Rules will make sure it can't actually be viewed as a whole.

---
Tags: 7, users
---


# Question
Title: how to create a link field which validates to a set of nodes?
Is there a way to set the Validation for a Link field so that authors are only allowed to link to a pre-determined certain set of nodes?

IOW: when authors add a link field to a Node I want them to be limited to only links that are on our site -and- which are webforms or other nodes. I do -not- want them to be able to freely link to other domains.

Ideally, I'd like to be able to limit this set of valid links to nodes of a certain content type, or with a certain tag.

Just to be clear: these are not site visitor form fields, these are the fields for -Authors-.

# Answer
> 0 votes
try the advanced link module:

> Provides autocomplete widget for CCK Link field and additional functionality over standard field:
>
> Variants of URL filtering (external or internal).
>
> Additional filter options by using URL patterns.
>
> Autocomplete link field for internal mode - displays suggestions from existing url aliases and menu items
>
> Option to allow users select url title from predefined list of values
>
> Use cases
>
> You want allow users specify link only to several sites (i.e. specify link only to facebook or twitter)
>
> **You want restrict users to specify only internal or external links**
>
> You want to use autocomplete suggestion when specifying internal links

---
Tags: forms
---


title: Drupal CSV import and create nodes

text:
# Question
Title: Drupal CSV import and create nodes
I am trying to accomplish the following through feeds and want to know if this is possible.

* Setup a cron to pull a CSV file via ftp from another server daily
* Create a bunch of nodes with custom fields based off the CSV file

I have the latest Feeds module setup, When I go to create a node it says I can upload my CSV file, however it seems the mapping could be wrong? I was a little confused at when I was setting up the mapping. My CSV file has no headers so for the source I put in the Column Name i.e A, B, C etc.

What am I doing wrong?

Link to CSV: http://markets.naptiveagency.com/diamondlot.csv

# Answer
> 1 votes
In order to do the mapping correctly, you have to instruct the feed importer how to do it. This is done through the configuration steps, shown in the following screenshots:

For sake of simplicity and time saving, I have created a content type called i.e. SimpleCar and added all the fields from the CSV file with the same name. Here is the screenshot of the content type:

Once you created a content type that closely correspond the screenshot shown above, then install/enable the following modules namely feed, feeds\_ui,job\_scheduler. And create a feed with the following configuration screens (closely watch how the feed is configured to read the CSV - Comma seperted file).

For simplicity, I have used the ***Standalone Form*** to directly upload the CSV. If you want this process to be triggered by CRON then you need to attach it to a content type - from the list).

You can also set the periodic import and tick the process in background option, you must have the CRON already configured.

Click on Fetcher and select either File Upload or HTTP, in this test case I have chosen File Upload, Save.

Once saved then you will see the File UPload Settings, Click it and see what is there. You can leave this settings intact. You can also tick the tick-mark to indicate where the feed importer should automatically pick up the CSV file and process it (should you have a way to automatically store the csv file in a directory then importer can pick it from there - that is advanced, you need to read about it).

Click on Parser and select CSV parser then SAVE. Once SAved then you will see the CSV Parser settings. By default it looks for Comma seperated, leave this intact and Save it. If you notice in this settings, there is a tick mark for ***Header***, if you tick that then feed importer will start from top-most row, if you don't select it then first row will be skipped.

Click on Processor settings and choose Node Processor, Save. Once saved the Node Processor settings will appear and it has two sub-settings, ***Settings*** and ***Mapping***.

The settings for this example, look as follow:

I have chosen ***Bundle*** as SimpleCar (which is the Drupal content type). This says that for every row of the CSV create one of the SimpleCar node. Save this screen.

The mapping settings of Node Processor should look as follow, to avoid mistakes, I recommend that you copy/paste fields directly from CSV and map them to their corresponding SimpleCar content type fields. Don't forget to map a unique value as VIN to ***GUID*** and ***Title*** and then Save.

Now go back to the basic settings and there is a link under the ***Standard Form*** drop down, you can use that link to upload your CSV and it should process and create your drupal nodes.

See my results:

and here is how the node looks like

In case you are lazy to follow the instructions, then at least create the content type and import the following code to Feeds using Import feed functionality and give it ago. You can then customize this to do it for you automatically either via HTTP download from server or pick up the CSV file from a location. You of course need to do some reading, google, there are a thousand tutorials on feeds module.

```
$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'csv_importer';
$feeds_importer->config = array(
  'name' => 'CSV Importer',
  'description' => 'Testing CSV Importer',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsCSVParser',
    'config' => array(
      'delimiter' => ',',
      'no_headers' => 0,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'DEALERSHIP_ID',
          'target' => 'field_dealership_id',
          'unique' => FALSE,
        ),
        1 => array(
          'source' => 'STOCKNUMBER',
          'target' => 'field_stocknumber',
          'unique' => FALSE,
        ),
        2 => array(
          'source' => 'new',
          'target' => 'field_new',
          'unique' => FALSE,
        ),
        3 => array(
          'source' => 'VIN',
          'target' => 'field_vin',
          'unique' => FALSE,
        ),
        4 => array(
          'source' => 'Year',
          'target' => 'field_year',
          'unique' => FALSE,
        ),
        5 => array(
          'source' => 'Make',
          'target' => 'field_make',
          'unique' => FALSE,
        ),
        6 => array(
          'source' => 'Model',
          'target' => 'field_model',
          'unique' => FALSE,
        ),
        7 => array(
          'source' => 'series',
          'target' => 'field_series',
          'unique' => FALSE,
        ),
        8 => array(
          'source' => 'Body',
          'target' => 'field_body',
          'unique' => FALSE,
        ),
        9 => array(
          'source' => 'Ext Color',
          'target' => 'field_ext_color',
          'unique' => FALSE,
        ),
        10 => array(
          'source' => 'Int Color',
          'target' => 'field_int_color',
          'unique' => FALSE,
        ),
        11 => array(
          'source' => 'Asking Price',
          'target' => 'field_asking_price',
          'unique' => FALSE,
        ),
        12 => array(
          'source' => 'MILEAGE',
          'target' => 'field_mileage',
          'unique' => FALSE,
        ),
        13 => array(
          'source' => 'Transmission',
          'target' => 'field_transmission',
          'unique' => FALSE,
        ),
        14 => array(
          'source' => 'Engine',
          'target' => 'field_engine',
          'unique' => FALSE,
        ),
        15 => array(
          'source' => 'restraint type',
          'target' => 'field_restraint_type',
          'unique' => FALSE,
        ),
        16 => array(
          'source' => 'image url',
          'target' => 'field_image_url:url',
          'unique' => FALSE,
        ),
        17 => array(
          'source' => 'Comments',
          'target' => 'field_comments',
          'unique' => FALSE,
        ),
        18 => array(
          'source' => 'options',
          'target' => 'field_options',
          'unique' => FALSE,
        ),
        19 => array(
          'source' => 'certified',
          'target' => 'field_certified',
          'unique' => FALSE,
        ),
        20 => array(
          'source' => 'VIN',
          'target' => 'guid',
          'unique' => 1,
        ),
        21 => array(
          'source' => 'VIN',
          'target' => 'title',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '2',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
      'bundle' => 'samplecar',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => 1800,
  'expire_period' => 3600,
  'import_on_create' => TRUE,
  'process_in_background' => FALSE,
);

```

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


# Question
Title: Easily add term to vocabulary with long list of terms
A client is complaining about the way on how to **add terms** to a vocabulary in taxonomy.

It's a **long list of terms and sub-terms**. So I told him when he adds a term he can select a **Parent term** and set the **weight** in the **Relations** block.

But the list of parent terms is long and not very clear. Isn't there a way to make this more user friendly? Maybe search in parent terms or .. ?

# Answer
> 1 votes
The way the default terms are added to a vocabulary is not so nice indeed, and we get to hear this kind of complaints often.
But, there is a module which is made exactly for this purpose :)
Check Taxonomy CSV import/export.

> This module allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.
>
> It helps you to quick import a non-standardized vocabulary, for example an old thesaurus, a hierarchical taxonomy or a simple list of children, synonyms, descriptions, weights or related terms to terms. It can be used as a module or as an API with a plug-in mechanism. It can manage internationalized vocabularies with i18n\_taxonomy, a submodule of i18n module \[Drupal 7 only\].

After that you just have to train the client on how to import the terms. The terms can be added in a single configuration textarea and can be comma separated.

# Answer
> 2 votes
For better UI management of taxonomy terms try Taxonomy Manager

```
This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

The Taxonomy Manager has following operations and key features:

 - dynamic treeview
 - mass deleting
 - mass adding of new terms
 - moving of terms in hierarchies
 - merging of terms (using the Term merge module in 7.x)
 - fast weight changing with up and down arrows (and AJAX saving)
 - AJAX powered term editing form
 - simple search interface
 - CSV Export of terms
 - i18n support for multilingual vocabularies (per language terms)
 - Double Tree interface for moving terms in hierarchies, adding new
   translations and switching terms between different vocabularies

```

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


# Question
Title: How can I add a class with table theme function to a table header row?
How can I apply a class to the `<tr>` of some table headers using the table theme function?

So, I get this: `<tr class='my-class'><th>foo</th><th>bar</th></tr>`

...rather than: `<tr><th class='my-class'>foo</th><th class='my-class'>bar</th></tr>`

...which is all I've managed with this:

```
$section = array(
  '#theme' => 'table',
  '#header' => array(
    array('data' => 'foo', 'class' => 'my-class',),
    array('data' => 'bar', 'class' => 'my-class',),
  ),
  '#rows' => $rows,
),

```

Thanks

# Answer
You can do it using below code

```
 $section = array(
      //It contains the rows
      array(
        //'data' contains cell data as numerical arrays:
        'data' => array(
          //Cell 1: array if need to add classes in cells too
          array('data' => 'Cell 1', 'class' => 'cell-class1'),
          //Cell 2:
          array('data' => 'Cell 2', 'class' => 'cell-class2'),

        ),
        //Row attributes, e.g. 'class', 'rel','data'
        'class' => array('row-class1'),
      ),
      //Contains the rows, is a numerical array (as default): 0, 1, 2 ... :
      array(

        'data' => array(
                array('data' => 'Cell#1', 'class' => 'cell-class1'),
                array('data' => 'Cell#2', 'class' => 'cell-class1'),
        ),
        'class' => array('row-class2'),
      ),
    );

```

Hope it will help!
> 2 votes

# Answer
If your current example works I'm assuming you are on drupal 6.

You can add attributes to the header array like this:

```
$section = array(
  '#theme' => 'table',
  '#header' => array(
    array('data' => 'foo', 'class' => 'cell-class'),
    array('data' => 'bar', 'class' => 'cell-class'),
    'class' => 'row-class',
  ),
  '#rows' => $rows,
),

```
> 1 votes

---
Tags: theming
---


# Question
Title: Commerce cart allowing quantity than In stock
I don't know on how to validate the quantity, meaning if user add the quantity more than In stock, it should not allow the user to add more quantity than In stock(quantity available), I think it can be achieved in rules, but Im not sure to do that any pointer would be helpful!

# Answer
> 1 votes
commerce stock module check the quantity and prevent add max than stock,also if the stock be 0 it change `add to cart` button to `out of stock`.

Also if you want to implement it by yourself you can do it with rules

---
Tags: commerce
---