# Question
Title: How to create the equivalent of a spreadsheet?
I don't want to start with too many unnecessary details on this one. I've got a stack of codes. Weekly more codes are added. On occasion these codes will be 'used' by other systems. These other systems are not Drupal sites.

I'm not sure how else to describe this, but all I want is the equivalent of a spreadsheet in Drupal: It should be possible to add rows, and delete rows of data on a single page, instead of creating a new node for every single code. I just want a table where I can add and delete codes, something like this, a CRUD table.

My current solution is this:

1. Build a table (my\_codes (id, code) )
2. Create a CRUD for the table so someone can manually enter in new codes (one by one)
3. Create a REST for the crud so these other systems can use these codes (codes/list, codes/add, codes/delete)

However, the main site is in Drupal, and only certain users should be able to add codes.

What is the simplest way to achieve this goal?
I could do all this work in a block, but I'd prefer to just install a Drupal module. If I can achive #1 and #2 with a module, then I should be able to do #3 myself. Note that last time I looked at CCK it did not have a "table" option.

# Answer
> 1 votes
The TableField or the Slickgrid modules may help here.

# Answer
> 1 votes
The Drupal model is that you can have an Entity representing a DB table, and then you display entities however you please. So if Drupal is to be the front end for managing the database of codes, then other systems can still use the DB without having to know how to resolve attached fields.

Views gives you tables which you can sort. Inline editing would be something you'd have to add.. A search brings me to this project: http://drupal.org/project/jeditable Representing functions as icons (trash for delete, etc) could be a formatter, or a form alter in the theming.

And voila: You've made Excel in Drupal. :-)

# Answer
> 1 votes
The Views Bulk Operations module could come in handy for you. It gives you a chance to add actions to a views table.

The Drupal standard security mechanism should be enough for you to make sure only a specific group of people have permission to create new data. You can define any number of roles and give them the permission to create your new content type.

To give a 3rd party system easy access to your Drupal data, you could use views and present your data as RSS feeds. You could also use views to get the node data as CVS files.

You might have to code a little bit for the Views Bulk Operation actions. Everything else should be possible with Drupal core and Views.

---
Tags: 7
---


title: Enabling blocks in an install profile

text:
# Question
Title: Enabling blocks in an install profile
I'm creating an install profile and I just can't seem to get my blocks enabled.

When I check the database after using the code below in my install function it puts the records in the block table, but the status is set to 0 and the region detail isn't inserted.

I'm using code from other install profiles and I can't see why mine isn't working - works fine on things like the erecruiter profile, the omega profile, but whenever I try it never works! Anyone experienced similar?

```
// Enable some standard blocks.
$default_theme = 'mytheme';
$admin_theme = 'seven';
$values = array(
array(
  'module' => 'system',
  'delta' => 'main',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'content',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'node',
  'delta' => 'recent',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 10,
  'region' => 'dashboard_main',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'user',
  'delta' => 'login',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'sidebar_first',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'navigation',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'sidebar_first',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'powered-by',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 10,
  'region' => 'footer',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'help',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'help',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'main',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'content',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'system',
  'delta' => 'help',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'help',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'user',
  'delta' => 'login',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 10,
  'region' => 'content',
  'pages' => '',
  'cache' => -1,
),
array(
  'module' => 'user',
  'delta' => 'new',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'dashboard_sidebar',
  'pages' => '',
  'cache' => -1,
 ),
);
$query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
foreach ($values as $record) {
  $query->values($record);
}
$query->execute();

```

# Answer
> 3 votes
Are you using the Profiler library to drive your installation profile? If so, there's a "feature" in the 7.x-2.0-beta1 release that causes this behavior. In short, there's some legacy code that disables all blocks in the database upon installation.

If you're using the Profiler module, upgrade to the latest development snapshot to get the fix.

---
Tags: 7, blocks, theming, distributions
---


# Question
Title: How to migrate a physical files into Drupal 7
I'm new to Drupal so forgive me.

I'm trying to migrate an existing site into Drupal. The site is all static content. I'm wondering if I can point Drupal towards a file path, rather then manually creating pages within Drupal and coping the body text.

Is there an easer way to handle a migration. I've looked on google, but most links are for existing CMS systems, or assume a database is provided.

If I do need to copy the HTML into the body, how I can I manually edit the header tag for a page? e.g. I'd like to add CSS and Js references.

Thanks

# Answer
If the site to be migrated has low double digit numbers of pages or has widely varying HTML and document structure among the pages the easiest solution is copy and pasting it by hand. This may be an opportunity to reorganize the site, add taxonomy terms and clear up other minor content issues.

For larger sites there are several options:

The Migrate module provides a framework and API for you to automate content migration. Using it will involve some coding and require a degree of familiarity with Drupal.

The Feeds module is generally used for importing data like RSS feeds but can be used to import site data. For example, it will import a CSV file, converting lines to Drupal nodes. I envision a solution copying pages into a structured spreadsheet with fields for Title, Author, Body, etc. and exporting that to a CSV for import via the Feeds module.

For completeness I'll mention the Import HTML module which only has Drupal 5 and 6 versions available. If you found this module suitable to import your content you could import into a barebones Drupal 6 installation and perform a site upgrade to Drupal 7.
> 1 votes

---
Tags: migrations
---


# Question
Title: Relation Between Drupal Commerce Line items and Products
I am making a website in Drupal 7 and Drupal Commerce with some custom modules. Now, I have a set of Products.

The Products are, \- Product 1 \- Product 2 \- Product 3 I have two line items. Lets say Product Sizes. And product weight. Each have select or another module implemented. I have followed the concept of Randy Fay's Screencasts. http://www.commerceguys.com/resources/articles/237
http://www.commerceguys.com/resources/articles/238

Now with each line items the cost of the product changes. As per the screenscasts, the process will be,

1. Create Line Items
2. Create Products
3. Create Product Display and add a Product Field Reference to it.
4. Then it will display the line item in the product display page.

But, I am not creating the Product display. This is going to be via the custom module. So can you tell me from the coding point of view, what is the relation between a line item and a product. So that I can list all the created line items for a displayed product.

# Answer
> 7 votes
It sounds like you are confused.

Short answer:
Line items has a reference to a product.

**Explaination**
Line items are only used when you add something to your order (cart), they have a relationship between the order and the product and hold data like price quantity, but can hold additional data, like the address (in case of subscriptions), which a unique each time you buy something.

If you have product attributes like size or weight, you probably want to store this on the product, since a products with different sizes and weight should be different products (A S size t-shirt is not the same as a L sized t-shirt).

So it really sounds like you are doing this the wrong way.

---
Tags: commerce
---


# Question
Title: How to create a block with CCK dropdown lists and some values in it?
As the question is clear, I want to create a block in the left sidebar and which contains sample values in it. How to do this? I am very new to Drupal

# Answer
This is something you can do in Drupal 7 easily as they now use enititys. However in Drupal 6 you will need to use a custom module like Node Blocks
> 1 votes

---
Tags: 6, entities, nodes
---


title: Fetch Total Cost of Today Orders

text:
# Question
Title: Fetch Total Cost of Today Orders
I am using Drupal-6 . i am using ubbercart module here. In Content type Product I have a field named Actual Amount.

Now i want to get total of Actual Amount by Datawise only .

Can Anybody tell me how to do this ?

Thanks

# Answer
> 3 votes
Views could do this and you might also want to use views calc, setup a view to display all orders with a filter to show only last day, then add the field for amount and use views calc to sum the total.

---
Tags: views, 7, hooks
---


# Question
Title: Create version of site with no header/menu?
So what I need is a copy my website without the header or navigation menu (it will be used in a frame for another site) but using the same database. I've considered theming the pages based on parameters in the url (e.g. www.example.com/?simpleview=true) but I can't think of how to append "?simpleview=true" to the end of all the links on the page so when they click, it stays.

If there is an elegant solution to this, it would be appreciated... otherwise I will have to make do with a messy one. :P

# Answer
> 1 votes
What I ended up doing was having a subdomain "simpleview.example.com". Since I was already using the built in multisite, it opens up the same structure as "www.example.com" by default and all the links still work as they are relative. I then added a CSS file that would only show up if it was the simpleview subdomain (using the `$_SERVER` variable to get the URL) and made the elements I didn't want hidden with `{display:none}`.

Not sure if this is the best way to do it, but it got the job done without too much trouble.

# Answer
> 0 votes
The regions in a site are printed in the page.tpl.php. Every theme defines them differently but $header is often used and you can remove that from the page.tpl.php and from THEME.info to remove that region.

It is impossible to say how to remove the menu from a given site since a menu can be set to display in any part of the page.tpl.php or as a block that can be placed in any region. One options is to remove the menu items from a given menu it will no longer appear or delete the menu itself.

# Answer
> 0 votes
You can have different themes for your normal site and your iframe version. Use the theme key module to distinguish between the two.

---
Tags: 7, blocks, theming
---


# Question
Title: Puilling Information From Referenced Entities to Display/Use In A Custom Content Type?
# Exposition

I have two Content Types with the following fields:

* Scenes

1. Scene Name
    2. Starring (Actor's names)
    3. Streaming Link
* Releases (DVD Releases)

1. Title
    2. Description
    3. *Starring* (All actor's names from all Scenes referenced)
    4. Scenes (Entity references to the Scene Content Type)

# My question

When displaying a Release node, how can I get Drupal to generate the list of Starring Actors by taking the names from the 'Starring' fields in the Scene nodes that have been referenced?

Thanks

# Answer
> 1 votes
Two suggestions

First, the most common solution:

1. Create a View
2. Add a "relationship" from Release to Stars
3. Add whatever fields you want to display, in this case, "Name", and make they "Use relationship Stars".

Second, what I would have done:

1. Create a suitable Panels Page for Releases
2. Create a mini-panel for Stars
3. Add the Stars reference field to the releases page with "Panels reference formatter", choose the mini-panel as the formatter.

Intro to Views.

Intro to Page manager and Panels.

---
Tags: nodes, entities
---


title: Bulk delete orders

text:
# Question
Title: Bulk delete orders
I have a bunch of test orders and I'd like to remove them. Is there a way to bulk remove all of the orders without uninstalling/installing the Ubercart module?

Obviously, I'd first backup the database with a simple `drush sql-dump`.

# Answer
> 6 votes
I would discourage you from messing with the database unless you really know what you're doing. You should better use the API and the function `uc_order_delete()`.

Have a look at this example script:

```
<?php
  include_once './includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  global $user;

  if ($user->uid == 1) {
    $result = db_query("select order_id from uc_orders");
    while($row = db_fetch_object($result)){
      //# uncomment below to view an order and exit
      //# usefull to write a query to only delete certain orders
      //print_r($row);
      //exit;
      print "deleting order $row->order_id\n";
      uc_order_delete($row->order_id); // comment this out for testing
    }
  } else {
    print "Only Administrater could deleter orders.";
  }
?>

```

Source: Delete all orders in Ubercart.

# Answer
> 4 votes
You can use a view created with the Views Bulk Operations (VBO) module to delete orders.

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

---
Tags: 6, ubercart
---


# Question
Title: adding a field to the form during form_validate
I am working on a node form in which my users can add sport-teams (which I'll handle through a taxonomy) that are related to the node (say it's a blog-entry about your local rugby-team and you want to relate it to the team's taxonomy entry). To each team entry, I also have a db-table with a corresponding zip-code of the teams headquarter (say your local rugby team comes from cardiff).

Now the users can also add teams, that are currently not in the taxonomy list (through the use of taxonomy-autocomplete (i.e. tagging)). When that happens, during `form_validate`, I fire a `form_set_error()` and ask the user to type in the City the team is coming from.

In effect, I want to add a field to the form during form\_validate. But how do I do that?

I tried, to no avail, adding the following to the `$form` variable in the `form_validate` function:

```
$form['field_new_team_location'][$i] = array(
'#type' => 'textfield',
'#title' => t('new team location'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
'#description' => t('description')
);

```

**EDIT** Alas, although Charlie S' answer helped me to put up a field during validation (read: the html gets displayed; I can write in them), but it seems I cannot access it in a follow-up validation. In fact, when I hit save again, neither `$form` nor `$form_state` have the newly created fields in them! Any help accessing my fields is much appreciated!

**2nd EDIT** With what Charlie S said, it works. One thing that holding me up was that the form only gets rebuilt when no error messages are being cast. In other words, every required field has to be supplied before the form gets rebuilt and the user is able to input something in the new fields.

# Answer
> 4 votes
In form\_validate(), make sure your arguments are being passed by reference:

```
myform_validate(&$form, &$form_state)

```

Then the last thing you should have in \_validate() is:

```
$form_state['rebuild'] = TRUE;

```

Edit: You will want to handle the actual adding of the element in the form builder. This is tested and working:

```
function customform_custom_form($form, $form_state) {
  $form['field_a'] = array(
    '#type' => 'textfield',
    '#title' => 'Field A',
    '#required' => TRUE,
    '#weight' => 1,
  );

  // Add field b depending on the value of field a.
  if (isset($form_state['input']) && !empty($form_state['input']['field_a'])) {
    $form['field_b'] = array(
      '#type' => 'textfield',
      '#title' => 'Field B',
      '#weight' => 2,
    );
  }

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

  return $form;
}

function customform_custom_form_validate(&$form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
    form_set_error('field_b', 'Please enter something in Field B.');
    $form_state['rebuild'] = TRUE;
  }
}

function customform_custom_form_submit(&$form, &$form_state) {
  drupal_set_message('You entered ' . $form_state['values']['field_b'] . ' for Field B.');
}

```

# Answer
> 1 votes
I'm not sure you can actually add fields to the form on validate? Have you looked at using ajax for this instead? You can define your own submit function and check the inputted tags here. To make it easier, maybe you could add the field\_new\_team\_location when you build your form and just set $form\['field\_new\_team\_location'\]\['#access'\] = FALSE and then enable it when you need it.

---
Tags: 7, forms
---


# Question
Title: Update Node Problematically is not working fine
I am using Drupal-6 . I am trying to update single field using following code.

```
    $nodnew->id=14;
    $nodenew->field_site_url[$array_id]['value']=$website_url;
   $nodenew->revision=1;
   $nodenew->changed = $node->created;
   $nodenew->comment = 0;
   $nodenew->type ='product';
   node_save($nodenew);

```

It updates field\_site\_url sucessfully. But it also changes other fields to blank. like title, body etc. i want to add only field\_site\_url.

Any idea how to do this?

# Answer
> 3 votes
You can try to load node with its id :

```
   $nodenew = node_load(14); // load the complete node

```

So when you use node\_save() all other field values that was previously stored in database will automatically get loaded. Then only thing remains is the field you want to update.

```
   $nodenew->field_site_url[$array_id]['value']=$website_url;
   $nodenew->revision=1;
   $nodenew->created = time();
   $nodenew->changed = $nodenew->created;
   $nodenew->comment = 0;
   $nodenew->type ='product';
   node_save($nodenew);

```

---
Tags: 7, hooks
---


# Question
Title: Checkbox list for content type in drupal 7
How do you add Content type checkbox list in Drupal 7?

I have content type "Exporter". When I edit an exporter I would like to have a list of regions that exporter is part of. In Drupal 7 how do I add a radio button field that list all regions in the exporter content type.

In Drupal 6 I had to use CCK, but I thought this was supported natively in Drupal 7?

# Answer
> 1 votes
You're right...the CCK module has now been incorporated natively into Drupal 7, so you would use that.

Just visit http://mysite.com/admin/structure/types/manage/CONTENT\_TYPE/fields to add the fields to your content type in pretty much exactly the same way you did using CCK in Drupal 6.

**EDIT**

Sorry I understand your problem now, the node reference and user reference modules aren't part of the default field system in Drupal 7; you just need to download and install the References module and then you'll have the "Node Reference" option in your field type drop-down like you're used to seeing.

---
Tags: entities, nodes
---


# Question
Title: How to integrate the Fusioncharts library with Drupal 7?
I have been trying to integrate the Fusioncharts library with my Drupal 7 site.

Just to check if everything is working properly, I followed this documentation for creating a basic graph with data contained in Data.xml file; the entire documentation is here.

FYI, I need to use PHP as I am more comfortable with it.

I have extracted the downloaded folder into /sites/all/libraries/FusionChartsFree/; with changes in paths (nothing else); I have pasted the code in the given example into my Drupal 7 node with the php input filter enabled. I also have the libraries module installed.

```
<?php
  //We've included ../Includes/FusionCharts_Gen.php, which contains FusionCharts PHP Class
  //to help us easily embed the charts.
  $name = "FusionChartsFree";
  if ($path = libraries_get_path($name)) {
    include $path . '/Code/PHP/Includes/FusionCharts.php';
  }
?>
<html>
  <head>
    <?php
      //You need to include the following JS file, if you intend to embed the chart using JavaScript.
      //When you make your own charts, make sure that the path to this JS file is correct. Else, you
      //would get JavaScript errors.

      include($path.'/Code/FusionCharts/FusionCharts.js');
    ?>
    <script type="Javascript" SRC="/sites/all/libraries/FusionChartsFree/Code/FusionCharts/FusionCharts.js"></SCRIPT>
    <title>FusionCharts - Simple Column 3D Chart</title>
  </head>
  <body>
    <?php
      //Create the chart - Column 3D Chart with data from Data/Data.xml
      echo renderChart("/sites/all/libraries/FusionChartsFree/Code/FusionCharts/Column3D.swf", "/sites/all/libraries/FusionChartsFree/Code/PHP/BasicExample/Data/Data.xml", "", "myFirst", 600, 300, false, true);
   ?>
  </body>
</html>

```

I get the below output. It is pretty long; hence, I have put then in part by part in these pictures.

(FYI, those Flash files that appear in the output, do not display anything if I click on them.)

Now, suppose I remove the below line from the code.

```
<?php
 include $path . '/Code/FusionCharts/FusionCharts.js';
?>

```

I get nothing. I mean only a text which reads "cahrt" in the below output.

**My Question**: How can I make Fusioncharts work in DRUPAL 7?

I am also having similar trouble with the pChart library too: Even pChart does not display anything, not even an error, or warning. Simply there is nothing in the node body.

# Answer
> 0 votes
Finally, it worked. I don't know exactly what the problem is, but here is what I did.

* I uninstalled all other modules related to charting
* I downloaded FusionchartFree again
* I sed the Libraries module
* I checked with the following code, and it worked.

```
$name = "FusionChartsFree";
if ($path = libraries_get_path($name)) {
  include $path . '/Code/PHP/Includes/FusionCharts.php';
  drupal_add_js($path.'/Code/FusionCharts/FusionCharts.js');
}

// Create the chart - Column 3D Chart with data from Data/Data.xml

echo renderChart($path.'/Charts/FCF_Column3D.swf', $path.'/Code/PHP/BasicExample/Data/Data.xml', "", "myFirst", 600, 300, false, true);

```

# Answer
> 2 votes
There's a couple of problems in your code:

* `include($path.'/Code/PHP/Includes/FusionCharts.php');` you have to use `./` to include files.
* `include($path.'/Code/FusionCharts/FusionCharts.js');` you should use `drupal_add_js()` to include javascript in your code.
* FusionCharts documentation seems a little old as `Column3D.swf` is now `FCF_Column3D.swf`

Here is a working example, I haven't used the librarie module but you should be able to adapt it easily. I put this code in a node with PHP filter activated.

```
<?php
$file = './sites/all/libraries/FusionChartsFree/Code/PHP/Includes/FusionCharts.php';
if (is_file($file)) {
  require_once $file;
}
drupal_add_js('sites/all/libraries/FusionChartsFree/Code/FusionCharts/FusionCharts.js');

//Create the chart - Column 3D Chart with data from Data/Data.xml
echo renderChart("/sites/all/libraries/FusionChartsFree/Code/FusionCharts/FCF_Column3D.swf", "/sites/all/libraries/FusionChartsFree/Code/PHP/BasicExample/Data/Data.xml", "", "myFirst", 600, 300, false, true);

?>

```

---
Tags: 7, theming, charts
---


# Question
Title: D7: How to loop an array as form elements?
I have the following hook\_form (below) which colect data from $\_POST and then send them via email. The problem is $jcartItemName and $jcartItemPrice are arrays so I need to loop through them and display the form items accordingly. I expect this could be done via a

```
foreach($jcartItemName as $value) {
    $form['jcartItemName'] = array(
    '#type' => 'textfield',
    '#value' => isset($value) ? $value : '',
    );
}

```

but how do I do that effectively. Thanks!

```
function checkout_form($form, &$form_state) {
     $jcartItemName = $_POST['jcartItemName'];//array
     $jcartItemPrice = $_POST['jcartItemPrice'];//array
     $jcartTotalPrice = array_sum($jcartItemPrice);//integer
     $form = array();
     $form['#action'] = "";

    $form['jcartItemName'] = array(
    '#type' => 'textfield',
    '#value' => isset($jcartItemName) ? $jcartItemName : '',
    );

    $form['jcartTotalPrice'] = array(
    '#title' => t('TotalPrice'),
    '#type' => 'textfield',
    '#value' => isset($jcartTotalPrice) ? $jcartTotalPrice : '',

    );

        $form['email'] = array(
        '#type' => 'textfield',
        '#title' => t('E-mail'),
        '#default_value' => "",

        '#description' => "Please enter your e-mail for order to be sent.",

    );

    $form['send-order'] = array(
        '#type' => 'submit',
        '#name' => 'send-order',
        '#value' => t('Send Order'),
        '#class' => 'button',
    );

    return $form;
  }

```

# Answer
> 3 votes
For those of you who face the same issue: I found the answer:

```
foreach($jcartItemName as $key => $value) {
$form['jcartItemName'][$key] = array(
'#type' => 'textfield',
'#value' => isset($value) ? $value : '',
);

```

---
Tags: forms
---


title: What HTML tags for image with style?

text:
# Question
Title: What HTML tags for image with style?
In below codes, there is `style="float: left;"` that make the image float.

```
<p><img alt="" class="image-medium" src="http://localhost/d7/files/styles/medium/public/about-us/images/2012/02/28/img.jpg" style="float: left;" title="" />Ut scelerisque pulvinar nisi eget ultricies. Fusce iaculis risus vel nunc aliquam hendrerit. Fusce et bibendum justo. In ultricies quam at libero dapibus eu fermentum ipsum eleifend. Proin at libero nulla. Mauris adipiscing, odio vel tempus dapibus, odio dolor pellentesque neque, ac adipiscing enim purus tincidunt mauris. Nunc elementum euismod tellus ut commodo. Aliquam nec felis nunc. Suspendisse et turpis nec purus auctor ultrices sed ut arcu. Mauris suscipit scelerisque tortor, id feugiat sapien lacinia vel. Phasellus congue tellus sed est blandit eu gravida ipsum ultrices. Vestibulum orci leo, condimentum at adipiscing in, scelerisque et odio.</p>

```

Without HTML filtering, it works. But if using HTML, what tag should I add to make the picture float?

Currently, below is my tags:

```
<a> <p> <span> <h1> <h2> <h3> <h4> <h5> <h6> <img> <map> <area> <br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <em> <b> <u> <i> <strong> <font> <del> <ins> <sub> <sup> <quote> <blockquote> <pre> <address> <code> <cite> <embed> <object> <param> <strike> <caption> <s> <textarea>

```

# Answer
You can use `class="left"` in your HTML, and `.left {float:left;}` in you CSS.
> 2 votes

# Answer
The issue is that the input filters strip out the class= and style= tag out, even if they are inside allowable tags. The quick solution is to figure out what DIV or SPAN encloses your text and then have css built up for that, eg, in a .css file have:

```
WHATEVERDIV img {
   float: left;
}

```

which would cause all imgs inside your div to float. If you need to get more fine grained than that, you could work with css selectors to target specific images (which can get ugly and not too supportable if they images change, etc.)
> 0 votes

---
Tags: 7, input-formats
---


title: How do I customize the Fivestar module?

text:
# Question
Title: How do I customize the Fivestar module?
I need to customize part of the Fivestar module's output, so that I am able to assign points ( e.g. 1, 2, 3, 4, 5).

I want the module to sum up and display the total points received by the content or user, and I want to use my own icons in the widgets.

Is this possible?

I am using Drupal 7.

# Answer
> 3 votes
Your first two items are settings that can be configured on the Fivestar CCK field's display options. You should read through the Fivestar Documentation thoroughly for instructions on how to set up a rating system.

If you want to use star icons of your own, you can simply override the styling of the Fivestar widget in your theme using CSS. However, if you want to create a star set that can be easily reused across sites, you can follow the instructions for creating a fivestar widget set

---
Tags: rating
---


# Question
Title: How do I calculate the total of a shopping cart?
I have the following cart implemented by a custom module I wrote.

The columns are stored in 2 associative arrays.

```
$jcartItemQty = $_POST['jcartItemQty'];
$jcartItemPrice = $_POST['jcartItemPrice'];

```

This is what those array could contain:

```
     [jcartItemQty] => Array
            (
                [0] => 3
                [1] => 1
            )

        [jcartItemName] => Array
            (
                [0] => Armas Jarnefelt - LAULAJAN KOTI
                [1] => Jean Sibelius - Kullervo
            )

        [jcartItemPrice] => Array
            (
                [0] => 110
                [1] => 120
            )

```

I need to combine somehow the arrays into one that looks like `$combined = (3 => 110, 1 => 120)` in order to be able to calculate the total. `array_merge()` is not working because will only concatenate those 2 arrays.

```
foreach ($combined as $key => $item) {
  $total += $key * $item;
}

```

I need to display the total in a form item like this:

```
foreach ($jcartItemPrice as $key => $value) {
  $form['jcartItemPrice'][$key] = array(
    '#type' => 'textfield',
    '#value' => isset($value) ? $value : '',
  );
}

$form['total'][$key] = array(
  '#type' => 'textfield',
  '#value' => isset($value) ? $value : '',
);

```

Is there a way to do this?

# Answer
Assuming the array keys of each array will always match (and that is what you're using to tie the two arrays together):

```
$total = 0;
foreach ($jcartItemPrice as $key => $price) {
  $total += $price * $jcartItemQty[$key];
}

```
> 1 votes

# Answer
You can use array\_merge() to merge two arrays into one.

It looks like you're trying to overengineer things. This is a simple solution:

```
$combined = array();
for ($i = 0; $i < count($jcartItemQty); $i++) {
  $combined[] = array($jcartItemQty[$i], $jcartItemPrice[$i]);
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: How to use drupal_http_request for send data?
I need some help in sending data in an array (POST) to a webservice (REST). I need some examples in how to use the function `drupal_http_request()`.

Now, I'm using cURL with PHP but I need to replace it with `drupal_http_request()`. And I see that it's easier to use in Drupal.

If my first page is the login (http://\[ip\]/users/sign\_in) and I'm using "User:Pass" to enter to main page(http://\[ip\]/event). Then, I select the menu for view the data that I send from my form in Drupal (http://\[ip\]/event/mobile/management).

How to do this with `drupal_http_request()`?

UPDATE:

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

    $name = $form_state['values']['name'];
    $email = $form_state['values']['email'];

    $attendee = array(
        'name' => urlencode($name),
        'email' => urlencode($email)
    );

    $attendee = http_build_query($attendee, '', '&');

    $url_login = 'http://[ip]/eventmobile/users/sign_in';
    $url_target = 'http://[ip]/eventmobile/attendee_management/attendee';

    $use  = array(
      'email' => 'root@root.com',
      'password' => '123456'
    );
    $user = http_build_query($use, '', '&');

    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $method = 'POST';

    $result_1 = drupal_http_request(url($url_login, array(absolute => true)), $headers, $method, $user); //I get a http_code = 200. OK
    $result_2 = drupal_http_request(url($url_target,array(absolute => true)), $headers, $method, $attendee); // I get a http_code = 500. Internal Server Error

```

}

UPDATE 2 (Using cURL):

```
$attendee = array(
        'name' => urlencode($name),
        'email' => urlencode($email)
);
$userpwd = "root@root.com:123456"
   $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url_target);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); //I get http_code=200

        if(preg_match('#Location: (.*)#', $result, $r))
                $url_redirect = trim($r[1]); //The URL of LOGIN

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url_redirect);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $page = curl_exec($ch); // Return string: Evaluating...
        $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); //I get http_code=200

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        $result = curl_exec($ch); // Return string: Evaluating...
        $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE);// I get http_code=200

    curl_close($ch);

```

# Answer
> 4 votes
Your `$url_login` looks like the default URL scheme for a Ruby on Rails website that uses the devise login system. Here is a function I've used to login to a rails/devise backed web site.

```
/** Authenticate via Rails/Devise site */
function devise_login($email, $pass) {
   //Build up data to send to devise
   $data = array('user' => array('email' => $email, 'password'=>$pass));
   //Pull the url out of the drupal settings
   $url = variable_get('devise_authentication_url', '');
   if ($url != '') {
     $response = drupal_http_request($url, array(
       'method' => 'POST',
       'data' => json_encode($data),
       'max_redirects' => 0,
       'headers' => array('Content-Type' => 'application/json', 'Accept' => 'application/json'))
     );

     return = json_decode($response->data);
   }

   return FALSE;
}

```

# Answer
> 0 votes
Have you tried this?

```
$headers =  = array();
$url = "the_link_to_post_to";

//now make the data string: it should be of type 'var_name=value&var_name2=value2&....' etc
$data = "username=user_name&password=chosen_password";

drupal_http_request($url, $headers, 'POST', $data);

```

---
Tags: http-request
---


# Question
Title: How to ajaxify webform submit in Drupal 7?
I have tried to alter the webform rendering using `hook_form_alter()` and `hook_node_view()` in a custom module so I could add '#ajax' somewhere.

Has anybody already had some experience working with webform and ajax on D6 or D7 ? I guess the logic would be the same for D6 and D7 then just the implementation changes.

# Answer
> 9 votes
The Ajax Module works for me in Drupal 6.

For Drupal 7:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
      // see if webform_client_form_ is in the form_id
      if(strstr($form_id, 'webform_client_form_')) {
        // get the nid so we can use it in the wrapper value
        $nid = $form['#node']->nid;
        // add the ajax properties to the submit button
        $form['actions']['submit']['#ajax'] = array(
          'callback' => 'mymodule_webform_js_submit',
          'wrapper' => 'webform-client-form-' . $nid,
          'method' => 'replace',
          'effect' => 'fade',
        );
      }
    }

function mymodule_webform_js_submit($form, $form_state) {
      // define the $sid variable (submission id from webform)
      $sid = $form_state['values']['details']['sid'];
      // if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
      if ($sid) {
        // first we have to load up the webform node object
        $node = node_load($form_state['values']['details']['nid']);
        // create an array up with the confirmation message, retreived from the webform node
        $confirmation = array(
          '#type' => 'markup',
          '#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
        );
        // return the confirmation message
        return $confirmation;
      }
      else {
        // return the form
        return $form;
      }
    }

```

# Answer
> 0 votes
One of the easiseast way if you are looking to ajaxify just a particular form will be to add the jquery form plugin. Its pretty straight forward.

Add the below code to you page preprocess function in template.php file.

1. **First add the jquery plugin with below code.**

drupal\_add\_js(drupal\_get\_path('theme', 'your\_theme') . "/js/jquery.form.js");
2. **Then Add the below code, replace `#your_form_ID` with form id of yours**

drupal\_add\_js('

```
            (function($){
$(document).ready(function() {

            $("#your_form_ID").ajaxForm(function() {
                alert("Thank you for your comment!");
            });
});     }(jQuery));;

       ', 'inline');

```

That's all you are done. Maybe you want to consider loading the scripts only the pages you need.

# Answer
> -1 votes
See if the Ajax module can help you with that. See the documentation as well

---
Tags: 7, ajax, webforms
---


# Question
Title: How do I get the Default Content module to work?
I saw the Default Content module. I wanted to know the real purpose of this module, how do we exactly use it, and what the difference with the node\_export module is.

# Answer
> 2 votes
You can use default content to give your nodes a machine name (as seen when editing a node). Then you can use features module to export those nodes to a feature.

# Answer
> 2 votes
You don't *use* it as such, rather it provides extra options to the Features module:

> When the module is installed nodes get optional "machine name" field. Nodes with filled-out machine names automatically become exportable from the Features interface.

---
Tags: 7
---


# Question
Title: Is there an installation package builder for Drupal?
Does anybody know of any websites that provide a service that allows you to select which modules you want, and download a pre-assembled installation package with the selected modules already in the /modules/ folder?

# Answer
> 2 votes
You could make your own easily with the Drush Make module; the Profiler Builder module will tell you what to include in your make file.

This requires you have some knowledge of using drush.

---
Tags: 7, distributions, installation
---


# Question
Title: Adding dynamic filter in module_invoke()
I have created a node named "weekday," and one named "place" on Drupal 7. Next, I created a block view of the fields in "weekday" I wanted to show in the "place" node template.

I implemented it using the following code:

```
$weekday = module_invoke('views', 'block_view', 'weekday-block');
print render($weekday);

```

Now I would love to add a flexible filter that allows to load the block module with a extra filter of the different weekdays. Weekdays are a taxonomy term field in the node type "weekday". The reason is that I would like to request the block by jquery in a link like http://www.example.com/place#Monday.

# Answer
You want to use views\_embed\_view(), rather than module\_invoke(), for this so you can pass the 'weekday' term as an argument to the view, such as in the following code:

```
print views_embed_view($view_name, $display_id, $argument);

```

There might be an easier way to do this in Drupal 7/Views by using contextual filters directly from the view itself; I'm not sure how you are planning on using jQuery to load each of these new blocks. Are you doing a load operation with the URL on each one? Is there any reason you need to use the # anchor attribute rather than a URL argument like http://www.example.com/place/Monday?

That could make it easier to set this up within views.
> 1 votes

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


# Question
Title: How to enable Administration menu Toolbar style for editor profile?
I have created an Editor profile which can create specific content types. However, I would like to give such users the possibility of using the `Administration menu Toolbar style` (i.e. overlays) rather than the default page display.

Is this possible? If yes, how? Thanks.

# Answer
You just need to grant a few permissions to the editor role to achieve this. Navigate to http://mysite.com/admin/people/permissions and tick the checkboxes next to the following permissions for the editor role:

* Use the administration toolbar
* Access the administrative overlay
* Use the administration pages and help
* View the administration theme

Only the pages that an editor user usually has access to will be shown as links in the toolbar.
> 4 votes

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


title: Where are profile2 fields shown?

text:
# Question
Title: Where are profile2 fields shown?
I have installed the profile2 module and added some fields, but I can't find where are they shown. How do I display fields' values for a user?

I also can't change fields' values after creating a user.Fields are shown only in user registration page.

# Answer
> 0 votes
Assuming you're using the default admin theme you should see a tab on each user edit page for each profile type in the top right hand corner, e.g.

You should also see a tab on the user page itself for each profile type, the fields are displayed in there.

---
Tags: users
---


# Question
Title: How to track which external link users who registered on my site came from
Google Analytics shows how many and from which links people have visited to my site as I have installed the Google Analytics module. How can I know from which link the individual registered users came from? For example, I would like to know something like:

> The user (uid:30) came from http://example.com The user (uid:31) came from http://somesite.com

Or do I have to ask users directly by making a kind of "Where did you know about us" profile field?

# Answer
> 0 votes
I believe StatCounter allows for this
http://statcounter.com/
http://drupal.org/project/statcounter

I believe what your asking for is against GA's TOS http://drupal.org/node/318974

---
Tags: 6, nodes, google-analytics
---


# Question
Title: How can I PUT a new file to a node using services 3 without overwriting the existing file?
Using Services 3 I have it working fine to add a file using

```
endpoint/file
{"uid":"1","filesize":"99999","filename":"whatever.bin","file":"BASE64_ENCODED_DATA"}

```

and also to add a node with that file using

```
endpoint/node
{"title":"testrest1","type":"dl","field_dl_file":{"und":[{"fid":582}]},"uid":"1","language":"und"}

```

But how can I add a new file to the node? When doing PUT

```
endpoint/node/999
{"field_dl_file":{"und":[{"fid":999}]},"uid":1,"language":"und"}

```

It just overwrites the existing file. Trying to POST gives a whole bunch of errors.

# Answer
## Background

Services uses drupal\_execute() with the node form to save updates to nodes, which won't entirely merge updates in with existing data.

If the update doesn't set a field at all, then it won't overwrite what's there, so in a sense it does merge data in that case. For instance, in your example, you don't set "title" in your update, and therefore it won't overwrite that field.

However, if you set a field, it will overwrite whatever was there previously. So, in your example, since you are setting "field\_dl\_file", it will overwrite whatever was previously there with whatever you set now. As you saw, this causes any existing files to be overwritten.

## Solution

Probably the best solution (and I assume the one intended by the Services team) is to load the previous value of the "field\_dl\_file" in your script (via a retrieve call to the REST interface), then call the update with both the new value as well as the old value. In other words, merge the old data in with the new data on the client side (inside the script that interacts with the REST interface).

Another possible solution is to manually merge your "field\_dl\_file" field with existing values inside node\_resource.inc (line 365 or so). I assume the Services team never intended this, and it would require changing the module directly (since there aren't any hooks there), so I can't really recommend it. It would, however, ease the work needed in the client-side script, which could be a benefit depending on your implementation.

**Note**: I referenced Drupal 6 code, though I'm fairly sure it applies to Drupal 7 as well (that part of Services 3 didn't change as far as I know).
> 4 votes

---
Tags: files, services, 8
---


# Question
Title: Error when I edit a block: Notice: Undefined index: und in eval()
I don't understand why I put `$node->field_test['und'][0]['value']` appears the next error:

> Notice: Undefined index: und in eval()

The field "field\_test" is a boolean field. The code is the following one:

```
$node = node_load(153);
if ($node->field_test['und'][0]['value'] == 1) {
  echo "test";
}

```

What is my error?

# Answer
> 6 votes
You must pay attention to the node's language. 'und' is for nodes which don't have a language set. If you set one, then the values will be in 'en' or 'de' or whatever the node's language code is.

# Answer
> 2 votes
Don't assume that 'und' is for fields of entities without language, it is also for fields that are not translatable, and without the entity translation module that is all fields. Moreover, there are differences in this between the various 7.x versions of Drupal.

Better to use the field\_get\_items() function which will sort out for you under what language code the data is stored.

# Answer
> 1 votes
I found the answer.

I had to change the code:

```
 <?php
    $node = node_load(153);
    if ($node->field_test[$node->language][0]['value'] == 1) {
    echo "test";
    }

```

I replaced it with the following one:

```
    $node = node_load(153);
if (isset($node->field_test[$node->language][0]['value']) && $node->field_test[$node->language][0]['value'] == 1) {
  echo "test";
}

```

This code solved the error and works for me.

---
Tags: blocks
---


# Question
Title: Is there a module that allows me to add files via ajax to a body field?
I am using Drupal 7. I am looking for a module that allows users to drag and drop files (images/video/audio) inline into a body field with something like jQuery UI sortable. I would ideally like the user to be able to make a "media bank" in the node creation where they can upload their media and then drag and drop it where they want it in their post. Also, and I know that I am already asking a lot, it would be awesome if when the user added an image, they could resize it to the best fit for its position and placement in the body.

Do you have any suggestion, or anything close that I may be able to customize for my needs?

# Answer
It is probably not exactly what you are looking for, but I'll mention them anyway, as it might give you further search directions:

I like the plup module a lot, very easy to use, but based on image fields, not inline. Perhaps, in combination with the Insert module, you can get them inline. I don't like the resulting UI, as people won't understand why something so easy (putting an image inline, optionally with fixed dimensions) needs to be presented so complex.

The Media module is still thinking how to handle inline images; see the issue #1283844.
> 1 votes

---
Tags: 7, nodes, ajax, javascript, files
---


# Question
Title: Where in Drupal database do I store additional file properties?
I have an (architectural) problem with D7 and don't know what would be a good solution to it. Here is what I'm trying to do: I have an article with a sound sample attached to it. I thought it would be great to calculate sound sample duration and bitrate and store it somewhere in the database. What would be the proper place for that? I thought of node fields first, but number of sound samples for one article is not restricted and it seems I'll need to define a field with unlimited number of values to hold durations and then somehow match samples with their respective durations. Don't think it's a proper solution here. So what's the common practice in such cases?

# Answer
You might want to look into the Media project which provides bundles for files and allows to add fields to them.

Another approach would be to use a module like Field collection which allows you to group a number of fields into a group that you can add as a field to another entity. That field can then have an unlimited amount of values which allows you to attach n fiels + meta information to your node.
> 2 votes

# Answer
Not a direct answer to your question, but in some minds, the best option is to leverage a library or module that already exists. In this case, you can use the getID3() module and associated PHP library for extracting metadata.
> 1 votes

---
Tags: 7, database, files
---


title: Simple news - Undefined Variable Error?

text:
# Question
Title: Simple news - Undefined Variable Error?
I am getting this error after transferring my site to another host. Not sure why it broke so need some help troubleshooting.

It seems the block\_html\_id and the content itself is not coming through. I am using the standard block.tpl file What could be wrong?

here is the code from simplenews-block.tpl.php

```
47:     <div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

50:    <php if ($block->subject): ?>

56:       <?php print $content ?>

```

Here is all the code from the simplenews-block.tpl.php

```
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?></h2>
<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>
</div>

```

I am thinking I need to delete the module and all tables related to it in the DB and start fresh...? What else is there to do?

This is the content of the template.php file.

# Answer
I have no clue where you got that block template content from, but that's completely wrong and *not* what Simplenews comes with.

The Simplenews block template can be seen here: simplenews-block.tpl.php. What you seem to have there is the default block.tpl.php which is *not* the same thing, even though they are named in a similar way.

Make sure that you are not overriding the default template somwhere (and if you do, use the correct one as the start point) and that you are using an unmodified, recent version of Simplenews.

Edit: Looking at the error message again, it looks like you already overwrote the template with something that is wrong. This your problem. Just delete that file, clear your caches and everything should be working again.
> 1 votes

# Answer
Clear your cache completely. Disable your current them and enable a core theme like Garland. If the error goes away, you'll know it's with your theme.

If not:

* Was the database fully migrated?
* Were your files (and theme!) fully migrated?
* When you say "standard" block.tpl.php file, where did it come from? It should have come from `/modules/block/block.tpl.php`.
> 3 votes

---
Tags: 7, emails
---


# Question
Title: How to select a particular node reference in a view programmatically
I have two custom node types : catalog\_item and category.

The catalog\_item node has a cck node reference field that allow a user to select multiple category nodes. I want to be able to select a particular category from the node reference based on some php code. Is this possible with views?

# Answer
> 2 votes
Within the views API, you could use this field as an argument and then use PHP to supply the default argument. This would then restrict the views to all catalog\_items that have that specific category node referenced.

If you are doing this in code/a module/template/etc, you could do it also like this:

```
$nid=WHATEVERPHPCODEYOUWANT;
return views_embed_view(VIEWNAME,'default',$nid); // 'default' is the views display

```

# Answer
> 0 votes
The other option is to use one of the views hooks.

I *believe* this will work, but I haven't tested to be sure:

```
function mymodule_views_pre_view (&$view, &$display_id, &$args)
{
  if ($view->name == "myview" && $view->current_display == "mydisplay") {
    $nid = some_function_to_get_the_nid();
    $view->args = array($nid);
  }
}

```

I don't recall if you need to set the arguments in the display handler, too.

With things like this, you need to poke through `$view` with `dpm()` and experiment with the various hooks.

---
Tags: 6, entities, nodes, views
---


# Question
Title: Drupal 7 - Call the default/base template implementation
I am overriding `node.tpl.php` for a specific node (`node--news.tpl.php`) to display it differently in the front page. Instead of copying `node.tpl.php` code into `node-news.tpl.php` to display the node with the default rendering when we are not on the front page, I would rather prefer calling the base template implementation (node.tpl.php).

```
if ($is_front)
  // ...
else
  base_template(/* ... */);

```

Is that possible ?

Thanks,

**Solution :**

```
function template_preprocess_node(&$variables)
{
  if (drupal_is_front_page() && $variables['node']->type == 'news')
    $variables['theme_hook_suggestions'][] = 'node__news__front';
}

```

Then, simply edit the template file `node--news--front.tpl.php`

# Answer
I would do this in the preprocess stage, eg, in your preprocess\_node() hook, do something along the lines of:

```
$node=$variables['node'];
if ($_GET['q']=='node') {                           // eg the frontpage (by default anyway) and not node/## (also then presumes this is a teaser view, too
  $foo=drupal_get_path_alias('node/' . $node->nid;  // or perhaps $foo=$node->path; works in D7?
  if ($foo=='news') {
    $variables['theme_hook_suggestions'][]='node__news';
  }
}

```

I saw "along the lines of" because I am just now getting to know D7 vs D6 and I could have some typos in there, but the logic is to set the template file to the node-news.tpl.php one only when the user is looking at the front page and your news node is presented there.

But also, from what I have seen, node--news.tpl.php suggests that it should be used for nodes of TYPE news, so, there may need to be a different name here as well. So, if that's what you mean, you could do this instead:

```
$node=$variables['node'];
if ($_GET['q']=='node' && $node->type=='news') {
  $variables['theme_hook_suggestions'][]='node__news__front';
}

```

and create a node--news--front.tpl.php file, or whatever the best practices name is :)
> 1 votes

# Answer
I have never tried this, but I suspect you can implement template\_preprocess\_node in your theme, use drupal\_is\_front\_page, and if `FALSE`, remove the specific template from the `$variables["theme_hook_suggestions"]` array.
> 1 votes

---
Tags: theming
---


# Question
Title: Should the plain text filter convert line breaks into p and div elements?
I have a plain text field in a content type. When I hit return between paragraphs the line breaks are there and show inside of firebug when I inspect the code. However, the body on the view page doesn't render any line breaks. I looked at the plain text input filter and the convert line breaks filter is checked. When I change to filtered html in the settings form of the body widget it works fine.

Do have to use the filtered HTML setting to get the line breaks converted?

# Answer
When you select "Plain text," you are not setting the field to use the "Plain Text" input format; you are setting the field to change the entered text into plain text.

text\_field\_formatter\_view(), the function that outputs the content of a text field, executes the following code, when the field is set to be shown as plain text:

```
case 'text_plain':
  foreach ($items as $delta => $item) {
    $element[$delta] = array('#markup' => strip_tags($item['value']));
  }
  break;

```

As you see, the text is passed to `strip_tags()`, which doesn't convert new-line characters in `<p>` or `<div>` tags.
> 2 votes

# Answer
The answer to your question is no, it should not.

But I always want it to and so do my users. For textareas that do not require "fancy" formatting, we have still **always** wanted line breaks to carry over into the display.

I use this in my theme's template.php to add them to plain\_text textarea fields:

```
/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$vars, $hook) {
  // Add line breaks to plain text textareas.
  if (
    // Make sure this is a text_long field type.
    $vars['element']['#field_type'] == 'text_long'
    // Check that the field's format is set to null, which equates to plain_text.
    && $vars['element']['#items'][0]['format'] == null
  ) {
    $vars['items'][0]['#markup'] = nl2br($vars['items'][0]['#markup']);
  }
}

```
> 9 votes

---
Tags: 7, input-formats
---


# Question
Title: I can't to expose the option sort Post Date in a view in Drupal 7
I have created a view type content, with the follow features:

**Format**

**Format:** Unformatted list | Settings

**Show:** Content | Teaser

**Fields**

The selected style or row format does not utilize fields.

**Filter criteria**

Content: Type (= article)

Content: Published (Yes)

**Sort criteria**

Content: Post date (desc)

When I checked the option "Expose this sort to visitors, to allow them to change it " in Sort Criteria\>Post Date and press Apply, the sort Expose doesn't show and when I am going again to Post Date I can see that the change was not stored, the "Expose this sort to visitors, to allow them to change it" appears unabled.

What's my error?

Thanks for your help.

# Answer
It seems to be an issue with having the devel module enabled. If you are using it try disabling it and it should work.
> 2 votes

---
Tags: views
---


title: Can feeds importer grab fields, too?

text:
# Question
Title: Can feeds importer grab fields, too?
I'm working outside the area of what I know about Drupal. We're looking at using feeds importer to migrate a number of nodes. However, I didn't see anything in the documentation about its ability to grab fields attached to those nodes. Can it? How do I configure it to do so?

We're using node export currently, which works well, but is tedious since we're doing it one-by-one.

# Answer
> 1 votes
It can, yes. We've used it extensively to import contacts (nodes) into a homebrew CRM.

After creating your Feeds Importer, you should see "Mapping" as the last item in your settings panel to the left. After configuring the rest of your importer to work with your export's format, the Mapping Settings of the processor will allow you to map source fields in your dataset to target fields in your actual destination content type. Your nodes should have the appropriate fields filled in on import.

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


# Question
Title: How do I create a custom Drupal 7 login?
On my site there are 3 types of users:

1. Public users who do not need to log in
2. Public users who need to log in in order to access documents (pdfs, excel, etc)
3. Users who maintain the web site (add, edit, delete content, etc)

I need to have a login form on my web site for the public users to log in to access what are otherwise "hidden" documents. These users will be public users so they will **not** have the ability to access anything related to the Drupal administration, such as adding content. I don't see how I can use Drupal's built-in Users system by adding a new role and modifying its permissions, especially since permissions are inherited from the authenticated user role.

What's the best way to go about this?

# Answer
> 1 votes
Drupal's administrative permissions are not necessarily linked to any specific role, and individual permissions can define access to anything from viewing individual content types to administrative functions like creating and editing--they aren't all tied to administrative features.

While it is true that all authenticated users will inherit permissions from Authenticated User, you can organize your permissions like so:

* Anonymous User: (Permissions for users that don't need to log in.)
* Authenticated User: (Remove all permissions *except* those needed to view documents)
* Administrator (new role): (Permissions necessary to administer the site)

Then, give the Administrator role only to the accounts used to administer the site. Nothing says you have to give that role to every Authenticated User. Administrators will be able to view documents (as with any other authenticated user), though this sounds perfectly reasonable if I understand your use case.

Additional contributed modules allow for more fine-tuning over access control. For instance, the Field Permissions module may be useful if the files you're looking to distribute have been attached to nodes via File fields; this will allow you to determine access control at the field level if necessary.

# Answer
> 0 votes
I would use Drupal's default role and permission system for this. But Content Access Module might also be an option.

# Answer
> 0 votes
Roles and Rules can help define access and you could try Login Destination.

---
Tags: theming, hooks, users
---


title: Widget settings hook for Drupal 7

text:
# Question
Title: Widget settings hook for Drupal 7
What hook is the equivalent in Drupal 7 for `hook_widget_settings($op, $widget)`, used in Drupal 6?

What hook is the equivalent in Drupal 7 for `hook_widget_settings_save()`, used in Drupal 6?

# Answer
> 1 votes
You can use hook\_field\_widget\_info().

Here you can give the widget settings.

---
Tags: 7, hooks, entities
---


title: Drupal and node relationships

text:
# Question
Title: Drupal and node relationships
For our final CS project, we have been tasked with building a project management system for a large corporation (which the company wants us to use Drupal). So far we have a few entities created (project, request, and task). A project can have many tasks, and a project can only have one request attached (the request is created first, once approved, a project is created).

Since Drupal is really more of a content (blogs/comments/articles/pages) management system, it is difficult to create dynamic forms that allow showing tasks attached to a project with the ability to add tasks directly within the project "form". I guess this would kind of be a master/detail view.

How can I go about building these types of add/edit/details "forms"? My first two ideas are:

1. Build custom add/edit/delete forms for each entity type
2. Build a node-add-project.tpl.php, node-edit-project.tpl.php, etc... for each complex view required

The downside to this is that my fields in my forms are now hard-coded. One requirement is that this system must be dynamic so the end-user can add a field if they need to.

How can I go about this? Templates? Custom Forms?

By the way I have googled, and googled, and googled (probably 5-8 hours) of different things (master details, complex forms, complex entity relationship forms) to no avail.

I am aware of the nodereference and entity reference (and all other reference) types. But these only allow you to use a dropdown list, or a select list, etc...

EDIT:

It is looking like building the database with the Schema API, and utilizing the Form, Theme, and security APIs are going to be our best bet.

Here is a good read.

# Answer
> 1 votes
Not exactly what you asked: Are you sure you want/must build this with Drupal? If you have to, have a look at entities. Be prepared to live with young and not perfect documented features. Entities are the Drupal thing of business classes. Nodes are one incarnation of them to manage content.

# Answer
> 5 votes
You should be able to duplicate this functionality using the Field Collection module.

In short, you attach a Field Collection field to an entity, and then define the Field Collection in a separate UI (/admin/structure/field-collections) by attaching additional fields to it. It will behave like (and is in fact internally represented as) a first-class entity, and the module allows you to manage these items from the same parent form you attached the Field Collection field to, complete with drag-and-drop for reordering and the like. It also has a number of other nice features, such as letting users with appropriate permissions add/edit/delete Field Collection items while viewing the parent node without having to go into the edit form itself.

---
Tags: 7, forms, theming
---


title: Different logic in Facets functionality

text:
# Question
Title: Different logic in Facets functionality
what I am trying to achieve is to filter the site's search results and produce results of 5 content types. Search API has helped me do that and very well I must say. There is one more thing though that I need to do and I am wondering it already supports such behaviour and/or if it can be solved by theming OR if I have to create a custom solution; so here it is:

Say my aforementioned content types are: Alpha, Bravo, Charlie, Delta, Echo. I want my facets to be produced in this manner:

* All (23)
* Alpha (10)
* Bravo (4)
* Charlie (0)
* Delta (1)
* Echo (8)

So what i need furthermore than the options your module provides is the "All" option as long as showing Facets which yielded no results.

Apart from that, I also need to bypass the "filter-like" functionality the module provides by default, where I have to click the "-" sign next to the link to go back to the main selection, and make clicking the link filter the results while leaving the other options there for clicking. So if I was to switch from "All" to "Bravo" i'd just had to click Bravo, something like a contextual filter of Content Types in a View, oh and yes, my results are in a view-page.

Thanks in advance.

# Answer
In the end I did all of this with jQuery alone.

I created a block that contains the

* All (23)
* Alpha (10)
* Bravo (4)
* Charlie (0)
* Delta (1)
* Echo (8)

options, I add the number with jQuery by counting the grouped results, and by JQuery again, I hide the appropriate grouping blocks. So the Facet API block was of no use to me and neither was the View's exposed filter.
> 1 votes

---
Tags: 7, views, search
---


# Question
Title: Is caching certain parts of a page possible?
I have created a drupal 7 commerce site that displays some real time data to visitors as current number of purchases, upcoming products in the next day or so etc. Is there a way to cache parts of the site / page so that not everything is reconstructed on every request? For example for each product everything can be cached except from the number of current purchases, so I would like to cache images, prices, theme etc, but not the number of current purchases. Is it possible?

# Answer
> 3 votes
If you use the Page manager together with Panels, then yes, this is trivial. Each "Pane", in a Panel can have it's own cache settings, and they can also be set on a per user basis, meaning you can cache things, even if they include data that is unique for the logged in user.

If you also add Cache actions on top of that, you can add some really aggressive caching that will be cleared only, and exactly, when the relevant data updates.

---
Tags: 7, theming, caching, commerce
---


# Question
Title: Where can I find good, reliable Drupal freelancers?
I've looked on Elance, Guru, etc for skilled, reliable Drupal freelancers without any luck. Are there any suggestions for where to look for these folks? Remote workers are fine for what I need done.

# Answer
A lot of generic freelancer site members may have used Drupal but usually work with anything, wordpress, joomla etc. Drupal has a fairly high learning curve and to get the best out of it you would be best with a Drupal Expert. Maybe try something closer to the Drupal community.

Using a Drupal resource for Drupal freelancers might provide more Drupal expertise...

http://drupal.org/paid-services http://drupal.org/marketplace-preview
> 2 votes

# Answer
You can try #drupal-consultants on IRC, freenode.

Mailing list: http://lists.drupal.org/listinfo/consulting

Forum: http://drupal.org/paid-services

Drupal groups:

1. http://groups.drupal.org/consulting
2. http://groups.drupal.org/available-for-hire
> 1 votes

---
Tags: 7
---


title: setTimeout and QuickTabs

text:
# Question
Title: setTimeout and QuickTabs
I'm using QuickTabs with a couple of views to show some content within tabs. This works fine.

Now, I want my tabs to automatically cycle. Basically, this issue sums up what I want to do.

The thing is, it partially works. I have two tabs, and it cycles to the second tab, but immediately goes back to the first. I have enough time to see it blinking, but that's it.

Here is the slightly modified code (original code does the same, I just find it nicer):

```
var rotateSpeed = 5000;
setTimeout(function featureRotate() {
  var active_tab = $('ul.quicktabs-style-basic').find('li.active')
  var next_tab = active_tab.next()
  if(next_tab.length){
    next_tab.find('a').trigger('click')
  }
  else {
    /* remove the following line if you don't want it to cycle */
    $('ul.quicktabs-style-basic').find('li.first a').trigger('click')
  }
  setTimeout(featureRotate, rotateSpeed);
}, rotateSpeed);

```

Debugging it, it looks like the `setTimeout` function works when it goes through the `else` statement, but not when it goes through the `if` one.

# Answer
> 2 votes
Alright, the problem was just plain old Javascript.

The bug made it look like the setTimeout had no delay parameter, which defaults to `0`.

After looking more at it, the `rotateSpeed` variable was not available in the block scope of the `featureRotate` function, but in its closure.

So I replaced the following:

```
// In the featureRotate function
setTimeout(featureRotate, rotateSpeed)

```

With:

```
// In the featureRotate function
setTimeout(featureRotate, this.rotateSpeed) // Look at this magic :-)

```

And it works perfectly!

# Answer
> 1 votes
You could use `setInterval()` insead:

```
function featureRotate() {
  var active_tab = $('ul.quicktabs-style-basic').find('li.active')
  var next_tab = active_tab.next()
  if(next_tab.length){
    next_tab.find('a').trigger('click')
  }
  else {
    /* remove the following line if you don't want it to cycle */
    $('ul.quicktabs-style-basic').find('li.first a').trigger('click')
  }
}

var rotateSpeed = 5000;
setInterval("featureRotate()", rotateSpeed);

```

---
Tags: 6, javascript, blocks
---


# Question
Title: D7: How to deal with the variables visibility?
Now I have some variables collected from POST

```
$a = $_POST['a'];
$b = $_POST['b'];
$c = $a * $b

```

I need to use them in 2 functions: hook\_form() and the callback mail\_send() the function that format and sends my email with form elements.

I have implemented the following hooks:

```
function MYMODULE_page() {...}
function MYMODULE_form() {...}
function MYMODULE_form_submit($form, &$form_state) {
mail_send($form_state['values']);
}

//a custom callback mail function call in the submit.
function mail_send($form_values) {}

```

...

Now I don't know where to place those variables to have maximum visibility:

* if I place them in MYMODULE\_form() the show up in the form but they are not available in the mail\_send().
* if I place them outside everything they are not available inside functions.
* if i place them inside a hook\_init() the same as above.

I need a place where all variables are visible. Thanks

# Answer
> -1 votes
For the maximum visibility use **global variables** like below

```
$a = $_POST['a'];
$b = $_POST['b'];
global $c;
$c = $a * $b

```

and you can anywhere like below,

```
function mail_send($form_values) {
  global $c;
  print_r($c);
}

```

There is no special methods exists in drupal, it is just like php.

---
Tags: 7
---


# Question
Title: Restrict a menu item only for a particular accessible after loggin and optionally for a role
This is the menu I have.

```
  $items['start'] = array(
    'title' => 'Take A Test',
    'page callback' => 'qe_start',
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

return $items;

```

What should be passed in this to make it accessible to a role/logged in user?

```
'access arguments'    => array('content'),

```

And how can I make this to a `callback_menu?`

# Answer
> 3 votes
If you actually just want to check if the user is logged in and don't want to set up permissions, you can set the access callback to 'user\_is\_logged\_in':

```
$items['start'] = array(
  'title' => 'Take A Test',
  'page callback' => 'qe_start',
  'access callback' => 'user_is_logged_in',
  'expanded' => TRUE,
);

```

# Answer
> 1 votes
You would normally define a permission for your module/page using `hook_permission()` and then assign that permission to a particular role/set of roles in the admin section.

You can then use that permission in your menu callback safe in the knowledge that only the roles you've allowed can access the page:

```
function qe_permission() {
  return array(
    'take a test' => array(
      'title' => t('Take a test')
    ),
  );
}

function qe_menu() {
  $items['start'] = array(
    'title' => 'Take A Test',
    'page callback' => 'qe_start',
    'access arguments' => array('take a test'),
    'type' => MENU_CALLBACK,
    'expanded' => TRUE,
  );

  return $items;
}

```

The permissions admin page is at http://mysite.com/admin/people/permissions just in case you haven't already seen it.

---
Tags: 7, routes, users
---


title: Skip items with empty values in View

text:
# Question
Title: Skip items with empty values in View
I've a view filled with events. Some events carry a date, some don't.
How can I leave out those without a date? There should be somewhere a `empty($date) ? hide($view) : break;`. But I don't know how to do this with a view. Any suggestions?

# Answer
> 1 votes
Add a filter to the View, and filter out all events where date is `NULL`.

---
Tags: 7, views
---


title: Showing content in popup in Drupal 7

text:
# Question
Title: Showing content in popup in Drupal 7
Like Modal Frame API in Drupal 6, is there a similar solution to load content in popup(without page refresh) in Drupal 7?

# Answer
> 2 votes
Take a look at

to name a few. There are probably more out there, but one of those should do what you want.

---
Tags: 7, ajax
---


# Question
Title: Trying to create user programmatically, running into issues
I'm attempting to programmatically create a user. I'd like to be able to create the user, then set the current global `$user` object to this newly created user. Here is what my code looks like.

```
    $new_user = array(
        'name' => $form_state['values']['username'],
        'pass' => $form_state['values']['password'],
        'mail' => $form_state['values']['email'],
        'status' => 1,
        'init' => $form_state['values']['email'],
        'roles' => array(
            DRUPAL_AUTHENTICATED_RID => 'authenticated user'
        )
    );

    if ($saved_user = user_save(NULL, $new_user)){
        user_load($saved_user->uid, TRUE);
        $form_state['redirect'] = 'member/profile';
    } else {
        $form_state['redirect'] = 'member/join';
    }

```

The reason for me essentially wrapping the existing user page is that there is a lot of additional functionality needed. This code does create a user in the database, but it fails in two places: 1) It does not create any roles for this new user in the `users_roles` table, and 2) It does not log the current user in or adjust the global `$user` object.

Any ideas why this is failing?

EDIT: Using Drupal 7.9

EDIT2: I solved the user not being logged in issue by using the function `user_login_submit`. Roles still aren't creating correctly, however.

# Answer
`user_save()` does nothing with roles unless they're part of the `$account` object (first argument passed in). Stepping through the code I can't see any reason why simply setting up a dummy `$account` var to pass in, just containing the roles, wouldn't work:

```
$new_user = array(
    'name' => $form_state['values']['username'],
    'pass' => $form_state['values']['password'],
    'mail' => $form_state['values']['email'],
    'status' => 1,
    'init' => $form_state['values']['email']
);

$account = new stdClass;
$account->roles = array(
  DRUPAL_AUTHENTICATED_RID => 'authenticated user'
);

if ($saved_user = user_save($account, $new_user)) {
  // etc...

```

`user_save()` seems to do all the rest of the required setup on the `$account` object so this should work fine.
> 0 votes

# Answer
Drupal's anonymous and authenticated roles don't get saved in the users\_roles table and you don't need to add the role yourself, all users are by default authenticated. Try editing your user in the backend, you'll see that it has authenticated checked off. The code you list above where you send the roles array in the $edit will work fine with any other role.
> 3 votes

---
Tags: users
---


title: Duplicate URLs for same node

text:
# Question
Title: Duplicate URLs for same node
Yesterday I found that one article from my website is indexed more than once in Google, and I discovered that the URLs are like like the following ones.

The same node is generated many times.

The original link is http://www.techiestuffs.com/gadgets/best-racing-games-available-android.

This doesn't happen for just a node; all other nodes are also indexed more than once.

I am afraid Google will penalize us for this.

Do you know of any solution to avoid this?
For which reason does Google generate this type of URLs?

# Answer
You should be ok with regards to Google penalizing you because you've got a canonical link statement in each page which will tell Google that the page is really just a duplicate of the main page.

```
<link rel="canonical" href="/gadgets/best-racing-games-available-android">

```

Google canonical link info
> 5 votes

# Answer
Those pages are generated from Views "paging" in this case (I assume) "the best racing games available on android" across 4 pages instead of putting them all on one, eg, the base url has the first X number of games, page=1 has the next X number of them, etc up to page 3. Just as long as the content is different on each page, I don't *think* google will ding you. But, if you are concerned, turn paging off in the view that generates this page and instead change it to show all items, and these extra pages will go away.
> 2 votes

---
Tags: 7, nodes, uri
---


# Question
Title: How to know if i click any link in drupal and set a variable?
I need some help for the following case:

In my content-type i have a cck link that redirect to another page. So, i need do this:

When, i click in the link.. In my content-type\_form (\[name\_content\_type\]\_node\_form) i need to extract a variable of this form of my node:

`form_state['values']['id'] = $id;
variable_set($id, 1);`

Then, when i stay in the another page (that is a form) ; in this form do:

```
$form['id'] = array(
        '#type' => 'textfield',
        '#default_value' => variable_get($id, 1)
);

```

for view the corresponding id.

How to do this?

# Answer
> 0 votes
As I understand it, you need to pass a value via the URL, and fix a forms element based on this.

You have to output a link ith your variable in it, in the form yoursite.com?variable=value, preferably via the l() function.

On your second page, the value will be accessible in several ways, for example in the $\_GET variable.

More powerfull and Drupalish, you could also implement a hook\_menu to be able to use clean URLs like yoursite.com/some\_menu\_entry/yourvalue and the corresponding function.

---
Tags: forms
---


title: Multiple taxonomies in single field

text:
# Question
Title: Multiple taxonomies in single field
Is there a module that allows you to combine two taxonomies?

Lets say I have the two simple taxonomies listed below.

Award:

* gold
* silver
* bronze

Year:

* 2012
* 2011
* 2010

Is there a module that allows me to add different deltas like "Gold+2012" and "Silver+2010" to the same field?

# Answer
You can try the Computed Field module.

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. \[…\] You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views.
> 0 votes

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


# Question
Title: Getting a linkable table of children in hook_block_view from taxonomy_get_children (Drupal 7)
I am trying to programmatically create a block that will display all of the children of the term being referenced by the current page in a linkable table (so that I can click on any of the taxonomy terms and then go to their page). So far I have managed to create an ordered list of children names with the following code:

```
function children_view_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);
      $term = taxonomy_term_load($tid);
      $children = taxonomy_get_children($term->tid, $term->vid);
      $stack = array();

      foreach ($children as $child) {
        array_push($stack,$child->name);
      }

      $theme_args = array('items' => $stack, 'type' => 'ol');
      $content = theme('item_list' , $theme_args);

      $block = array(
        'subject' => t('Children'),
        'content' => $content
      );
    break;
  }
  return $block;
}

```

But what I really want is a table that might contain some other details about the taxonomies but more importantly I would like each taxonomy in the list to be a link that will take me to that taoxnomies term page. I image the reason these terms are not linkable is because I am only passing the name into the array but when I tried to pass the actual term into the array I get an error from the theme module. How would I make these linkable? Also, I imagine that I could change the ordered list into a table by replacing the 'ol' in the call:

```
      $theme_args = array('items' => $stack, 'type' => 'ol');

```

with a table but I am not sure what I would pass instead of 'ol' and I could not find any documentation about this. Could anyone link me to such documentation?

# Answer
> 1 votes
You can use the `l()` function to create the link to each term, and the `theme_table()` function to build your table:

```
function children_view_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);
      $term = taxonomy_term_load($tid);

      // Set up the table rows and headers array
      $rows = array();
      $header = array('Link', 'Vocab ID');

      $children = taxonomy_get_children($term->tid, $term->vid);

      // Add a new row for each child term
      foreach ($children as $child) {
        $rows[] = array(
          l($child->name, "taxonomy/term/$child->tid"),
          $child->vid
        );
      }

      // Set up the params for the theme_table call
      $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');

      $block['subject'] = t('Children');
      $block['content'] = theme('table', $table);

      break;
  }

  return $block;
}

```

I've put a second column in there (Vocab ID) just as an example of how to add extra columns to the table.

---
Tags: blocks
---


# Question
Title: Roles in Features: Are they always imported in alphabetical order?
This is a request for more information outside of what was given here: User roles and keeping their IDs when using features

Basically, it's the age-old problem of storing Roles in Features, and then migrating or importing them into a new site.

Based on some observations of mine when putting roles into a feature failed, it seems like Drupal takes the Role Feature and imports the stored roles in alphabetical order.

For example, I have some roles on my site that I stored into a feature. They had been originally created and added to my development site in this order:

* administrator
* moderator
* subscriber
* training
* announcer
* blogger
* manager

However, when I migrated the Features code to a new version of the site on a fresh database install, Drupal took the roles Feature I created, and imported the roles it contained in the following order:

* administrator RID -\> 3
* announcer RID -\> 4
* blogger RID -\> 5
* manager RID -\> 6
* moderator RID -\> 7
* subscriber RID -\> 8
* training RID -\> 9

Is this normal behavior? And, if I just organize my roles into Features in alphabetical order, can I expect them to always be reimported in the same proper RID heirarchy?

# Answer
> 1 votes
Roles being imported in alphabetical order has been my experience, too.

**But counting on autoincrement IDs to be consistent between multiple sites is never a good idea.**

I recommend, instead of relying on the autoincrement IDs to be generated in a particular order, to avoid using autoincrement IDs.

* For Drupal 6 and Drupal 7, the Role Export module turns Role IDs into hashes of machine names, so they're consistent from site to site, regardless of import order.
* For Drupal 8, work is in progress to eliminate autoincrement Role IDs altogether.

---
Tags: users, features
---


# Question
Title: Adding content type to the class of each views row
I have a view that has a filter to only pull results from 2 content types. I would like each views entry to have a class that shows the content type of the node. How can I do it?

# Answer
You can add that into the views fields template for the row or you can add a node type field to your view, and make sure it's first or before the field you want to add the class to, and disable its display. Then, you can go to the field you want to add the type class to, select rewrite output, and use the contents of this first field as a replacement value in the class of the wrapper element.

Just rereading, the above just wraps a field in your row. To put that class in the row's html, you could edit up `views-view-fields.tpl.php` for your specific view and add a div wrapper yourself with that information in it (grab it all out of the $row variable provided). Keep the node type field in there but have it not displayed.

So, for example, if your view is named foo, you could create a `views-view-fields--foo.tpl.php` with this in it:

```
<div class="<?php print $row->node_type; ?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
</div>

```

where, if I am cutting and pasting right today, the only thing I've added is the opening div and closing div. This then wraps your whole row in your own div with class of nodetype.

You can find all of these templates in the views style information area (make sure your views code matches mine). Just save them in or under your theme directory.

ADDITION:

If you want to have the class in `<div class="views-row views-row-2 views-row-even....">` instead of adding another `<div class="....">` inside it, you can copy `views-view-unformatted.tpl.php` to one appropriately named for your view and grab the information needed for the node-type out of the `$view` variable there. You could also use a views\_preprocess() function to do it, although for stuff like this I like seeing it in the template, but that's just me. The function should be `mythemeormodulename_preprocess_views_view_unformatted(&$vars)` and you can add or modify any of the vars you want, once again, since $view is present, all the information about the view is as well. For ideas, check out the views code in `sites/all/modules/views/theme/theme.inc,` or where ever module code is stored on your machine.
> 1 votes

---
Tags: views, nodes, theming
---


# Question
Title: Added a secondary link through code. Why is my href URL getting decoded?
Added the following through code:

```
// $uri = custompath?type=All&field_id=2&storage=3

$secondary_links['menu_custom_item'] = array(
                      'attributes' => array( 'title' => $label ),
                      'alter'   => 1,
                      'href'    => $uri,
                      'title'   => $label,
                      'language'  => 'en'
                );

```

Why is it that when drupal renders the link the URL it links to is something like: http://mydomain.ca/custompath%3Ftype%3DAll%2526field\_id%3D2%2526storage%3D201110

Literally it links like that and obviously returns Page Not Found. As soon as I manually change the %'s in the path we're good again. Is there a way to prevent this? Do I need to deconstruct the URI and pass the variables in one by one?

# Answer
Try using urlencode ...

```
$secondary_links['menu_custom_item'] = array(
                      'attributes' => array( 'title' => $label ),
                      'alter'   => 1,
                      'href'    => urlencode($uri),
                      'title'   => $label,
                      'language'  => 'en'
                );

```
> 0 votes

# Answer
Resolved. Had to do with how the url() function works in Drupal. Because I was passing the href in a way that Drupal considered it an 'internal' path - the query string was not being processed correctly. Resolved by turning href in my code to an absolute link so Drupal views it as external.
> 0 votes

---
Tags: routes
---


# Question
Title: Detect if the value of a cck field has changed when a node is edited
Drupal 6.25, CCK 2.9

I have a node of type EVENT. The EVENT node contains several CCK fields that allow users to submit events to our calendar which go in to a workflow. If the user requested IT support at their event, the IT support person is e-mailed. If they will be hosting an event with food, the catering staff is notified.

Everything works great except that we can edit the event later upon their request. If the edits that we make change one of these values that is used to notify staff, I need the system to automatically notify those people.

I know how to handle notification and everything else works well, but I don't know how to detect if the state of a single field is changing.

DETAILED EXAMPLE:

*--- Event information... ---*

**Will you require IT support at your event?**

* I need my lecture recorded.
* We will require someone on hand to assist with software installation.
* Video conferencing
* Special request

(multiple checkboxes)

*--- More event information ... ---*

If that EVENT node is submitted, approved, and later edited to change the value of that field so that one of the boxes is checked, I need to handle that.

I have a custom module to handle this in and have experience writing validation and submit handling, but I'm not sure what values of $form or $form\_state are helpful to this task. I thought that I might store the value of the field as it was originally as a hidden field with a hook\_form\_FORM\_ID\_alter and then check that hidden value against the submitted value but it's hard to get CCK values in to hidden fields because you have to capture the value in an #after\_build function and... I'm just getting stuck and thought I'd ask for help.

Thanks in advance for your time and consideration!

**EDIT - My solution based on the suggestion from Jimajamma below:**

```
function sitecustom_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  // If we are saving an EVENT node...
  if ('presave' == $op && 'event' == $node->type) {
    // If the node already exists...
    if ($existing = node_load($node->nid)) {
      // If the FIELD_EVENT_TECH_SUPPORT value has changed...
      if ($node->field_event_tech_support == $existing->field_event_tech_support) {
        // Log the change.
        watchdog('event_edit', 'FIELD_EVENT_TECH_SUPPORT value did not change');
      } else {
        // Notify people accordingly.
        // TODO: Notification of staff of changed tech support for EVENT.
        // Log the notification.
        watchdog('event_edit', 'Event edited with FIELD_EVENT_TECH_SUPPORT value changed. Staff notified.');
      }
    }
  }
  // Handle other nodeapi uses, validation, etc.
}

```

And I'm not exactly sure if it's correct to do `if ($existing = node_load($node->nid))` because that block seems to execute even when an EVENT node is being created from scratch. I know that I could use `if ($existing->created != $existing->changed)` but I haven't thought through everything yet and exactly what I want to test, etc. For now, using what I've shown above won't trigger the notification in this case IF the node is new.

I guess I just wanted to get something up here in terms of a solution in case people find this in the future. I will move on to exploring how to make this easier to do/find with RULES and ACTIONS as time allows.

# Answer
> 3 votes
I haven't done this, but my first idea would be to do this in nodeapi() and do something along the lines of (this horrid pseudo code):

```
if ( $op == 'presave' and $node->type == 'event' ) :
   $existing = node_load($node->nid);
   if ( $existing ) :
       check your fields in $node against the $existing node
       if they are different do something

```

and take into account you may no longer need IT or catering, so that needs to be conveyed as well as if you need it afterall.

---
Tags: entities, 6
---


# Question
Title: Is there any documentation for the UUID module?
I think I need to utilize the UUID module to make universal ID's for some taxonomy terms. However, after installing the module it doesn't seem to do anything and the configuration interface has only one button that does nothing.

I can't find any helpful articles, tutorials, or documentation for this module. Anybody have any suggestions?

# Answer
> 5 votes
UUID is an "API" module. It wont do anything out of the box. It is for other modules to use the functionality provided by UUID.

See the module's README.txt file:

> This module provides an API for adding universally unique identifiers (UUID) to Drupal objects, most notably entities.
>
> ## FEATURES
>
> * Automatic UUID generation: UUIDs will be generated for all core entities. An API is provided for other modules to enable support for custom entities. See https://www.drupal.org/node/2387671
> * UUID API for entities, properties and fields: With this unified API you can load entities with entity\_uuid\_load() so that all supported properties and fields are made with UUID references. You can also save entities formatted this way with entity\_uuid\_save() (depends on Entity API).
> * Export entities to use as default/demo content: The integration with Features module provides the ability to export UUID enabled entities with intact dependencies and references to other entities. This functionality depends on Deploy module 7.x-2.0-alpha1 (soon to be released) and is probably the most robust way for installation profiles and distributions to provide demo content!
> * Services integration: The integration with Services module alters all UUID enabled entity resources (nodes, users, taxonomies etc) to be based on UUIDs instead. This way it becomes easier to share and integrate content between sites. This functionality is used by Deploy module.
> * More integrations: UUID module integrates with Views, Token, Rules and provides some CTools plugins.

---
Tags: entities
---


title: Permissions problem with OG group pages

text:
# Question
Title: Permissions problem with OG group pages
I can't see why it's the case, but one of my site editors cannot edit the content on OG group pages.

Our groups are private, but that users is a member of all the groups in the site and the "site editor" role should allow him to edit any content anywhere on the site.

There are two kinds of groups, which each have their own content type (because they are subtly different), but the role's permissions settings are identical and the "site editor" role has all boxes ticked in the role based access control settings for both the content types. For both the content types, the "site editor" role also has the create, edit (own/any) and delete (own/any) permissions.

The main problem seems to be that the edit menu isn't appearing for that user.

I'm evidently overlooking something somewhere, but I can't just see where. Surely the role doesn't also need "administer Organic groups permissions" granted.

Is anyone able to point me to the obvious mistake I'm making?

# Answer
> 3 votes
Take a look at Configuration -\> Organic Groups Global Permissions (drupal/admin/config/group/permissions). There you will find really fine grained controls over who can view and edit nodes and fields on your group pages.

---
Tags: 7, users, organic-groups
---