title: Adding content when creating a node

text:
# Question
Title: Adding content when creating a node
I'm currently building a system to create rapports for a set of possible units. So far I have built a set of content types in CCK that acts like templates where the templates fields are used to add structures that the users creating the rapport will fill out.

I have, in my template, a list of "key value names" that will then be added to the rapport and the user can fill them out.

```
The Template:
a, b, c

The rapport:
* a = x
* b = y
* c = z

```

where x,y,z is entered by the user generating the rapport.

I found this here on drupal.stackexchange.com and I guess it's on the right track. But I don't understand what I would fill in 'hooks' with and how to limit the action to only trigger on(/before) node creation. There is also a number of sub-nodes that needs to be created based on the templates, but that part I haven't research yet, if it is connected please include information about it in your answer if possible.

# Answer
Per the question you linked to, the Rules module will do this very well and can be used to call your custom actions when criteria are met during pre-save, validation, or other stages you might need.

It's worth pointing out that, since you want custom nodes created, you're likely to already need to be writing custom code. In this case a better approach might be to write an implementation of hook\_nodeapi() (Drupal 6) or hook\_node\_{operation}() (Drupal 7) that means you can fire your own custom code at specific points during node creation.

Take a look at this question about how to make nodes programatically, and also this article with more detail about the process in Drupal 7 (only in Google cache). Extract of the article:

> **1 Initialize a node object**
>
> ```
>  $node = new stdClass(); // We create a new node object $node->type =
>  "page"; // Or any other content type you want $node->title = "Your
>  title goes jere"; $node->language = LANGUAGE_NONE; // Or any language
>  code if Locale module is enabled. More on this below * $node->path =
>  array('alias' => 'your node path'); // Setting a node path
>  node_object_prepare($node); // Set some default values. $node->uid =
>  1; // Or any id you wish
>
> ```
>
> \*We set LANGUAGE\_NONE for $node-\>language, if you don’t have the locale module enabled, the node will not be assigned any particular language. So that's why we put here the constant LANGUAGE\_NONE. In Drupal, nodes and fields can exist in more that one language, so if your site is multilingual you should specify the language code for your field. You can configure languages and get language codes by going this path in Drupal administration: Configuration -\> Regional and language -\> Languages.
>
> **2 Add a body field**
>
> ```
> // Let's add standard body field
> $node->body[$node->language][0]['value'] = 'This is a body text';
> $node->body[$node->language][0]['summary'] = 'Here goes a summary';
> $node->body[$node->language][0]['format'] = 'filtered_html'; // If
> field has a format, you need to define it. Here we define a default
> filtered_html format for a body field
>
> ```
>
> **3 Add custom fields**
>
> ```
> // Let's add some CCK/Fields API field. This is pretty similar to the
> body example  $node->field_custom_name[$node->language][0]['value'] =
> 'This is a custom field value'; // If your custom field has a format,
> don't forget to define it here
> $node->field_custom_name[$node->language][0]['format'] = 'This is a
> custom field value'; // And etc. you can add as much fields here as
> your content type has. The sky is the limit... and the server specs,
> of course ;)
>
> ```
>
> **4 Add file / image fields**
>
> ```
> // Some file on our system $file_path =
> drupal_realpath('somefile.png'); // Create a File object $file =
> (object) array(   'uid' => 1,   'uri' => $file_path,   'filemime' =>
> file_get_mimetype($file_path),   'status' => 1, );  $file =
> file_copy($file, 'public://'); // Save the file to the root of the
> files directory. You can specify a subdirectory, for example,
> 'public://images'  $node->field_image[LANGUAGE_NONE][0] =
> (array)$file; //associate the file object with the image field:
>
> ```
>
> **5 Add a term to a node**
>
> ```
> $node->field_tags[$node->language][]['tid'] = 1;
>
> ```
>
> field\_tags here is the name of a term reference field attached to your content type, 1 is a term id you wish to assign to a node. Simple!
>
> **6 Save a node**
>
> ```
> $node = node_submit($node); // Prepare node for a submit
> node_save($node); // After this call we'll get a nid
>
> ```
> 1 votes

---
Tags: entities, hooks, nodes
---


# Question
Title: SEO-friendly Views: How do I make contextual filters work together with exposed filter criteria?
I have substituted my frontpage with a view at http://example.com/frontpage.
I use it with two exposed filters: country and city. The current url format (http://example.com/frontpage?country=us&city=New York) is not too much SEO friendly.

What I would like to use is http://example.com/frontpage/us/New-York.

How do I do it with Views and Drupal 7?

# Answer
> 7 votes
You're nearly there, but you need to replace your exposed filters with equivalent Views arguments (i.e. Country and City). Then if you change the view's 'page' display path from `frontpage` to `frontpage/%/%`, each percent will be mapped to the arguments in the order they appear.

Once the above is done you can still use exposed filters for other fields to control the view, but they will need to be other for fields. If you need to change the city/country arguments inside the %, look into making a 'Jump menu' view display to provide a drop-down to control the view, rather than an exposed filter. Also see the Jump module.

If you need more power, a related alternative is to re-create the page in Panels which will allow you to pass arguments to several views in different panes at the same time. Views should do the job on its own for you, though.

---
Tags: views
---


title: Drupal 7 Update Module Not Working

text:
# Question
Title: Drupal 7 Update Module Not Working
I just upgraded to Drupal 7 from Drupal 6. It appears I've finally gotten everything working, except the module updater isn't working; it can't update from a URL or a file. I also cannot install new modules.

I check the box next to the module to update and it appears that it's working, or downloading; it works for a few seconds, then it just reloads the updater page and nothing has changed. It is the same when I install a new module, entering the URL for the module, or choosing the file from my computer. Again, it appears to be working, but it just reloads the module install page.

# Answer
> 1 votes
This sounds like a folder permissions problem.
Check to see that the user account that your web server is using to server web pages has write permissions in the 'sites/all/modules' folder. Your webhost can help you with this.

---
Tags: 7, updating
---


# Question
Title: How can I place content in page_top in D7 since it is hidden in regions?
I need to place a small menu in the page\_top region using D7. I know the region is hidden, so my thought is to create a completely new region in the place that page\_top would be showing up (I'm not sure how this is done). I have been creating a subtheme using Zen. Does anyone have an idea about how I can do this? Help is sincerely appreciated.

# Answer
> 2 votes
In the .info file of your theme you can add regions.

The template files that control your page layout are going to display that region.
Usually page.tpl.php will have the regions called upon for display. So if you add a region to the .info file you will need to add the region in the page.tpl.php file as well.

Great article here... a little dated.. but still works. http://yuriybabenko.com/blog/creating-new-drupal-regions

---
Tags: theming
---


# Question
Title: Visibility depending on several values of another field
I'm having a form with two field. And visibility of the one is depending on the values of the other.

```
    $form['property'] = array(
    '#title' => t('Property'),
    '#type' => 'radios',
    '#options' => array(
        'private' => t('Private'),
        'bail' => t('Bail'),
        'lease' => t('Lease')
    ),
    '#required' => TRUE,
);

$form['bank'] = array(
    '#title' => t('Bank / leasing company'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#states' => array(
            'visible' => array(
                ':input[name="property"]' => array('value' => 'bail'),
            ),
        ),

);

```

What comes to `':input[name="property"]'`. How do I make it visible when `"bail"` OR `"lease"` values are set?

# Answer
The Conditional Fields module should be able to do that.
> 2 votes

# Answer
You need to use Ajax, both a Wrapper and a callback. The wrapper will be set to be hidden by default with a little function to determine the set value of `$form['property']` if it is `"bail"` OR `"lease"`
> 0 votes

---
Tags: forms
---


title: Similar entries 7.x-2.0 known error

text:
# Question
Title: Similar entries 7.x-2.0 known error
When I try the view for out-of-the-box use that comes with Similar entries 7.x-2.0 i get this error:

Strict warning: Declaration of similar\_handler\_argument\_nid::query() should be compatible with that of views\_handler\_argument\_numeric::query() in require\_once() (line 11 of C:\xampp\htdocs\drupal\sites\all\modules\similar\views\similar\_handler\_argument\_nid.inc).

I searched drupal.org and found someone with the same problem: http://drupal.org/node/1270404 with no answer since September so I decided to try here.

I have tried the beta1 and dev version, run cron, tried to find some tutorial on how to use the module, read the readme for the module and had no luck. Am I missing something obvious?

I also get the error:

SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'score' in 'order clause'

# Answer
> 1 votes
This is not you, it is a bug in the module. I'm sorry to say that the fact that the bug goes back to September does not bode well for a fix. Neither does the fact that there is only one active maintainer who has not made any changes since the releases in August. If you are a coder, you might try fixing the code. If not, you may want to look for other options.

---
Tags: 7
---


title: Image and other media file management

text:
# Question
Title: Image and other media file management
My question may seem vague but I'm confused and need advice on Drupal 7 media files management, so please bear with me. I'm looking for existing modules or ways to build the following functionality with minimal effort:

1) Image management. I'm building a site that is mostly text articles with a random image or two scattered here and there (an average Wikipedia article may be a good example). I want to be able to

1.a) insert scaled image thumbnails into my text and provide an explanation of what is in the image right under it (exactly as they do in Wikipedia). This doesn't seem to be standard Drupal feature when handling images.

1.b) if it is possible I also want my image thumbnails to be clickable with links leading to original unscaled images (again something that can be seen at Wikipedia, though they first lead you to another page that contains image information and copyright status).

2) Media file management. Sometimes I want to attach a file to an article that browser itself won't handle, something like .mp3 or .pdf. If I simply add a File field to an article, it won't offer any protection against anyone who decides to download it. Can I possibly make downloading a file a bit more complex - like forcing a visitor to enter captcha first?

# Answer
Ari,

Let me start off by saying that media files (images, videos, etc..) attached to nodes, Meaning they are acctually uploaded when entering in a node content, those files are stored in the default file folder (usually 'sites/default/files' ), unless that field in the content type specifies otherwise.

Example: If i create a *content type* called *'blog entry'*, I would add a field to that content type called media. When you get to the screen where you can edit the field information, you can select accepted file extentions, where the files would be stored in relative path to the default file location in your sites file location settings (again, usually: sites/default/files)

I would make this file location *'blog-entry/media'* for this new field in my new content type. So my files would upload to: *sites/default/files/blog-entry/media* when i uploaded them during the addition of content.

The thumbnail settings are somewhat default and can be adjusted under the *display settings* for the content type. THere are default thumbnail parameters you can select from, or you can add/remove thumnail options in the site settings as well under *image settings*

Once you get a hang of this flow you will see how easy it really is to manage media.

Another module worth looking into (after you have done the above, so that you may understand what the core of Drupal is doing with your media files), is the Media Module. It makes uploading and managing a little easier than core.

Also to note: stay away from Media Gallery right now.. its a mess as of this week.. most bugs should be resolved sometime next month.
> 1 votes

# Answer
Seems like there is no straightforward solution to either of my questions. Here is what I've found:

1. For handling images and placing them where I like I now use the Insert module. It works with popular WYSIWYG editors but I personally hate WYSIWYG and prefer raw code. The Insert module relies on content type fields, but allows user to choose where to place uploaded image. After installing the module, I went to admin/structure/types/manage/%yourcontenttype%/display and set "Image Label" and "Format" to hidden; this prevents images from showing before or after your text body. Then, I just used the "Insert" button that appears in article edit form. I couldn't find how to make it insert clickable previews or wrap them into style-able DIVs, so I had to do it all manually. The Insert module generates something like this in the article text:

```
<img src="http://yoursite.com/sites/default/files/styles/medium/public/images_in_articles/bla-bla.jpg" alt="Bla" title="Bla" class="image-medium" />

```

I then manually write code that surrounds image preview:

```
<div style="float:right"><a href="/sites/default/files/images_in_articles/bla-bla.jpg">
  <img src="http://yoursite.com/sites/default/files/styles/medium/public/images_in_articles/bla-bla.jpg" alt="Bla" title="Bla" class="image-medium" /></a>
  <div>Explanation</div>
</div>

```

It doesn't look nice, but it does its job well.
2. As for forcing users to enter a CAPTCHA on file download, there is also no ready solution. I've found a module written by some Russian guy for Drupal 6-x and 7-x, but I have yet to look into it.
> 0 votes

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


# Question
Title: Page not found when trying to access my custom module
Something is very strange. I have built 8 modules and they all work fine. When I installed the 9th one, it said "Configuration options have been saved" but when I access the path, I receive a "Page Not Found".

Tried : reinstalling module / clearing cache / recoding the whole module / renaming the module / using other path / rebuild permissions / ... even reinstalled the whole site and reconfigured it all.

All other modules are working but the 9th one fails.

I have seen many posts about this, but none of the options have helped me so far. Where did I make a mistake? Where can I look in the database to find out more?

# Answer
`hook_menu()` had 3 entries: one for entering parameters, one for showing the question selection, and one for showing the answers.

The error was in the second page, which still pointed to an old (disabled) URL.
The very very strange thing is that the module didn't show even the first working path and that there was no error of it.
> 1 votes

# Answer
@Droopy apart from checking the error reporting and logging ...if the module defines its own tables in an install file, delete them after the uninstallation in case its not written in your `hook_uninstall` and check if the tables are being created properly during the reinstallation of the module (provided you have full permission to access the DB)..also if possible delete the entry for your module in `system` table and reinstall the module... that worked for me in similar occassions..also request you to tag your drupal version in the question to help identify similar issues to other users..
> 0 votes

---
Tags: 7, hooks, uri
---


# Question
Title: Is taxonomy a good choice for managing Code Lists, instead of creating tables of their own?
I have a project where there is a set of code lists (code/label), Airport codes for example.

I am hesitating between creating my own tables, with two columns code/label and using Taxonomy (fieldable \o/ ) Any suggestions ?

# Answer
Since there isn't anything common between codes and labels, I think you should create your own table.

Also see How to Decide Between Using Taxonomy Terms and a CCK Field
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: How can I count the number of nodes submitted by the current user?
I want to expose in a block the number of content type published by the current user. I know we can write a query, but is there any other method to do it?

# Answer
You can use the Views module to do this.

1. Create a new view
2. Remove sort options, fields and other default settings
3. Add a field for "Content: Type"
4. Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
5. Add yet another field for "Content: Type"
6. On the second "Content: Type" field, click "Aggregation settings"
7. Set the aggregation type to "count"
8. The second "Content: Type" should now look like "COUNT(Content: Type)"

THIS IS NOT MY SOLUTION LOOK HERE: Count of nodes by type
> 3 votes

# Answer
The two ways that come to mind are to write a custom query as you suggest, or use the Views module to create a block with the content you need.

Views essentially provides a UI for creating custom queries that you can then automatically add to a block/full page/etc.

Depending on your level of PHP/MySQL experience it may actually be easier to write the query yourself...Views has a fair bit of a learning curve although there are a lot of tutorials out there if you search on Google.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: Is there a way to show a node's comments when displayed in teaser format on the taxonomy term page?
Is there a way to show the first page of a node's comments when the node is displayed in teaser format, e.g. on the taxonomy term page? I am building a site with 'posts' (a node type) which have comments, but I want users to be able to read comments, and leave comments from the taxonomy term page.

Is there a way to do this programmatically?

# Answer
I figured it out! with the help of @amateur-barista !

Here's the code I added (replace 'hook' with your module name):

```
function hook_node_view($node, $view_mode, $langcode) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
      $node->content['comments'] = comment_node_page_additions($node);
  }
}

```

thanks!

david barratt
> 1 votes

# Answer
**Associate a custom node to each taxonomy term.**

1. Create a content type of "taxonomy term page" with comments enabled.
2. Add a custom field of type "taxonomy term".
3. Create a View, with a display of type block. Add to it a contextual argument of type taxonomy, and specify from where in the URL path is the argument going to be found. This should filter out nodes based on the current taxonomy found in the URL path. For safety, add a content type filter (regular, non-contextual), and specify "taxonomy term page".
4. Change the render type from "fields" to "node", or something like that. Try to see if in the node display option, you can choose to render comments as well.
5. Using Context, add a condition for `taxonomy/term/*` paths.
6. In the same Context, add a reaction of type block. Browse and select your block. Add it to the desired region. Save.
7. ...
8. Success!

I tried to suggest the "easiest" option, which was using Views. If however for some reason Views won't allow you to render a full node view - with comments enabled - then you will need to create your block programatically using hook node view. But you still get the idea. The purpose is to take advantage of the existing comment-to-node architecture to avoid writing custom code as much as possible.
> 2 votes

---
Tags: 7, taxonomy-terms, nodes, comments
---


# Question
Title: Using wildcards in custom module outputting sql query
It has become obvious to me that SQL syntax is a little different within drupal.

After some fiddling around I am getting the hang of it, but I haven't been able to use wildcards succesfully.

```
$sql = 'SELECT name Nombre, mail Email  FROM users WHERE status = 1 AND mail LIKE ('%@hotmail%') LIMIT 25';

```

Do you have any suggestion? I haven't been able to find (or I might be looking in the wrong places) for Drupal documentation regarding wildcards within `$page_content` in a module.

# Answer
Your code has the following errors:

* The string delimiter for the query is the single quote character, which is the same delimiter you use for the string inside the query.
* The table names are always surrounded with *{* and *}*, which allows Drupal to prepend the prefix set in settings.php to the table name.
* If you need to use the *%* character as wildcard character, you need to escape it with another *%*, in a query passed to the database API.
* If you need to limit the number of returned rows, in Drupal you use db\_query\_range() that allows to use a query that is compatible with every database engine for which there is a driver for Drupal. If you look at the code used from that function for different database engines, you will notice it will use a different syntax for different database engines, such as:

### MySQL/MySQLi

```
$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $from . ', ' . (int) $count;

```

### PostGreSQL

```
$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from;

```

Your code should be written as the following one:

```
$sql = "SELECT name, mail FROM {users} WHERE status = 1 AND mail LIKE '%%@hotmail%%'";
$result = db_query_range($sql, array(), 0, 25);

while ($row = db_fetch_object($result)) {
  // $row->name contains the username, and $row->main contains the email address.
}

```

This is code taken from a Drupal module that uses the `LIKE` operator:

```
  $query = "SELECT url, COUNT(url) AS hits, MAX(timestamp) AS last FROM {accesslog} WHERE url NOT LIKE '%%%s%%' AND url <> '' GROUP BY url";
  $query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> '' AND url NOT LIKE '%%%s%%'";

```

The query uses 5 *%* because the first 2 are for using *%* as wildcard, the third is for the "%s" placeholder, and the last two are again for using *%* as wildcard.

This is an example of code used by a module that limits the number of rows the query returns:

```
        $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {term_node} tn ON tn.vid = n.vid INNER JOIN {term_data} td ON td.tid = tn.tid INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND td.vid = %d ORDER BY l.last_comment_timestamp DESC");
        $result = db_query_range($sql, variable_get('forum_nav_vocabulary', ''), 0, variable_get('forum_block_num_0', '5'));
        $content = node_title_list($result);

```

The query string is passed to `db_rewrite_sql()`, but that is irrelevant, here; the code would not change if it didn't need to use `db_rewrite_sql()`.
> 1 votes

---
Tags: 6, database
---


# Question
Title: Template file not loading for block view
I have a block view in the header. The suggested tpl files are block\__mens\_header (block--mens-header.tpl) as well as node--mens-header.tpl For some reason the more general tpl files are working but I need to get specific here. Is there a preprocess function I need before these will be seen?

# Answer
I seem to remember, in drupal 6 at least, that you need to have block.tpl.php there, even if you don't modify it at all, in order for the specific block templates to be seen.

ADD: If it's in there, you might try a preprocess\_block() hook with something like:

```
$variables['template_files'][] = 'block--mens-header';

```

stuck in it. This should point it to block--mens-header.tpl.php in your theme directory. Obviously, wrap that in some logic so it's only set for the block in question.
> 1 votes

---
Tags: views, theming
---


# Question
Title: What is the difference between wysiwyg module + ckeditor and ckeditor module?
What is the difference between using the Wysiwyg module and the CKEditor - WYSIWYG HTML editor module? Are there benefits on using one over the other?

# Answer
> 9 votes
I've played with both recently and can offer some insight, at least for Drupal 7.

The Wysiwyg module lets you use any number of editors, such as CKEditor. It also integrates with the Media module if you use that. If you don't want to use CKEditor, but, say, TinyMCE, then you'll want to use Wysiwyg.

The CKEditor module is (obviously) just for CKEditor, and has more options specific to CKEditor. For example, you can change the skin CKEditor uses (Office 2003, Karma, etc). You can also set advanced CKEditor config options which you can't do with Wysiwig+CKEditor. It also integrates with some file browser modules like CKFinder. And I believe you can use the Media module with new versions of CKEditor.

One of the big reasons I went with the CKEditor module is that it doesn't strip out JavaScript. I couldn't find a way to get Wysiwyg+CKEditor to preserve JavaScript.

# Answer
> 2 votes
> And I believe you can use the Media module with new versions of CKEditor.

I confirm CKEditor works with the Media module.

Here's how to enable it: http://drupal.org/node/1022986#comment-4403648.

# Answer
> 0 votes
By installing Ckeditor via Wysiwyg module gives you ability to select the tools you want to be default in a text format.

For example you don't want to show Image option in the default editor to users you can uncheck that in Wysiwyg module settings.

I use Wysiwyg + ckeditor + media to get the things done.

---
Tags: wysiwyg
---


title: Loggin into Drupal using Yahoo mail

text:
# Question
Title: Loggin into Drupal using Yahoo mail
Merry Christmas to all, I would like to allow users to log in my site using their Yahoo e-mail. Is there a module for that?I am using Drupal 7. Thanks

# Answer
Try the RPX (Janrain Engage) module.

> Using Janrain Engage, Drupal sites can authenticate new and existing users with popular social networks, map user profile data from these websites to Drupal fields, and share Drupal content with a user's friends on their social networks.
>
> This includes Facebook, Twitter, Google, Yahoo!, LinkedIn, Myspace, AOL, PayPal, and Windows Live (see the complete list below).
> 3 votes

---
Tags: users
---


title: A "No results" View problem

text:
# Question
Title: A "No results" View problem
I would just like to hear a confirmation from someone: If I have a View A that displays View B in case of No results, does the View B display with all its attachments? Somehow I cannot get this cascade to work. The attachment does not show and I'm not sure it's because of limitation or is it me (again)...

# Answer
OK, it was me, I have not provided the specific view display, and the "default" did not work. No wonder. Sometimes asking a question in the air makes the answers come along magically.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to set up a contextual filter or child relationship?
Every now and then I'm re-attempting to set up a decent taxonomy explorer/browser. I have already managed to customize a tpl file for that (oh, I know, tpl should not contain advanced logic, some day I'll learn how to do that properly). Now I decided to give it a shot using Views. While I managed to set up a view for the top-level listing, now I'm trying to set up a decent lower-level browser. I don't think it's possible, but maybe you will prove to me that it is. My taxonomy has a very simple structure in that **at a given level it has only branches or leaves, never are they mixed**. Now, at some level (the depth is variable at different branches), the branches end and the leaves are to be listed. Therefore I'd thought this logic would be appropriate:

```
on page taxonomy/term/%
list items which
(a) belong to vocab X
and ((b1) are either children of parent with tid=%1
(b2) or are published nodes of content type Y with term tid=%1 assigned.)

```

For (b1) I have defined a parent term relationship and used it as a contextual filter. This alone works, but I don't know how to set up the b2 part. Can I re-use the same part of URL for another or'ed contextual filter. The '%1' string does not seem to work when entered in the filter section. What am I doing wrong?

Thanks.

# Answer
> 1 votes
Apparently there is no way to solve it using contextual filters and relationships. I solved the b2 part by using a separate dedicated view of content nodes as a No results view. It works because the taxonomy has consistent, non-mixed level contents.

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


# Question
Title: Can I disable the #required form attribute temporarily?
I have functionality set up where an admin can create a user with a content profile. The content profile has a required field but I want the user himself to fill it out. How can I disable the required-ness of that field when the admin is creating the user so he can submit the form. I tried setting #required to 0 or unsetting it, but that does nothing.

```
function mymodule_form_contenttype_node_form_alter(&$form, &$form_state) {
        $form['field_reviewer_instruments']['#access'] = FALSE;
        $form['field_reviewer_instruments']['#required'] = FALSE;
}

```

# Answer
> 1 votes
This is most likely because of the ordering. THe module which is altering the form and setting the required element is being run after yours.

In the system table set your module weight to be higher than the module which is affecting the form.

# Answer
> 1 votes
Another answer mentioned the ordering which is probably right. Another way to handle this is to use the #after\_build property and do it in the function defined there.

---
Tags: 6, forms, users
---


# Question
Title: View output a custom designed teaser then full post separate design
I have a design that requires and custom design for the teaser view. I need to output the custom teaser view then have the full post follow another template.

The teaser has a float left thumbnail image and a few lines of text to the right. The actual post will have many images and text.

Is this possible?

# Answer
> 3 votes
Sure it is possible.For that you need to add custom field in your content type called featured image. While creating the views use that field first and you can have to add

```
float: left;

```

In Image field css class to align it left

For exmaple you can see my site www.techiestuffs.com which is exactly what you mentioned.The teaser has image aligned left and when you click either image or title it will leads to original content. see the below css code i used to achieve this

```
  .view-recentarticles .views-field-field-image {
float: left;
padding: 3px;
border: 1px solid #C9C9C9;
white-space: nowrap;
margin-right:10px;
margin-bottom:5px;
}
.view-recentarticles {
padding:5px;
border:1px solid #ccc;
background-color:#ffffff;
}

.view-recentarticles .views-field-title {
  margin-bottom: 10px;
  padding-left:10px;
  font-size: 18px;
  line-height: 1.4;
  font-weight:bold;
  background-color:#f4f4f4;
  }
  .view-recentarticles .views-field-title a {
  transition: all 0.2s;
  -moz-transition: all 0.2s;
  -webkit-transition: all 0.2s;
  -o-transition: all 0.2s;
 }
 .view-recentarticles .views-field-title a:hover {
  color: #181818;
 -webkit-transition: all 0.2s;
  text-decoration: none;
  background-color: #f6ecdd;
 }
  .view-recentarticles .views-field-body {
  padding-bottom:5px;
  border-bottom:2px solid #f4f4f4;
  }
    .view-recentarticles .views-field-field-blog-author {
    font-size:10px;
    font-weight:bold;
  padding:5px 2px 5px 2px;
  background-color:#f4f4f4;
  }

```

---
Tags: views, nodes
---


# Question
Title: How to create review site with Drupal 7.7, FiveStar 2.x-dev, Node Reference URL, and Unique field?
How to create review site with Drupal 7.7, FiveStar 2.x-dev, Node Reference URL, and Unique field?

Configuration:

1. Drupal 7.7
2. FiveStar 2.x-dev
3. Node Reference URL Widget
4. Unique field
5. Bartik theme

What I have now are:

1. Product node
2. User can write a review and rate each product node with multiaxis fivestar (value, price, and reliability).
3. User can create only one review per product (unique field module).
4. Rating is available when User create a Review node (Node Reference URL).

Questions:

1. How to embedded product node on the top of the review node? I want user to see what they are voting for without going back to the product node page.
2. How to create average rate of each category (value, price, and reliability) using Views?
3. How to compute average of all rating categories values? It means to create one number computed from average rating of value, price, and reliability.

Thanks for helping.

# Answer
> 0 votes
I think this is what you need, its simple and clear about the topic http://drupal.org/node/1308114 only the thing you need is to just spend couple of minutes on it, you'll surely get what you are trying to achieve.

Good luck!

# Answer
> 0 votes
Yes you can make good review site with those mentioned but still now there isn't any plugin or hack for achieving Google Review Snippets.

http://drupal.org/node/901260

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


# Question
Title: How to ask for user confirmation when submitting a form using FAPI
What I want is suppose a user enters same data twice in two rows then I want to show her an error/warning and now if she chooses to press submit again then I'd process and accept the form.

How to do it?

# Answer
> 2 votes
use the confirm\_form function. See Here and Here for examples

> This function returns a complete form array for confirming an action. The form contains a confirm button as well as a cancellation link that allows a user to abort the action.

---
Tags: 6, forms
---


# Question
Title: Commerce / Rules: How to update node that references a given product when the product is updated
I am trying to follow the Commerce Product model of Node Display that references each product.

When I create a product, Rules automatically creates a Node with the same title, and references the product in the node.

However also using Rules, I would like to perform the following:

* When product is updated, update the referencing Nodes Title / Published attribute
* When product is deleted, delete the referencing Node

I can't figure out the way to fetch the Node Entity in Rules at all.

Thanks!

EDIT:

As per @rfay's comment below, I've attempted to go down the Bi-directional reference route, which means installing the References module and create a node\_reference field in the product that points back to the node.

Unfortunately however it seems Rules is not providing the means to fetch the node entity, as it is not recognizing the existence of the node\_reference field on the product by which to fetch the node from.

# Answer
If you want to delete the product display node, you need to hook the entity update (e.g. on node update). If the product reference field is empty, you can delete the node. But the product reference field must be a required field.

When the Drupal commerce module deletes a product, it needs also to delete all the references from the product display.
> 1 votes

---
Tags: rules, commerce
---


title: Is there node api hook in drupal 7

text:
# Question
Title: Is there node api hook in drupal 7
Is there still a `hook_nodeapi` in drupal 7 or do i have to try `hook_node_load` hook for appending some content to node?

# Answer
> 4 votes
`hook_nodeapi()` is split into multiple hooks in Drupal 7, so you should use hook\_node\_load()

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


# Question
Title: Is there a site as good as Smashing Magazine geared towards drupal rather than wordpress?
As the title says, I'd like to find a site that is similar to the Smashing Magazine site that caters more to drupal users.

I love this site. I have yet to find a Drupal centered one that keeps me checking the feed so often for quality content.

I'll try any suggestion.

# Answer
I check Planet Drupal often. I've set it up on Flipboard on the iPad. You can also setup an RSS reader to find you Drupal content.
> 1 votes

# Answer
Well I have been trying to make such a website www.techiestuffs.com, but since I haven't found authors to write drupal based content I have scattered the site with categories I am comfortable with. If I find authors I will work with them.
> 1 votes

---
Tags: nodes
---


# Question
Title: How I create table View of webform submissions
I want to view webform submissions in table view. I created a view of webform submissions but it shows a link for the data submitted. I dont want to use link, I want only simple table view.

# Answer
You can create your own tables of Webform submissions with Views...

1. Make a new view of type 'Webform submissions'
2. Add a page, set the path and set the Style to 'Table'.
3. Add the fields you want, sort and filter as needed.

If you want submissions filtered by the node (Webform) they were submitted against, you should add a relationship for 'Webform submissions: Node' so you can pass the Node ID to the view -- remember to include the argument placeholder in your path for the nid (e.g. `submissions/%`)

*(Of course, this provides a tabular view of Webform submissions with the fields you choose as outlined in your question -- the existing view of submissions will still be on the tab for that Webform node... Changing that is a different question.)*
> 3 votes

# Answer
In default webform results are arranged in Table format.If you wish to show webform results to users then just enable permissions in people\>permission.
> 2 votes

---
Tags: views, 6, webforms
---


# Question
Title: Is there a module that makes Taxonomy tags like they are on stackexchange sites?
I'm Looking for a module that makes my free tagging taxonomy tags like they are on this or any other stack exchange site. I would like for when a user puts their cursor in the Autocomplete tag field, it displays a list of suggested tags for them to select. Also, I would like to incorporate tag aliases/synonyms so multiple tags relate to one another. I'm running Drupal 7 and I figure I could use permissions on my taxonomy set to allow people to create new tags based on their role. Does anyone know of a module or way to get this functionality? Thanks.

# Answer
> 3 votes
Active tags will give you the look & feel of stackexchange's tags but won't provide the nice description and suggestion list that SE sites have.

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


# Question
Title: How do I post a node to PayPal after node insert/update?
I have an option in my node to "upgrade".

If the user selects this option either when creating a new node or updating an existing node, I would like to post the node data (which includes some Paypal html elements) to Paypal so that it can process a payment.

The node should be inserted/saved regardless of the payment result. I need to specify via Paypal what the return URL is and with inserting node's I wont know that until after the node is inserted.

Is there a way to post to 2 places? I know that doesnt really make sense but im just looking for a solution.

# Answer
> 1 votes
If you want to send this information and get and `nid`, the best place to do this is in:

---
Tags: 7, payment-gateways
---


# Question
Title: Media/file repository - asset autocomplete widget?
Does anyone know of a module which would install an autocomplete widget for file and image fields on admin-side?

The purpose of it would be to allow admin/editor to re-use a reference to an already uploaded file by typing its name. The widget would then auto-complete the path/reference based on the actual contents of directory where the asset is supposed to be uploaded. Otherwise, the file would have to be uploaded repeatedly.

Or, to rephrase the question: how do you folks solve such a media repository issue?

# Answer
You can use Media module to store Images in a specific location,but you cant get the auto complete function with this module but you can select and reuse the old photos from the Image location.

The another good thing using this module is it is already integrated with the Ckeditor.
> 1 votes

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


title: Modify create content flow

text:
# Question
Title: Modify create content flow
I want to do the following:

1. filling content (create new content)
2. after pressing the save button (submit) will display the contents of the data has been filled,and other additional information required
3. select save to submit the content, or cancel it

How do I show data that has been filled as a confirmation before the data saved?

I have tried using the Form API to change the flow of the process (\_form\_alter) but no success. And i can't find the examples to altering the content type.

# Answer
> 1 votes
Provide the roles to user to make any content and after save the content it will show with restriction. Or you can make custom module for that.

---
Tags: forms
---


title: Migrating to Pressflow

text:
# Question
Title: Migrating to Pressflow
I am currently using drupal 7 for my site. I recently read about Pressflow for drupal and it seems to provide better performance compared to the regular drupal 7 version. I have a quite a few custom modules and if I have to migrate to pressflow later, do I have to modify the modules to support pressflow? Also, are there are any issues on migrating from drupal 7 to pressflow?

# Answer
> 5 votes
Pressflow 7 doesn't seem to contain any relevant performance improvements at this time.

Below is a diff from 7.10 to the pressflow/master branch on github, where pressflow is now maintained. (https://github.com/pressflow/7)

```
$ git diff -R pressflow/master
diff --git b/includes/bootstrap.inc a/includes/bootstrap.inc
index d63a59b..e5e7ab7 100644
--- b/includes/bootstrap.inc
+++ a/includes/bootstrap.inc
@@ -728,6 +728,22 @@ function drupal_settings_initialize() {
   }
   $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';

+  // Load environmental config, if present.
+  if (isset($_SERVER['PRESSFLOW_SETTINGS'])) {
+    $pressflow_settings = json_decode($_SERVER['PRESSFLOW_SETTINGS'], TRUE);
+    foreach ($pressflow_settings as $key => $value) {
+      // One level of depth should be enough for $conf and $database.
+      if ($key == 'conf') {
+        foreach($value as $conf_key => $conf_value) {
+          $conf[$conf_key] = $conf_value;
+        }
+      }
+      else {
+        $$key = $value;
+      }
+    }
+  }
+
   if (isset($base_url)) {
     // Parse fixed base URL from settings.php.
     $parts = parse_url($base_url);
@@ -2329,6 +2345,17 @@ function _drupal_bootstrap_database() {
 function _drupal_bootstrap_variables() {
   global $conf;

+  // Pressflow Smart Start
+  if (!empty($GLOBALS['databases']) && variable_get('pressflow_smart_start', FALSE)) {
+    try {
+      $result = db_query('SELECT s.name FROM {system} s WHERE s.name = :name', array(':name' => 'system'));
+    } catch (Exception $e) {
+      // Redirect to the installer if an essential table is missing.
+      include_once DRUPAL_ROOT . '/includes/install.inc';
+      install_goto('install.php');
+    }
+  }
+
   // Initialize the lock system.
   require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
   lock_initialize();
diff --git b/sites/default/default.settings.php a/sites/default/default.settings.php
index f8894aa..08fc81b 100644
--- b/sites/default/default.settings.php
+++ a/sites/default/default.settings.php
@@ -487,3 +487,13 @@ $conf['404_fast_html'] = '<html xmlns="http://www.w3.org/1999/xhtml"><head><titl
  * Remove the leading hash signs to disable.
  */
 # $conf['allow_authorize_operations'] = FALSE;
+
+/**
+ * Smart start:
+ *
+ * If you would prefer to be redirected to the installation system when a
+ * valid settings.php file is present but no tables are installed, remove
+ * the leading hash sign below.
+ */
+# $conf['pressflow_smart_start'] = TRUE;

```

As this shows, there are only two actual changes, one allows to set $conf values from the environment and the other is a safety check when Drupal isn't installed properly. Both are probably only really relevant for their Pantheon hosting environment.

So, while the interview posted by @wiim is nice, it's two years old and nothing has really happened. So, you can IMHO save yourself the hassle of switching for *now* (of course, this might change).

# Answer
> 3 votes
Pressflow is 100% API compatible with drupal core, this means your custom modules will continue to function as long as they meet drupal's coding standards

Also an interesting read, to ensure you are making an in-formed decision as to why you are choosing pressflow Pressflow 7: Continuing to Push Performance and Scalability in Drupal Pressflow 7 will by no means magically make your site faster ;)

---
Tags: 7, migrations
---


title: Do I need RDF enabled on a normal site?

text:
# Question
Title: Do I need RDF enabled on a normal site?
When you install Drupal 7, you notice that RDF is enabled by default. Now... I have a website called 7 Tutorials and I am wondering if RDF is useful, considering the content shared on the website.

I read a bit about it and learned that the "Resource Description Framework" is the standard for encoding metadata and other knowledge on the Semantic Web.

I admit I did not research much about it and I am not sure I fully understand its use cases but, it sounds to me RDF would be useful only to websites which share data in a structured way. Is this correct? Would I have anything to gain by enabling RDF on my website? (e.g. help with SEO).

# Answer
As far as Google is concerned if your website is well structured it will be easy for crawlers to crawl your website.Morever Google Rich snippets uses RDF and it needs every site to be RDF structured if you want to enable rich snippets for your website.

Drupal 7 rich snippets and RDF

> So Unless you have any problem with RDF module enabled why you need to disable it?
> 3 votes

---
Tags: 7, rdf
---


# Question
Title: Why is form submit handler not called when calling form_set_error?
I want to know where in Drupal documentation it is listed that submit handlers are not called when form\_set\_error has been called.

I don't see it in form\_ser\_error api, nor in FAPI Quickstart guide and FAPI reference.

Looks like I'm missing some simple thing.

# Answer
> 0 votes
submit handlers are only invoked if there are no validation errors. Calling form\_set\_error() results in a validation error.

From the quickstart guide that you linked:

> 1. A submit function is called only if a submit button was present and exists in the $\_POST, and validation did not fail.

---
Tags: 6, forms
---


# Question
Title: Pager disappears when adding "GROUP BY" in the SQL query
Drupal pager disappears when I add `GROUP BY` to the query.

This code works.

```
$countSql = "SELECT  COUNT(*) FROM journal ";
$sql = "SELECT  * FROM journal";

$result = pager_query($sql, 1, 0, null, $countSql);
theme_pager(NULL, 10)

```

This code doesn't show the pager.

```
$countSql = "SELECT  COUNT(*) FROM journal ";
$sql = "SELECT  * FROM journal GROUP BY id";

$result = pager_query($sql, 1, 0, null, $countSql);
theme_pager(NULL, 10)

```

What is it wrong with the latter code?

# Answer
Your query with the `GROUP BY` is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a `GROUP BY` clause you should group all the columns without an aggregate function.

Also if you put a `GROUP BY` in your query, you should also include it in your count query. Generally a brutal way to make the count query is to put it this way:

```
$sql = "SELECT  * FROM journal";
$countSql = "SELECT  COUNT(*) FROM ($sql) ";

```

Try to modify your queries and amend your question with further precisions.
> 4 votes

# Answer
I need distinct journals, and their IDs must be in article table; the article table can have multiple journal IDs, and I need two article columns.

```
SELECT  j.nid AS journal_nid, j.title AS journal_title, j.id AS journal_id, a.is_epub, a.nid AS article_nid, j.image_file_name
FROM journal j
INNER JOIN article a ON j.id = a.journal_id ". $condition." GROUP BY j.id ORDER BY j.title ASC

```

I modified my query, and the pager appears.

```
SELECT  j.id AS journal_id, j.nid AS journal_nid, j.title AS journal_title, j.image_file_name,
(select max(nid) from article where journal_id = j.id) AS article_nid,
(select max(is_epub) from article where journal_id = j.id) is_epub
FROM journal j
WHERE j.id IN (SELECT journal_id FROM article)

```
> 1 votes

---
Tags: theming, paging
---


# Question
Title: Programatically upload/link images and attatch to Ubercart's product node?
One of the things my Ubercart module needs to be able to do is programatically upload or link (this being preferred as it means I don't have to mirror it) an image and attach to Ubercart's product node. The user will give me some information, and my module will fill in the name, description, and product image. The product image is a big hurdle which I have no idea how to conquer.

The core Ubercart module `product` has a dependency on Drupal's core `Image` module, which is where I'm assuming is handling all the images. I thought I could learn how to do it by looking at the `product` module's code, but I'm having trouble wading through and understanding the thousands of lines of code. I'm not even sure of any other module that does something similar to what I'm doing, so I'm out of example code.

Does anyone know of a way to accomplish what I'm wanting to accomplish?

# Answer
Ubercart already has the option of a predefined cck imagedfield, where do you plan on getting the correct image programatically? I remember using a default imagefield image before in the field settings.

Have a search for creating ubercart products programatically, its a fairly common thing as people import products from other dbs and excel files etc.

Here is a start, it all depends on where your data is coming from;

```
<?php
function MYMODULE_createnode() {

global $user;
if (isset(

$_POST['values_from_form']))
  {
    $values['nid'] = intval(check_plain($_POST['nid']));
    $values['title'] = check_plain($_POST['title']);
    $values['type'] = 'product'; //uc node content type
    $values['body'] = $_POST['body'];
    $values['name'] = $user->name;
    $values['uid'] = $user->uid;
    $values['field_cck_field'][0]['value'] = $_POST['cck_field']; // Custom CCK field example for whatever it was you were wanting to do
    $values['status'] = 1;

    $node = node_submit($values);

    node_save($node);

    }
}
?>

```
> 1 votes

---
Tags: ubercart, media
---


title: User Webform as user registartion pages

text:
# Question
Title: User Webform as user registartion pages
I have 3 pages in my website where user can either register register of login. On each page the amount of data required for registration is different. Problem is that i need to use webforms for the user registration pages and create 3 different forms with different level of data being asked. And when the user enters his email ID in the registration form, if he has already submitted the form once, his previous data should be filled up in the user registration for editing purpose.

# Answer
Webform isn't the right choice here because Webforms are designed for multiple submissions against a template. You seem to want to extend/create user profiles and include these fields in registration. I recommend you use the Profile 2 module instead.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How can I stop the cron tasks from being triggered by site visitors?
My site's logs show that cron is triggered if someone visits the website. This is slowing down the load time for the first visit.

The cron is configured to run each 3 hours here: *Administration » Configuration » System » Cron*.

How can I run the cron scheduled and not triggered by visitors?

# Answer
You should start by reading the Drupal handbook pages about cron to get background and commands to run.

* If you have shell/SSH access to the (Linux) server, you can run use run `crontab -u www-data -e` to edit the cron table for the web user. You should be able to use the details in the above link to set up proper cron runs as often as you'd like.
* If you're on shared hosting without shell access, you'll need to use your web host's control panel (CPanel, Plesk etc.) to log in and add a 'Scheduled Task'. This provides as web interface to the cron tabs, so the same settings will be needed.
* If these are not available you'll need to ask your hosting company to help, but there are also free and paid services you can use call the `cron.php` page remotely for you. See Set Cron Job for example.

Take a look like the Elysia Cron module if you want more out of cron in general -- it's got good documentation and allows you to finely control what tasks run when.

Finally, remember to disable the site running it when visitors arrive at *Administration » Configuration » System » Cron* when you've managed to set this up.
> 10 votes

# Answer
Drupal 7 incorporated in its modules the code that were in Poormanscron, whose purpose is exactly to run Drupal cron tasks on a site where it is not possible to set cron tasks, when a user visits your site, and every X hours (as set in the page you saw).

If you want to avoid that behavior, you just need to set "Run cron every" to "Never"; contrary to what it could seem, that just influences what happens when users visit your site.<sup>\[1\]</sup> You can still run Drupal cron tasks from outside Drupal, remembering that in Drupal 7 cron.php needs to be invoked, from outside Drupal, passing the value shown in "Administration \> Reports \> Status report."

**\[1\]:** In fact, neither cron.php, nor drupal\_cron\_run() checks the Drupal variable used in that settings page. The only Drupal variables used are:

* "cron\_key" that contains the cron key used to avoid the Drupal cron tasks are ran from unauthorized users
* "maintenance\_mode" that is set to `TRUE` when the site is in maintenance mode
* "cron\_last" that contains the timestamp of when cron tasks were ran last time
> 13 votes

---
Tags: 7, performance, cron
---


# Question
Title: Drupal template files are not recognized
### sites/all/modules/dc\_wiwo

```
function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'template' => 'wiwo',
    ),
  );
}

function dc_wiwo_page() {
  return theme('dc_wiwo_page', array('tweets' => array()));
}

```

If I put a template file in sites/all/modules/dc\_wiwo/wiwo.tpl.php it works, but if I put a file in sites/all/themes/media/wiwo.tpl.php it doesn't work. I thought you could override templates in the theme. Is there a setting I have to change to allow this?

# Answer
> 0 votes
You should keep default template in module's directory in order to be able to override it in theme.

# Answer
> 1 votes
By default, the template file is expected to be in the same directory containing the module or the theme which defines the theme function. To use a different path, in the hook\_theme() implementation you need to use the *path* property, which is defined as:

> * path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.

So, in your case the code should be similar to the following one, since you are using a theme.

```
function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'path' => drupal_get_path('theme', 'dc_wiwo') . '/media';
      'template' => 'wiwo',
    ),
  );
}

```

For a module, the code would not be much different.

```
function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'path' => drupal_get_path('module', 'dc_wiwo') . '/media';
      'template' => 'wiwo',
    ),
  );
}

```

---
Tags: 7, theming
---


# Question
Title: Storing permanent value in Form while in validation handler
We can store a permanent value in `$form_state` in the submission handler, which will be retained against form errors, but I want to know how we can do it while in the validation handler, where I show an error using `form_set_error()`.

In short, I want to show an error in validation with the message "Press submit again to confirm". In this way, if the same form is submitted again it would skip the validation handler.

I can't do it in the submission handler, since it clears the values in the form.

`form_set_value()` is not able to retain a value.

**EDIT (on 28th Dec)**

I've found that $form\_state\['storage'\] is works in validator also only if form\_state\['rebuild\] is set to true. Infact this is how we use in submit handler. And if I call form\_set\_error in the validator form\_state\['rebuild\] is simply ignored even if it is set and the storage value is not retained.

# Answer
> 4 votes
`$form_state['storage']` is probably what you're looking for. I've used it on multi-step forms myself to preserve necessary data that I need during various stages of the form processing. As an example you can define a storage variable like this:

```
$form_state['storage']['mykey'] = 'myval';

```

Edit: Considering the additional information you provided it is indeed not quite as simple in your specific case. Setting `$form_state['rebuild'] = TRUE;` in the form validation handler also means that the user set form values will be lost. So what I think you could do is the following:

In the form validation handler function:

```
if (!isset($form_state['storage']['mykey'])) {
  $form_state['storage']['mykey'] = 'myval';
  // Save all the user set form values.
  foreach ($form_state['values'] as $key => $val) {
    // If you want to skip some values do it here.
    $form_state['storage']['values'][$key] = $val;
  }
  $form_state['rebuild'] = TRUE;
  drupal_set_message('Press submit again to confirm');
}

```

In your form builder function use the stored values as defaults. Example:

```
$form['key_1'] = array(
    '#type' => 'radios',
    '#title' => t('Title'),
    '#options' => array(0,1,2),
    '#default_value' => $form_state['storage']['values']['key_1'],
);

```

Not sure how well the example code fits your needs, but it should get you started or at least give further ideas/options to try out.

# Answer
> 1 votes
The Unique field module does something similar with respect to overriding form validation. Grab its code and take a look to see if you can modify it to your needs.

---
Tags: 6, forms
---


# Question
Title: Updating Drupal modules via git on remote server
Here is my Drupal workflow for updating modules.

1. I update modules on my local dev and test.
2. Run update via drush if needed.
3. Commit and push to github.
4. Pull these new updates from Github on remote server to live site.
5. run update via drush.

However, I was thinking of making a "modules-update" branch, pushing to that from local dev, pulling that branch to my live site and merge with my master branch later if all went well. If all does not go well for some reason on the live site, then I could simply pull from my master branch that had the older versions and do a restore of the DB from the backup and restore module if need be.

So my questions is, I am looking for feedback if this seems like a sound practice or are there better ways to do this? I am fairly new to Git so I am guessing there might perhaps be a better way than this.

# Answer
In my opinion the workflow you mentioned look good. You just need to make sure you have a latest database backup in case you need to revert back. Have you looked into https://getpantheon.com/ it is free for drupal development. Request an invitation code at https://getpantheon.com/request-code Best thing about pantheon is it provides dev test and live sites, daily, weekly, monthly and on demand backups. Push code from dev to test and live, Pull database and files from live to test and dev with just push of a button.
> 1 votes

---
Tags: version-control
---


# Question
Title: How to redirect all URLs to a new domain
I'm shutting down an old site and want to redirect all URLs to the homepage of a new domain. Is there a module or quick php snippet that can do just that?

# Answer
The problem with trying to do it with PHP or a module is that PHP doesn't handle every request; for example, if someone deep linked to a file, no PHP solution would help.

So the easiest (and most complete) way to do this is actually with Apache (or whatever web server you happen to be using):

```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^old\.example\.com$
RewriteRule ^(.*)$ http://new.example.com/ [R=301,L]

```

You can do this in the host configuration file or the `.htaccess` file: assuming the old site is a Drupal site, you'll want to place everything except the first line immediately after `RewriteEngine On` (around line 58 in Drupal 7.x).
> 4 votes

---
Tags: 7, redirection
---


# Question
Title: Why does Git in Cygwin complain about info/refs not being found?
I am learning to use git with Drupal. I'm using Cywgin (Windows-based Linux command line), and trying to follow Practicing patches. The documentation tells me to use the command:

```
git clone --branch master http://git.drupal.org/project/current_content.git

```

However, I appear to have an old version of Git, because it tells me that "--branch" is unknown. The Git troubleshoot page explains a work around:

```
git clone [project_url] [directory]
cd [directory]
git checkout --track origin/[existing_branch_name] -b [tracking_branch_name]

```

However, the first line tells me:

```
fatal: http://git.drupal.org/project/current_posts/current_posts.git/info/refs
 not found: did you run git update-server-info on the server?

```

Any suggestions on what I am doing wrong? I've got the last version of git via Cygwin.

# Answer
From the error, it looks like your `git clone` line was incorrect (it complains about `current_posts`—which isn't a project—instead of `current_content`—which is). Try:

```
git clone http://git.drupal.org/project/current_content.git

```

You can also do:

```
git clone git@git.drupal.org:/project/current_content.git

```

Note that the `master` branch is the default branch: you don't need to specify it in the clone or afterwards: it'll automatically check it out.
> 4 votes

---
Tags: version-control
---


title: Why is "403 Forbidden" used?

text:
# Question
Title: Why is "403 Forbidden" used?
RFC 2616, the document that defines HTTP/1.1, lays out the definitions of all the HTTP status codes, including *403 Forbidden*.

> The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

That's not how Drupal uses it: Depending on the case, it either uses it for the default condition in callbacks (e.g. `shortcut_link_add_inline()`), essentially making it equivalent to *Drupal doesn't understand the request*, or it is used to inform the client it doesn't have access to the page.

In the case of the former (the request isn't understood), the more appropriate status code should be *400 Bad Request*.

> The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

In the latter case (the client does not have access to the page due to permissions), it should either be *401 Unauthorized*, if Drupal wants to give away it's just a permission problem.

> The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.

Drupal could also use 404 File Not Found, if it doesn't want to make public it's a permission problem.

> The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. **This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.**

I realize it's been like this for many years, but what was the original rationale for making *403 Forbidden* the only response Drupal sends when it gets a request it doesn't like?

# Answer
As stated in your quote, *401 Unauthorized* must be combined with HTTP authentication, which is not what Drupal is using, so this is not an option.

IMO, 403 is a perfectly valid response because clients must not repeat their request, but eventually fill out a login form which will result in a different request.

Special cases like the short link function you posted aren't so clear. I guess the reason for using access denied there is that it's checking the token which is a kind of authentication. It could just as well use 400 or 404. I guess the reason for using 403 instead of 400 is simply because there is no helper function for returning a 400.

There also has been a discussion regarding the Privatemsg module (that I'm maintaing) whether trying a private message as anonymous user should result in a 403 or a 404 (for privacy reasons). It used to be 404 but has been changed to 403 because users often click on direct links in mail notifications and a 403 page can easily be turned into a login form (as there is a module that does this out of the box). So this is related to the last two sentences of the 403 description.
> 6 votes

---
Tags: 7
---


# Question
Title: What is the alternative to drupal_realpath()?
I use `drupal_realpath()` to do includes for some code samples I have:

```
 require_once(drupal_realpath('public://php_includes/functions.php'));

```

This gives the real path `C:\www\sites\mysite\files\php_includes\functions.php`.
What is the command to get the HTTP path `http://mysite.com/sites/files/php_includes/functions.php`?

The api documentation says "RealPath is deprecated"... if it's deprecated, what is supposed to replace it to get the same path (either `C:\...` or `http://...`)?

# Answer
> 6 votes
To get the HTTP path of a file, you need to use `file_create_url($uri)`.

```
file_create_url('public://php_includes/functions.php');

```

This will output `http://mysite.com/sites/files/php_includes/functions.php`.

Regarding the fact that `drupal_realpath()` is deprecated, I think it's to warn developers to avoid relying on file system path and instead use wrappers.

---
Tags: 7
---


# Question
Title: How can I conditionally add a parameterized variable to my themes based on URL?
I'd like to do something like the following:

If a user goes to `node/15`, my `node.tpl.php` file is used, as normal, to generate HTML.

If a user goes to `node/15/animal/7`, then my `node.tpl.php` is still used, as expected, but it has a variable in scope called `$animal`, set to the value that I would get from loading an animal.

So, the URL schema would look something like the following: `node/%node/animal/%animal`. I want this behavior so that if the user goes to node/15, that's fine, but if they attempt to go to node/15/animal/100 and animal 100 does not exist, the user gets a 404.

The problem I'm running into is that this requires functionality from several distinct areas of Drupal, and I don't know how to make them work together. Adding a custom URL schema would be done in `hook_menu()`, which requires a page callback. Using anything other than `node_page_view` would cause the node not to be rendered as normal. BUT, adding a variable to the template's scope would require implementing `moduleName_preprocess_hook()`, which I only want to conditionally fire when the user hits this specific URL schema.

I could of course manually check the contents of the requested URL myself, perhaps during `moduleName_preprocess_hook`, but this seems a little too low-level. Surely Drupal has some sort of way to accomodate what I'm trying to do?

# Answer
You're on the right track: it'll be much more straightforward to stick this in a module where you have access to the menu system, and the most straightforward way to expose the data to the node template is through preprocess functions.

First, create an implementation of `hook_menu()`:

```
function example_menu() {
  // Only two things specific to your case is page callback
  // and page arguments. Other options taken from node_menu(): customize as
  // you see fit.
  $items['node/%node/animal/%'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'example_animal_view',
    'page arguments' => array(1, 3), // Pass node object and animal ID
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  return $items;
}

```

Then create your callback, which will display the node as normal (including using the node template) if your animal check succeeds:

```
function example_animal_view($node, $animal) {
  if (animal_exists($animal)) { // Replace with your own check
    return node_page_view($node);
  }
  // Return a 404 if the check failed
  return MENU_NOT_FOUND;
}

```

Now, to expose the animal ID to `node.tpl.php`; you could either add it to the node object via the Field API, but in this case—since you're just using it for theming purposes—it's much easier to just add it to the template variables in a preprocess function:

```
function example_preprocess_node(&$variables) {
  if (arg(2) == 'animal') {
    $variables['animal'] = arg(3);
  }
}

```

You could do this last part in your theme, but I'd keep it in the custom module to encapsulate the functionality so it's available in every theme.

Finally, in `node.tpl.php`, just reference `$animal`.
> 1 votes

---
Tags: 7, routes, hooks, theming, uri
---


title: Template suggestion being ignored

text:
# Question
Title: Template suggestion being ignored
I have a parent theme as a basis for a multisite installation. Right now, I'm working on a child theme which has to have some custom templates. Here's my preprocess function in my child theme:

```
$orig = $vars['theme_hook_suggestions'];
$manual = array('page__node', 'page__node__%', 'page__node__96', 'page__gallery', 'page__drisco_gallery');

dpm(array_diff($manual, $orig));
dpm($manual);
dpm($orig);
$vars['theme_hook_suggestions'] = $manual; // Loads my page--gallery.tpl.php template and works as expected.
$vars['theme_hook_suggestions'] = $orig; // Ignores my template, just uses page.tpl.php

```

The template only loads if I create the array by hand, even though it's apparently identical to the one already there. Here is what `dpm()` outputs:

```
... (Array, 0 elements)

... (Array, 5 elements)
    0 (String, 10 characters ) page__node
    1 (String, 13 characters ) page__node__%
    2 (String, 14 characters ) page__node__96
    3 (String, 13 characters ) page__gallery
    4 (String, 20 characters ) page__drisco_gallery

... (Array, 5 elements)
    0 (String, 10 characters ) page__node
    1 (String, 13 characters ) page__node__%
    2 (String, 14 characters ) page__node__96
    3 (String, 13 characters ) page__gallery
    4 (String, 20 characters ) page__drisco_gallery

```

Does anyone have a clue of what I'm doing wrong?

# Answer
> 2 votes
In order to load the template based on the content type, inside the template.php file of your theme you need the following code:

```
function your_theme_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

```

if the content type is "mycontent," create the page--mycontent.tpl.php file.

For template files that are based on the page path, create the page--front.tpl.php, page--node--7.tpl.php, page--node--58.tpl.php or page--node--nodeid.tpl.php files. Please note that between the page and node templates are different from what they used to be in drupal 6.

---
Tags: 7, theming
---


# Question
Title: Theme overrides for custom hook_theme() in Drupal 7
I have a custom D7 module which defines it's own `hook_theme()` which defines a few theme functions, of which they define their own template, for example:

```
function foo_theme($existing, $type, $theme, $path) {
    $items = array(
        'post_foot' => array(
            'template' => 'templates/post_foot',
            'variables' => array('node' => (object)array())
        )
    );
    return $items;
}

```

As you can see, it defines it's own template, which is located in the foo module, in this specific case `sites/all/modules/custom/foo/templates/post_foot.tpl.php`

I'd like to be able to define my own `post_foot.tpl.php` in my theme, and use foo's tpl as a fallback.

Does this happen automagically? Do I need to expand my `hook_theme()` to include overrides?

# Answer
> 2 votes
This should happen automatically. Most core modules define theme hooks which you wouldn't think twice about overriding in your theme. Take a look at node\_theme for example http://api.drupal.org/api/drupal/modules--node--node.module/function/node\_theme/7.

The devel themer module should help you out with such things. Needs some work for D7 but should help.

# Answer
> 2 votes
This happens automagically UNLESS your theme hook has a name that is different from the template file, after hyphens have been replaced with underscores. In that case the auto-discovery will fail.

The auto-discovery is based on the name of your module-defined theme hook, not on your module template name. This was a gotcha for me.

In module:

theme hook: foo\_theme\_hook

template: theme-hook.tpl.php

In theme

template: theme-hook.tpl.php

= FAIL

To fix, in the above example, either rename theme hook to be "theme\_hook" instead of "foo\_theme\_hook" or rename the overriding template file to be "foo-theme-hook.tpl.php"

---
Tags: 7, theming, hooks
---


title: Drupal 7 is ready for big sites?

text:
# Question
Title: Drupal 7 is ready for big sites?
I know to right now Drupal 7 is stable since almost a year but the truth is Drupal needs third party modules for satisfy the requirements of almost any site

Yesterday i tried jump to drupal 7 but the first thing to i see is to many of modules are betas, releases candidates and a lot haven't a version for D7.

and many of this modules are essentials, modules like Ctools, panels, references, context, all of these modules are pretty useful and none of them have a stable version for drupal 7

So my question is, Drupal 7 is ready for a bigger site than a blog? how many of you use drupal 7 with unstable modules for a client's sites?

How risky is use non stable modules in drupal 7?

# Answer
> Q: "How risky is use non stable modules in Drupal 7?"
>
> A: "Depends."

Without wanting to be obtuse, in late 2011 this is a question only you can answer, based on your abilities, needs and experience.

The simple answer is: Betas are usually fine, Alphas should usually be avoided, RCs are almost certainly OK.

If you're happy to hit a bug and help fix it or apply patches, you'll be mostly fine and able to really help the Drupal community. If not, the risk for you is higher and could become a show-stopper.

If you're using one of the 'biggies' with tens of thousands of users (CTools, Panels, Views etc) you can probably use alphas/betas without hitting many major issues -- or you'll be one of thousands with the same problem which means it'll get fixed quicker... But if you're using less common (but still complex) modules, or it's critical you have complete reliability in your site, then you'll need to think twice - and maybe stick with D6 for a while.

A safer approach if you're worried and don't have the expertise to get your hands dirty in code or patches is probably: use Drupal 6 but choose your modules carefully so there's always a D7 upgrade path. Upgrade when you're happy it's right for you.

Ultimately you might *have* to use Drupal 7 because it provides certain features you cannot get in D6.

To close I would say that, for the most part, Drupal 7 and its ecosystem of modules is ready for most people/sites/projects. But things are changing by the day, so if you don't feel comfortable now you might in do a month or two.

Do your research and if you have doubts or hit snags, Drupal 6 is generally still an excellent choice and will be for many more months.

Good luck!
> 14 votes

# Answer
We have recently launched a large government site re-written using drupal 7 (\> 3000 nodes, high traffic). Having gone through this development, we had to learn a few things:

* due to views only recently being made stable, a lot of modules that depend on views are still unstable. Even so, the more popular ones work okay
* we had to port some modules that we use a lot, that had no D7 branch. An example was Apache Solr Panels
* features in D7 was shaky for a while, but now is fairly stable

All in all though, Drupal 7 has awesome new features, a whole new database abstraction layer, a wicked states API, image handling in core. As time goes on contrib will keep getting better and better for D7, whilst you will find shortly I would imagine that none wants to make new features for D6 contrib.

If you want to check the site out, visit health.govt.nz
> 4 votes

# Answer
Absolutely, Drupal 7 is ready for big sites; even though many modules are in beta, the essential ones are stable, and you can start building with Drupal 7.

On other hand, there is no need to hurry up, since Drupal 8 will be, most probably, released between 2 years.

For your reference, read this article too.
> 1 votes

# Answer
We launched a truly huge Drupal 7 site (www.examiner.com) before Drupal 7 was *launched*. Then, it required a good number of people very, very familiar with core. Now? It's so ready and easy.
> 1 votes

---
Tags: 7
---


# Question
Title: Setting up a staging server workflow (for a relative beginner)
I'm working on a Drupal 6 project and would like to set up a simple staging/live server workflow.

I know Drupal pretty well, including the Features module, and am relatively familiar with Git; as for the server itself, I've only got FTP access. I'd be interested in hearing possible ssh-based solutions too, though.

Can anyone recommend a suitable workflow, or suggest what I should consider if I have to develop my own workflow?

# Answer
If I understand what you are asking for, that being your production server being remote, you might want to consider installing a devdesktop from acquia.com if you're using a Windoze or mac development system. Then you can use features and/or deploy to move you changes to the production system via ftp.

If you're using a \*nix development box I'd install Drupal directly and still use features and/or deploy to move things.

Worth a try -
> 0 votes

---
Tags: workflows
---


# Question
Title: How to quickly create Drupal 7 Installation profiles / Distributions
Dose anyone know how to make quickly and easy installation proflies for drupal 7? Something like this 5 easy step tutorial but for drupal 7.

# Answer
> 3 votes
This really helped me.

How to Write a Drupal 7 Installation Profile http://drupal.org/node/1022020

---
Tags: 7, distributions
---


# Question
Title: What is wrong with this code returning error
I am using this function to return metatag on front page of my drupal site

```
<?php
  if ($is_front) {
    echo "<META NAME="KEYWORDS" CONTENT="Geek community,stuffs for geeks,geek contents,tech updates,electronics stuffs,tech geeks">";
    echo "<META NAME="DESCRIPTION" CONTENT="Get articles related to Drupal,wordpress,design tips,Electronics,Web designing,Linux and Programming.Join our Tech community where you can share and get answers for your queries.">";
  }
?>

```

But it throws the following error:

> Parse error: syntax error, unexpected T\_STRING, expecting ',' or ';' in /public\_html/techiestuffs/modules/system/html.tpl.php on line 52

Anyone know what is wrong with this code ?

# Answer
> 6 votes
PHP can define a string with `'` or `"`. Whichever one you choose, you can't have those characters in the string without escaping them: `echo "need to escape any \" in this string"`

You can use this instead to avoid PHP strings altogether:

```
<?php if ($is_front): ?>
<META NAME="KEYWORDS" CONTENT="Geek community,stuffs for geeks,geek contents,tech updates,electronics stuffs,tech geeks">
<META NAME="DESCRIPTION" CONTENT="Get articles related to Drupal,wordpress,design tips,Electronics,Web designing,Linux and Programming.Join our Tech community where you can share and get answers for your queries.">
<?php endif; ?>

```

# Answer
> 2 votes
The error is caused from the fact you are using the string delimiter inside the string itself. The syntax highlighter shows you that:

```
if ($is_front) {
  echo "<meta name="keywords" content="Geek community,stuffs for geeks,geek contents,tech updates,electronics stuffs,tech geeks">";
  echo "<meta name="description" content="Get articles related to Drupal,wordpress,design tips,Electronics,Web designing,Linux and Programming.Join our Tech community where you can share and get answers for your queries.">";
}

```

It should be:

```
if ($is_front) {
  echo '<meta name="keywords" content="Geek community,stuffs for geeks,geek contents,tech updates,electronics stuffs,tech geeks">';
  echo '<meta name="description" content="Get articles related to Drupal,wordpress,design tips,Electronics,Web designing,Linux and Programming.Join our Tech community where you can share and get answers for your queries.">';
}

```

# Answer
> 2 votes
Or even better, you can do this the 'drupal' way and place the logic into a module. Or better yet, use a module that someone else has written.

If you are using drupal 6 - Nodewords: The Drupal 6 Meta Tags module Or drupal 7 - Meta tags

This way if you ever change themes, the metatags will still remain.

---
Tags: meta-tags
---


# Question
Title: How to move a field to a different region using Omega sub-theme / D7?
I used to be pretty good at theming Drupal sites, but I haven't done it much since D7. I added a custom field to my Basic content type and I want to put it in a Sidebar if it exists. What's the best way to accomplish that?

# Answer
Thank you IRC! At least two modules will help with this (quotes included are from their project pages):

* CCK Blocks:

> Since version 6.x-1.1 , the module does not hide the field in the node's content area anymore. You can do that for yourself in the display settings for your content type.
>
> CCK blocks will define a display mode named "CCK Blocks", which you can use to configure the display of fields when they are appearing as blocks.
>
> This allows you show the field both in the node's content area and in the CCK block, with different display settings.
* Display Suite:

> ... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
>
> By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.
> 1 votes

---
Tags: theming
---


title: duplicate taxonomy array being called

text:
# Question
Title: duplicate taxonomy array being called
I am working on a music site with a couple other programmers who have left.

We are using taxonomy terms or "tags" for each node, to determine the url/subdomain the node will be shown, on effectively creating different subdomains of content.

There is only one debug statement in the code, and even if there was another hiding somewhere, it does not explain why it shows two different arrays from the same taxonomy on the homepage.

I use the following code to reveal what terms are associated with the node:

```
 $terms = array();

 foreach($node->taxonomy as $term) {
   $terms[$term->name] = $term->name;
 }

 print 'debug:<pre>' . check_plain(print_r($terms , 1)) . '</pre>';

```

I get the following output:

```
    debug:
    Array
    (
        [national] => national
        [nyc] => nyc
    )
    debug:
    Array
    (
        [national] => national
        [nyc] => nyc
    )

```

Why is it showing 2 groups of arrays from the same taxonomy? The posts are only tagged once with these two tags "national" and "nyc."

Also on any nodes tagged with only "national," "washington" shows up as well in the duplicate array. I think it may be coming from another content type because when I performed a redirect on the node, using

```
unset($terms['national']);
      $value = array_shift($terms) ;
      if($region != $value) {
        $link = 'http://' . $value . '.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');
        drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);

```

it redirected to a different content type "CD of The Month." using term "washington" it should choose the other term in the first array; in the case above "nyc." and go to the same node type in this case "blog," I performed this redirect using drupal\_get\_path\_alias for other logic cases and it worked fine.

```
<pre>
debug:
Array
(
    [national] => national
)
debug:
Array
(
    [national] => national
    [washington] => washington
)
</pre>

```

The debug is called inside this function

```
function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  /*global $user, $base_url;*/
  switch ($op) {

    case 'view':

      if( (arg(1) == 0)){ }

      else {

```

The site is http://www.thedelimagazine.com.

# Answer
Is this in a hook function? It's possible your hook function is being called more times than you expect which gives you your extra debug statement.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: How can I make individual nodes fieldable?
One of the great things about the entity and field APIs is the ability to add fields to any entity and subsequently any bundle.

Is there a way, using the Field API or the Entity API, to make fieldable nodes, field instances attached to individual nodes instead of content types?

If there isn't, is there any work being done using other concepts that would achieve the same result? The closest I can think of is the Webform module, but I'm sure it's not intended to be a way to create content, and it doesn't take advantage of the field API.

# Answer
I did this by attaching entities to nodes on creation.

1. Create an entity type: I used contrib's Entity API as the framework for doing this.
2. Create a custom node content type.
3. Create an implementation of `hook_node_insert()` for your custom content type that creates a bundle for the entity type you created in step 1.

At this point, the node is technically fieldable: you can do any number of things, whether its create fields programmatically or implement some sort of UI to let users add their own fields.

There are two gotchas with this approach:

1. Since the node and entity type are two separate structures, you need to make sure the bundle you create is linked to the node: there's some promising work being done with the Relation module, but I opted for just adding a property to the entity bundle that stores the node ID (you could also store the bundle ID in the node if you wanted), then loading the bundle information on `hook_node_load()`.
2. Versioning bundles is heavy wizardry I chose not to get into: there is no API for it, and while in theory if you created a record of every change you made to the bundle it *should* work, it might possibly instead awaken the Old Gods. I opted for turning off revision support on the nodes I made fieldable this way.
> 1 votes

# Answer
You could use something like http://drupal.org/project/conditional\_fields but that's all done from a front-end point of view, which means Drupal doesn't really know about your structure.

http://drupal.org/project/properties looks interesting and may suit depending on your needs.

I had a similar issue recently and decided to split up into three separate content types instead of just one.
> 3 votes

# Answer
It's hard to say no it's not possible, as I might be missing something. But based on the data stored for fields and instances of fields, I'd say the current setup doesn't support this.

The best solution I can think off, would be to create a special field, that would allow for values of different kinds, much like you can add several images using the same field. I'm not sure if doing something like that would be a good idea, it would certainly be complex and time consuming, and probably couldn't use the code for all the fields that already have been defined.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How do I show user attributes on articles?
I added a custom field "Twitter URL" to each of my users (on the page Home » Administration » Configuration » People » Account settings). I'm trying to display this "Twitter URL" on every article that that user makes. For example, under the "Published by someusername on Wed, 12/28/2011 - 02:57" that is already on every post, I want to have the "Twitter URL" for that user right under that.

> Published by mike on Wed, 12/28/2011 - 02:57 http://twitter.com/someusername

I think I need to go into node.tlp.php and edit something, but could anyone give me a little more help?

# Answer
If you take a look at `node.tpl.php`, you'll notice there's already a variable for this type of data: `$submitted`. You could replace that variable with your own data, but to do it the Drupal way, what you want to do is modify the value of `$submitted` using a preprocess function.

In your theme, create a `template.php` file (if you don't have one already). In it, add the following function (replacing `example` with the short name of your theme):

```
function example_preprocess_node(&$variables) {
  // Linkify the URL
  $twitter_url = l('http://twitter.com/someusername', 'http://twitter.com/someusername');

  // This is the same thing as saying
  // $variables['submitted'] = $variables['submitted'] . ' ' . $twitter_url;
  $variables['submitted'] .= ' ' . $twitter_url;
}

```

Clear the cache (*Configuration* → Performance → *Clear cache*), and check your node pages again: you should see the Twitter URL appended to submitted line.

But this is of course, static: to load the user's Twitter URL, you'll need to load the field data:

```
function example_preprocess_node(&$variables) {
  // Even though there's a user object in $variables['user'], we need to
  // load a new copy because the preloaded one doesn't have have field data
  $user = user_load($variables['uid']);

  // Retrieve the data and its value for the Twitter URL field
  // Replace field_twitter_url with the short name of the field
  // found at admin/config/people/accounts/fields
  $items = field_get_items('user', $user, 'field_twitter_url');
  $field = field_view_value('user', $user, 'field_twitter_url', $items[0]);

  // Get the rendered output of the field for use in the submitted line
  $twitter_url = drupal_render($field));

  // If you wanted to get more fields, repeat the last three lines, replacing
  // field_twitter_url with the names of the other fields.

  // Linkify the URL and append it to the $submitted variable
  $variables['submitted'] .= ' ' . l($twitter_url, $twitter_url);
}

```

The Field API isn't the most intuitive or straightforward API in the world, but here's what's going on:

1. Load the user object, which contains the information about the fields attached to it.
2. Load the specific data associated with the `field_twitter_url` using `field_get_items()`.
3. Get the render array for the specific field you want to display using `field_view_value()`.
4. Get the final rendered output using `drupal_render()`.

Now, if you wanted to have the Twitter URL separate (so you can move it to where ever you want in the template), just create your own variable:

```
function example_preprocess_node(&$variables) {
   // ...
   // Do all the stuff from the previous sample function, except
   // setting $variables['submitted']
   // ...

   $variables['twitter_url'] = $twitter_url;
}

```

Now, you can add `$twitter_url` to anywhere in `node.tpl.php`. If your theme doesn't already have its own `node.tpl.php`, navigate to the `modules/node` folder, copy the `node.tpl.php` that's there to your theme folder, and clear the cache.
> 7 votes

---
Tags: nodes, users, entities
---


# Question
Title: Given a File ID (fid) how can I get the HTML that represents that fid?
I'm looking to do something like this

```
$fid = 15;
$file = (array)file_load($fid);
$content = drupal_render($file);
echo $content;

```

And specifically this fid is from the 7.x-2.x version of the media module.

# Answer
This works for me. For videos via the media module:

```
<?php
  $file = file_load($fid);
  if (strpos($file->filemime, 'video/') !== 0) {
    return;
  }
  $key = 'media_' . substr($file->filemime, 6) . '_video';
  $formatter_info = file_info_formatter_types($key);
  $content = array();
  $content['#theme'] = $key;
  $content['#uri'] = $file->uri;
  if (isset($formatter_info['default settings'])) {
    $content['#options'] = $formatter_info['default settings'];
  }

  $rendered = drupal_render($content);
  return $rendered;
?>

```

And for images; this shows you what presets are available (`#style_name`)

```
<?php
$styles = image_styles();
echo '<pre>' . print_r($styles, TRUE) . '</pre>';
?>

```

And this will render the file

```
<?php
$file = file_load($fid);
$image = image_load($file->uri);
$content = array(
  'file' => array(
    '#theme' => 'image_style',
    '#style_name' => 'large',
    '#path' => $image->source,
    '#width' => $image->info['width'],
    '#height' => $image->info['height'],
  ),
);
echo drupal_render($content);
?>

```

Note that image\_load performs I/O.

And for the reverse; given a filename get a fid.

```
<?php
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'file')
  ->propertyCondition('filename', basename($filename))
  ->execute();
foreach ($result['file'] as $values) {
  $fid = $values->fid;
  break;
}
echo $fid
?>

```

Given media embed code, get a FID.

```
<?php
$file = media_parse_to_file($embed_code);
if (empty($file->fid)) {
  return FALSE;
}
return $file->fid;
?>

```
> 16 votes

# Answer
You are misapplying `drupal_render()` in your example. `drupal_render()` holds the content to be displayed and the instructions for how to render it in an array so that all content can be modified by other modules, until the last moment before displaying. Everything is loaded in the `drupal_render()` argument `&$elements`, which is the argument for the function. `drupal_render()` does not return rendered elements from variables passed in arguments.

Look at the theme API for a series of functions that will provide HTML for various content elements including files.
> 7 votes

# Answer
The function you are probably looking for is file\_get\_content\_headers(), which sets the headers for allowing a file to be downloaded, or (if the file is a text file, or an image) to be viewed inline.

The function requires a file object as returned by file\_load\_multiple(), file\_load(), or entity\_load('file').
> 3 votes

---
Tags: 7, files, theming
---


# Question
Title: How can I create a block that shows the total items in my cart?
I'm using Ubercart ajax cart, and I want to create a static block with AJAX that only shows the total items in the cart.

How can I go about doing this? Is there a module that has this functionality?

# Answer
> 3 votes
You can test this one -

Put below code in your page (create new page content) and select input format "php" and hit preview button you will get what you want (if cart is not empty).

```
<?php
        $items = uc_cart_get_contents();

        foreach($items as $item){
            while(list($key,$value) = each($item)){
                if($key == 'qty')$qty = $value;
                if($key == 'price')$price = $value;
            }
            $total_qty += $qty;
            $total_price += $qty*$price;
       }
       echo 'Total Quantity : '.$total_qty.' Total Price : '.uc_currency_format($total_price);
    ?>

```

---
Tags: ajax, ubercart
---


# Question
Title: How can I create a new user—with Profile 2 fields—programmatically?
I am writing a module where I need to create a new user and save his profile fields using Profile 2.

This is the code I'm using, but it's not working:

```
$edit = array(
  'name' => $submission->data[1]['value'][0],
  'pass' => user_password(),
  'mail' => $email,
  'init' => $email,
  'status' => 1,
  'roles' => $role_id,
  'profile_first_name' => $submission->data[1]['value'][0],
  'profile_surname' => 'ag',
  'profile_email' => $email,
  'access' => REQUEST_TIME,
);

$new_user = user_save(drupal_anonymous_user(), $edit/*,'customer_profile'*/);

```

What am I doing wrong?

# Answer
> 3 votes
I load the profile object:

```
$profile = profile2_by_uid_load($user->uid, '<role type here>');

```

Then I edit the $profile object.

I have a Rules component that saves the profile object. I forget why I have the rule but I remember that it requires quite a bit of code and database queries to get it right.

I set the Rules component to take the $profile object as an argument / parameter and invoke it like this.

```
    rules_invoke_component('rules_machine_name_this_is_the_component_url_too', $profile);

```

---
Tags: 7, users
---