# Question
Title: hide certain fields on the edit form of content profile
I would like to hide certain CCK fields on the edit form of the user's content profile. Showing them without editing is done by a custom page. The problem is that if the user edits his content profile node all fields are displayed.

Already tried these:

* field permissions module
* content permissions module
* profile permissions module

but no one worked as expected..

do you have any suggestions what to do?

# Answer
I'm not familiar with content profile and it suprises me that there's not an option to hide edit fields. But if you are comfortable with a little coding, a common way would be to create a small module that implements `hook_form_alter()` along these lines:

```
/**
 * Implements hook_form_FORM_ID_alter()
 *
 * @todo Double-check the form name is profile_node_form.
 */
function mymodule_form_profile_node_form_alter(&$form, &$form_state) {
  // Hide the my_field field on the edit form.
  $form['my_field']['#access'] = FALSE;
}

```
> 1 votes

# Answer
Content permission can be quite tedious, because once it's installed you have to configure every single CCK field's permission both for view and edit. While you're connected as the admin you will always see everything but you have to test this with a normal user.

However if you just want to hide your field you can do this in several ways.
> 2 votes

# Answer
You can try http://drupal.org/project/computed\_field Although this requires some php, but it has no field on the node edit form...
> 0 votes

---
Tags: entities, users
---


# Question
Title: How to make a block visible only to one page
I have made a custom block and i want to make it visible only to pages that follow this pattern: user/\[user-id\]/galleries.

Is there a way to do it?

# Answer
> 11 votes
There are Visibility settings for blocks in Drupal. One of options is "Show block on specific pages". Select "Only the listed pages" and input `user/*/galleries`

# Answer
> 1 votes
In the *Page specific visibility settings*, select *Show if the following PHP code returns TRUE (PHP-mode, experts only)* and enter

```
return arg(0) === 'user'
    && is_numeric(arg(1))
    && arg(2) === 'galleries'
    && arg(3) === null;

```

in the *Pages* text input field. Skip the `&& arg(3) === null` part if you also want to display the block on pages further down in the hierarchy (e.g. on `user/[user-id]/galleries/private`).

---
Tags: blocks
---


title: PHP 5.2 or 5.3 for Drupal 6.22?

text:
# Question
Title: PHP 5.2 or 5.3 for Drupal 6.22?
I have noticed that PHP 5.2 is officially recommended for Drupal 5 and 6. But as the 'System Requirement' page needs update, I am wondering what would be the anticipated problems using Drupal 5.3.

I have been using PHP 5.3.2 + FPM on a Drupal 6.22 site, and have some JavaScript issues with the Voting UP/Down and Poll modules. Is it possible that I can resolve these by downgrading PHP to 5.2?

# Answer
> 6 votes
Drupal 6.22 is compatible with PHP 5.3, but some contributed modules may not support 5.3. That said, I have been developing D6 sites on 5.3 for more than a year without any problems.

Usually, the PHP version is not the cause of JS problems, so I would start to look for the solution elsewhere (Firebug?).

---
Tags: 6
---


# Question
Title: Lack of permissions on sites/default/files
I currently manage a Drupal install on a shared university computer (i.e. I don't have root access to the box), but the sites/default/files directory was created with all permissions and ownership set to a unknown user (as is shown below), therefore I have absolutely no way to delete or change anything in this folder without using the Drupal interface or contacting the sysadmin.

I believe the owner of these files is the webserver's user (which is on another box). Is there any way to change the uploaded files permissions/owner within Drupal (or at least delete/chown this folder)?

```
myself@sparta:~/public_html/drupal/sites/default/files$ ls -la
total 252
drwxrwxr-x 4     48        48   4096 Set  3 11:43 .
dr-xr-xr-x 3 myself  students   4096 Set  2 12:07 ..
-rw-r--r-- 1     48        48 227057 Set  3 11:43 Estatuto.pdf
-rw-rw-r-- 1     48        48     93 Set  2 12:30 .htaccess
drwxr-xr-x 2     48        48   4096 Set  3 11:25 imagefield_thumbs
drwxrwxr-x 2     48        48   4096 Set  3 10:47 languages
-rw-rw-r-- 1     48        48   2666 Set  3 11:25 posse.jpg

```

Thanks!

# Answer
You can install the devel module and visit /devel/php on your site. This will give you a place to run ad-hoc PHP from where you could run chown() or something similar on the files in question.

I'm sure it doesn't need to be said but be careful, the last thing you want to do is make a mistake with permissions!
> 1 votes

# Answer
So when you say you manage the installation, presumably you have ftp access to it. If so, you can use something like Filezilla to set permissions for files within the root drupal folder. You need ftp access to install modules also, but you are normally walled within the drupal folders. Ftp permissions changes will depend on the privileges of the Ftp user login.

When you open the Drupal folders in Filezilla, right click on the file you wish to change and choose:

Then you will see the permissions window:

From here you choose the permissions that you want.

OK, following your comment below: If the whole install is owned by your user, and you can make any changes from within the Drupal interface. Then, using your SSH access, create a new folder alongside 'sites/default/files' called 'files2' and copy over the files you want in there, make sure you 'chown -R files2 username:www-data' and then in Drupal go to 'admin/settings/file-system' and change the file system path to 'sites/default/files2' and hopefully, that'll work based on your explanation of the permissions you have. Make sure you protect any new folders using CHMOD on the permissions for the folder and separately for the files inside.

If you can't copy over the files to the new folder then you'll have to recreate them by downloading them from the Drupal site in question and then uploading them back into the new folder.
> 1 votes

---
Tags: users, files
---


# Question
Title: Problem with swfobject_api or jwplayer module
I have a problem with swfobject\_api or jwplayer module.

When I use this code in node.tpl.php everything is fine.

```
$config='sample';
$flashVars=array( 'file' => 'path to flv' );
print theme('jwplayermodule_render_player', $config, $flashVars);

```

When I use this code in front-page.tpl.php the code is not working.

In node-tpl.php this JavaScript is added.

```
<script type="text/javascript" src="/projects/theme/sites/all/modules/drupal/jwplayermodule/jwplayermodule_jwembedder.js?c"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, { "jwplayer": { "files": { "jwplayer-1": { "flashplayer": "http://localhost/projects/theme/sites/default/files/jwplayermodule/player/player.swf", "width": "400", "height": "280", "controlbar": "bottom", "wmode": "opaque", "file": "/projects/theme/sites/default/files/1057680_0.flv", "config": "http://localhost/projects/theme/sites/default/files/jwplayermodule/configs/sample.xml", "events": [  ] } } } });
//--><!]]>
</script>

```

In front-page.tpl.php, it is not added.

I put `<?php print $closure ?>` in footer.php, and included it in front-page.tpl.php and node.tpl.php.

# Answer
> 0 votes
Your template file should be called page-front.tpl.php, not front-page.tpl.php. Once you've renamed it flush your caches and it will work!

---
Tags: files
---


# Question
Title: Can the same entity type (bundle) have different fields in different instances?
I have a question about adding fields to an entity I've defined in a drupal 7 module upgrading from d6 which has 4 types. The modules get a list of fields from a 3rd party server and if the user enables them through the admin interface they are added to the node object as cck fields before the node gets saved. Can I add fields to a bundle in a similar fashion using field\_create\_instance? Is it okay if the same type entity has different fields in different cases, or does the field get added to every entity of that type once it's added?

There are different resources (think data coming from different servers with potentially different fields) each with the same 4 entity types, and different fields could be enabled for each resource. I'm considering adding the fields which are enabled to the entity before it is saved. Entity type 1 could have different fields selected for resource 1 and resource 2. This is the first time I have used d7 entities which is why I'm asking how they work.

# Answer
`field_create_instance` already adds a field instance to a bundle. You can't add fields to an entity type or an entity itself.

I'm not quite sure if I understood you right:

**Guess 1:**
You want for example two nodes of type *person* where one has a field *phone number* and the other one not, which is not possible. Your node type has to define all possible field types, but they may be optional, so if the external system doesn't provide data for it, simply leave it empty.

**Guess 2:**
You want to adjust a whole entity type (this means *all* existing entities) based on external systems, user input or whatever. Thats possible with the Field CRUD API.
> 2 votes

---
Tags: 7, entities
---


title: Adding static pages to Drupal as is

text:
# Question
Title: Adding static pages to Drupal as is
I want to add a static page to drupal. To be specific, for example,

```
<html>
  <head>....</head>
  <body>
    Hi there
    <a href="/node/add/this">Link</a>
  </body>
</html>

```

No sidebars. No Drupal anything. Just a nice page some words. I would like to have the base tag in the header (e.g., `<base href="http://example.org/'>`) set for me.

# Answer
> 2 votes
The simplest solution is to add a html file somewhere in your drupal folder. Apache or whatever web server you use will serve it as is.

# Answer
> 1 votes
Why use Drupal? If you need to use Drupal (e.g. to restrict access based on roles), you can exclude this page from displaying whatever blocks you don't want to display in the visibility settings for that block. Just add your page to the excluded box.

Or you can write a module that uses hook\_menu() and bypasses the entire Drupal theming system. The page example module in the example modules pack is a good starting point for how to do this.

# Answer
> 1 votes
You can make it via theming. Just copy your page.tpl.php to page-url\_you\_want.tpl.php and write whatever you want in that file.

---
Tags: theming
---


title: Location module predictive textfield

text:
# Question
Title: Location module predictive textfield
If you are familiar with the location module you would know that when creating a location the **state/province** textfield predicts options as you type. These options come from a file in the Location module.

I need to re-create that for the **city** field. Can you please point me in the right direction of how to accomplish this? I want to avoid user typos.

**Do I need to create a module of my own or do I hack Location.module ???**

Thanks

# Answer
What this is is an autocomplete field. My guess is if you want to recreate it for another field within the same module then you will indeed need to hack Location module. You'll want to look at the autocomplete callback for the state/province field as well as the autocomplete properties set on the field itself.

However, this may be difficult to do with cities, which is probably why it hasn't been done in Location. If you want to an autocomplete field for cities that actually adheres to the cities wiin a state/province, or even if it doesn't adhere, it will require a full list of cities within each state/province. That's a pretty hefty task if you ask me, but it certainly isn't impossible. I would check around the Location issue queue to see if this has been discussed before. Maybe you can gain information on why it was never done and what the drawbacks may be to developing this.
> 1 votes

---
Tags: location
---


# Question
Title: How to create 2 or more different registration pages in Drupal 7
I'm trying to create (on this, my first project) 2 user registration pages, one for free, the other one could be a 'paid' subscription sign up via UberCart. I'm using AutoAssignRole, Profile2, Views, roles. I'm sure it is really very easy, but I seem to be going around in circles and not getting anywhere. Maybe I can't see the 'logic' for the 'trees'.
The Drupal forums lack any specific answers.

I'm running a Dev machine on an Ubuntu localhost (without WAMP) prior to any.
It's all very frustrating and I'm trying to learn ASAP as to get back in to work. Does any one have a simple answer, or any suggestion for a tutorial on the above? I'm a newbie to Drupal 7 and web programming, but I have 25 years of experience in IT, previously on Microsoft platforms.

# Answer
Could Rules and Webform suffice for what you need to accomplish with the second registration form?

I actually did something similar recently, using a webform as a second registration form. I used the original registration form for the basic registration and on the second form I used Webform Rules to perform actions when the webform was submitted. Of course, this could also be done with a simple fielded node and Rules, but I liked the extra features that webform offered in doing this. If this project can be accomplished with nodes/Rules or Webform/Webform Rules then that can certainly offer you a lot of flexibility in updating the forms in the future as well.
> 1 votes

---
Tags: blocks, users
---


# Question
Title: How to Move the Nodes Displaying in the Front Page to Another Page? (e.g. domain.com/articles)
I've searched almost everywhere and nothing found, so hopefully someone can help me in here!

Okay, I'm using Drupal 7, I installed it and changed the front page to a basic page as I want to have static page displayed rather than list of articles! So this bit is fine and working perfectly, but the problem is how to display a list of my articles on another page, say I'm posting articles regularly and I want to be displayed on the articles section of the website and not on the front page, so how do I do that?

This can be done easily with WordPress 3, but couldn't find a solution for Drupal 7? Anybody have any idea? If you do then please help!

For example http://mydomain.com/articles/ would display a list of my articles, by the way I want each of my articles to be displayed as http://mydomain.com/article/the-article-name

Any idea?

Thanks

# Answer
> 0 votes
You can use a view as suggested, but as **'/node'** also contains a list of article teasers as you say, you can create an alias for **'/node'** called **'/articles'** using URL Aliases.

Given that you've changed your front page to a standard page, the default **'/node'** still exists and will receive a teaser from any content that has *'promoted to the front page'* checked under *'publishing options'* when creating a new piece of content. You can also use the *'sticky at the top of lists option'* if you want an article to remain at the top of your **'/articles'** page. Example from Drupal6;

Finally for any new articles you simply assign the URL Alias **/articles/article-name** when creating a new article.

# Answer
> 1 votes
You need to use the Views module to create a list of recent articles. In fact views come with a predefined view that emulates the core Drupal frontpage. You just need to enable it and just define another path to use (such as site.com/articles). Here is a good series on learning views http://nodeone.se/blogg/learn-views-screencast-series-summed-up (Not affiliated in any way)

---
Tags: nodes
---


# Question
Title: Make 'Full HTML' the default text format
How do I make Full HTML the default text format for the administrator? Currently it is Filtered HTML.

# Answer
> 34 votes
If I remember it correctly, the order that the text formats appear (depending on the permissions you as a user have on using the text formats) is set on the example.com/**admin/config/content/formats** page. Just use the cross icon on the left to drag an re-order the various formats. Put the Full HTML on the top to make it the first choice.

---
Tags: input-formats
---


# Question
Title: Installation profile similar to openatrium but focusing on projects
I'm looking for an install profile (or Drupal based app) similar to Open Atrium, but focus on projects rather than on contacts and tasks; something that is similar to Basecamp.

# Answer
> 1 votes
Not an install profile, but there is a good module for that (6 only), called Storm.

---
Tags: distributions
---


# Question
Title: How do display a secondary menu within a drupal node without the node displaying as a actual menu item
I have created a menu with a teaser view with the teasers linking further to nodes. The problem I have is I would like the secondary navigation to continue to persist with the node that the teaser page links to. The secondary navigation always drops when I go to the actual node. However I don't want these nodes to be menu items. How do you keep a node within the secondary navigation structure without making it an actual menu item?

# Answer
I found a great module that seems to work great! It's called menu position found here: http://drupal.org/project/menu\_position and it's super easy to use.
> 1 votes

---
Tags: routes, navigation
---


title: Create a blog from a separate menu item

text:
# Question
Title: Create a blog from a separate menu item
I want to create a menu link that says blog, and have blog posts show up there (this blog is only for a single user).

I can't find any documentation, and so far everything seems to be posting on the homepage and I can't find a way to redirect blog posts to a different page.

# Answer
What version of Drupal are you using? If you are using 6x you will have to create a "blog" content type and fields using the CCK module. In D7 Content types and custom fields are built into core. Make sure you uncheck the "promoted to front page" option in the content type settings so that your posts won't default to the front page. If you want your blog to go to a link other then the homepage (blog for example). You will need to install the views module, and create a "blog" view page, and configure that view to display your "blog" content types as either teasers (that will further link to the full node) or to full nodes themselves if you don't prefer teasers. Then go over to menus and create a "blog" menu link that leads to the new blog view that you created. Now every blog post will post to the blog view.
> 2 votes

# Answer
Drupal 6.x and 7.x Already have content Type "Blog" under Modules \> Core - optional.

Just enable these and you will be able to use the blog feature.

In order to avoid showing the blog posts on front page, you will need to set specific front pate in addition to @jive's instructions above.
> 0 votes

---
Tags: nodes
---


title: Manually enter custom timestamp

text:
# Question
Title: Manually enter custom timestamp
So I'm making quite a few nodes through a script, an action. To do this I'm using the form\_state drupal\_execute method.

However because there is a lot of processing per node in one batch I get lots of nodes with different time stamps.

Is there any way to manually edit the timestamps a part from going into the DB? I've tried this: outside loop: `$time = time();`

inside loop:

`form_state['values'] = $time;`

And give the same timestamp to all the nodes. But apparently druapl\_execute gives them a new time stamp.

Thanks.

EDIT: Solved! I ended up adding this line, it was the fastest solution I could think of.

`db_query("UPDATE {node} SET created = %d WHERE nid = %d", $time, $form_state['nid']);`

# Answer
Another solution is assigning the `created` property of the `$node` object before calling `$node->save`.

e.g.

```
$body_text = 'This is the body text I want entered with the node.';
$created_time = time();

$node = new stdClass();
$node->type = 'article';
node_object_prepare($node);

$node->title    = 'Node Created Programmatically on ' . date('c');
$node->language = LANGUAGE_NONE;

$node->body[$node->language][0]['value']   = $body_text;
$node->body[$node->language][0]['summary'] = text_summary($body_text);
$node->body[$node->language][0]['format']  = 'filtered_html';

$path = 'content/programmatically_created_node_' . date('YmdHis');
$node->path = array('alias' => $path);

$node->created = $created_time;

node_save($node);

```

For more information please see the API docs on node\_save().

The solution above has the added bonus of not requiring additional databases queries to clean up the timestamps after the node was created.
> 1 votes

---
Tags: nodes
---


title: Drupal 6 Ahah With FileField Problem

text:
# Question
Title: Drupal 6 Ahah With FileField Problem
i'm creating a form which uses ahah in Drupal 6.

I have 2 select fields. The first uses ahah in order to populate the second and it works well.

But the problem is when I add a file field to the form because the ahah call doesn't work (it doesn't appear in firebug and the page is refreshed instead of the normal behavior). If I remove the file field it works again.

Any idea please? I'm getting frustrated thinking about the solution.

Thanks

# Answer
It's a common issue that is reported here and even in the drupal documentation, the issue is reported so I think it's not yet solved at all so you need to find another solution that AHAH for the file upload filed.
> 1 votes

---
Tags: ajax
---


# Question
Title: Adding variables to page--taxonomy.tpl.php
How do I add preprocess variables to `page--taxonomy.tpl.php` which will be available only to the vocabulary *Project Type*? I know my code below is wrong.

```
function themename_preprocess_taxonomy(&$vars, $hook){
    $vars['testing'] = 'It works!'; // This doesn't work :p

    // If that checks out, how to limit it only to a specific vocabulary (e.g. Shoes)?
}

```

# Answer
> 2 votes
You can limit variables to certain conditions. Obviously only when the variables to measure these conditions are available.

```
function themename_preprocess_taxonomy(&$vars, $hook){
  var_dump($vars);
}

```

This will show you all the available variables, for example the $vid, which contains the vocabulary-ID. The simple version would be:

```
function themename_preprocess_taxonomy(&$vars, $hook){
  if($vars['vid'] == 12) {
    $vars['example'] = "Foo";
  }
}

```

A clean, and much better solution would then be:

```
function themename_preprocess_taxonomy(&$vars, $hook){
  $vars['example'] = ''; # Always instantiate a variable, and make sure
                          # it has a constant type
                          # e.g. always return a string.
  if($vars['vid'] == variable_get('themename_vid_for_example', 123)) { # Avoid Magic Numbers [1]
    $vars['example'] = "Foo";
  }
}

```

\[1\] http://en.wikipedia.org/wiki/Magic\_number\_%28programming%29#Unnamed\_numerical\_constants

**EDIT:** updated variable\_get. tss.

---
Tags: taxonomy-terms
---


title: add a checkbox to the image_field

text:
# Question
Title: add a checkbox to the image_field
I want to add a checkbox-field to each image I upload (like the title- or alt-fields) , to set the option whether the theme should render the image as a gallery or not. the value should be saved in the db. `int(1)`

I don't want to install heavy modules for this...

**edit**: but if there is no other option, I take the module :D

is there maybe a strategy I should use to solve the problem? writing a `widget` or something? hooking into the `images_schema` ?

# Answer
> 1 votes
I just did this with the imagefield extended module and a small custom module. After enabling the imagefield\_extended module, I add this code to my custom module.

```
/**
* Implementation of hook_imagefield_extended_widget().
*/

function MYMODULE_imagefield_extended_widget($element, $extra_values) {
  // If you need the field or widget to conditionally add a FAPI field, use these.
  $field = content_fields($element['#field_name'], $element['#type_name']);
  $widget = $field['widget'];
if($element['#type_name'] == 'occupancy_status' && $element['#field_name'] == 'field_task_files'){
  return array(
    //This will Replace the Textfield with dropdown select for the description
    'description' => array(
      '#type' => 'select',
      '#title' => t('Document Description'),
      '#options' => array(
         'Occupancy Flyer' => t('Occupancy Flyer'),
         'Personal Property Release' => t('Personal Property Release'),
         'Introduction Letter' => t('Introduction Letter'),
         'Notice of Rights' => t('Notice of Rights'),
         'Miscellenous' => t('Miscellenous'),
      ),
      // this makes b the default value when the value is not set.
      '#default_value' => isset($extra_values['description']) ? $extra_values['description'] : 'Miscellenous',
    ),
  );
  }

   if( $element['#type_name'] == 'property_gallery' && $element['#field_name'] == 'field_gallery_images' && arg(1)!=='add'){

  return array(
    //These are stored in the 'data' column of the cck imagefield's db table
    'revised' => array(
      '#type' => 'checkbox',
      '#title' => t('Revise This Description'),
       '#default_value' => isset($extra_values['revised']) ? $extra_values['revised'] : 0,
     '#attributes'=>array('class' => 'revise-check')
       ),
    'revisedby' => array(
      '#type' => 'textfield',
      '#maxlength' => 64,
      '#title' => t('Revsied By'),
      '#description' => t('Replace your name with the current name if you are making a new revision.'),
     '#default_value' => ($extra_values['revised']==0) ?  NULL : $extra_values['revisedby'] ,
       ),
       'revisedon' => array(
      '#type' => 'date',
      '#title' => t('Date Revised'),
     '#default_value' => ($extra_values['revised']==0) ?  NULL : $extra_values['revisedon'] ,

       ),

  );
  }
} /*End function */

```

You have the ability to add or modify the filefield or the imagefield field widgets. The only problem that I'm stuck at is making this work for fupload\_imagefield.

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


# Question
Title: Can't get CKEditor to work on Drupal 7.8
I've tried both the CKEditor module, as well as the WYSIWYG module (with CKEditor library installed). I've configured it all correctly and it should work, but it doesnt. I've also tried changing the CSS options but still nothing.

I'm getting "r is undefined" in the console, but only if I change the text format option underneath where the editor should be.

I'm currently working off localhost - might that be an issue?

# Answer
Well I finally got it working...

I installed CKEditor module, CKEditor library, and then had to hack the CKEditor library folder by creating new subdirectories with the appropriate files (it was looking for the skin and language files in the wrong directory within the CKEditor library folder)...

I'm using the latest version of everything - why is this happening? I would have thought since this happened to me its happening to everyone else as well!

If anyone else has this problem, ensure you have these files in your /modules/ckeditor/ckeditor/ folder: "lang/en-gb.js" "skins/kama/images/sprites.png" "skins/kama/editor.css" "skins/kama/icons.png"

All these files are just in the root folder by default for some reason.
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: WYSIWYG error when using managed_file and AJAX
I have a form that has both a managed\_file element and a text\_format element. Both are encapsulated in a wrapper div (using #prefix and #suffix). On submit, an AJAX callback is executed and both elements are populated with data.

However, when the form is rebuilt, the WYSIWYG editor disappears. The following error is displayed in the javascript console of my browser: **Uncaught \[CKEDITOR.editor\] The instance "edit-text-value" already exists**.

When I remove the managed\_file element, the form works as it is supposed to. It probably has something to do with the Drupal behaviours not being executed properly (managed\_file widget?), not removing the editor instance.

# Answer
go around ckeditor.utils.js, the thing is that at various events ckeditorOff() function is called which causes ckeditor to go off, i just commented out a destroy call in the ckeditorOff() method and the RTE disappearance issue got solved
> 0 votes

---
Tags: 7, forms, javascript, wysiwyg, files
---


title: Multiple registration forms

text:
# Question
Title: Multiple registration forms
I have multiple user role and different registration forms for each role. It means that for each registration form, there are different fields.

I when a user select her role, the registration form should change. can I have several registration forms?

# Answer
> 3 votes
Take a look at Auto Assign Module to see if that solution will work for users assigning themselves to roles.

If that will work, developing a single registration form that will show additional fieldsets or other form elements based on user role should not be too difficult.

# Answer
> 4 votes
First thing you should be aware of, is that you probably don't want to expose the roles to the user during registration, at least not all of them. If you do, then any user would be able to create an admin account, and gain access to the backend.

You can't easily make different registration forms, but you can instead create a multi step form. Step one would be general user information where the user selects which role / type of user to create. The second step would have unique fields depending on the role selection.

The example module has a lot of great examples including how to create multi-step forms.

# Answer
> 0 votes
I'm trying to do a similar thing... Check Profile2 (which requires the exciting (Christ I am geeky!) Organic Groups(OG) and Entity)). I have just installed so am going through it myself, but certainly it's the closest thing to what I have been looking for. Hope it helps. Alternatively, try http://drupal.org/node/999420... but I was lost.

---
Tags: 7, forms, users
---


# Question
Title: I get "/tmp is not writeable by the webserver" on migration
I migrate a Drupal website from Apache to IIS.All the image that customize whit ImageCach not shown and I get this error "/tmp is not writeable by the webserver"! please help me soon!:(

# Answer
> 4 votes
If you search Google for "drupal iis tmp not writeable by the webserver", the first result is a post on drupal.org, telling you to:

> Try going to admin/settings/file-system and set /tmp to just tmp

and a comment saying:

> Confirming this fix. It might have something to do with going from linux system to windows.

I guess that will work in your case too.

---
Tags: migrations, iis
---


# Question
Title: How can I set a message if db_delete deleted one or more rows
In drupal 6 my code worked like this:

```
if (db_query("DELETE FROM {,ymodule_fields} WHERE conid = %d", $conid)) {
  drupal_set_message(t("Deleted fields."));
}

```

Now I'm supposed to use db\_delete.

Will this code work? I know db\_delete returns a DeleteQuery object so I'm assuming it's going to evaluate to true every time. I can't test my module yet because I'm doing a lot of work updating the code that creates cck fields to use core fields. Is DeleteQuery a PDO that has the `rowCount` method?

```
if (db_delete('mymodule_fields')
  ->condition('conid', $conid)
  ->execute()) {
  drupal_set_message(t("Deleted Fields."));
}

```

# Answer
> 2 votes
Sure, `db_delete()` returns an object so you can continue working with the object, but the last method called (the method whose return value your conditional is really checking) in your statement is `Query::execute`, which returns boolean `TRUE` or `FALSE` indicating whether the query worked. So, ultimately the whole statement:

```
db_delete('drealty_fields')
  ->condition('conid', $conid)
  ->execute();

```

Should return `TRUE` or `FALSE` since you're ultimately executing the `Query::execute` method. The workflow is just that you call `db_delete()`, which returns an object, `Query::condition`, returns an object, then `Query::execute` returns boolean, but your conditional is just getting and checking the return value of the last method called - `execute` \- rather than the return value of `db_delete()`. Essentially, the `db_delete()` return value was already operated on by continuing with a condition, and the condition's return value is inconsequential because it was operated on by `execute`, thus the execute's return value is the only one really getting sent back to the `if` statement. Make sense?

So, in essence each of these examples should give the same results:

```
$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
$success = $query->execute();
if ($success) {
  // Do something.
}

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
if ($query->execute()) {
  // Do something.
}

if (db_delete('drealty_field's)->condition('conid', $conid)->execute()) {
  // Do something.
}

```

---
Tags: 7, database
---


# Question
Title: Drupal 7 : How to break title of content into multiple lines
Most of the content-nodes on my site have two parts (English | Arabic). I want to put a line break between the two, so that the broken text does not look awkward. But when I put an html line-break tag, the tag itself shows up in the title.

What to do?

Appreciated...

# Answer
> 3 votes
As I understand you want have your nodes titled using pattern `<English name><Arabic name>`, and split your title on 'language border' to different lines. As was mentioned node title is used in both places content title, and page title.

So you can use changed pattern `<English name>|<Arabic name>` and override your template file in your theme. You can use str\_replace before displaying title for your node. Also your page title will look ok, without changing theme more; and this solution support titles without `|` delimiter, or with more then 1.

# Answer
> 0 votes
HTML tags are not allowed in titles, and they are escaped. The HTML 4.01 Specification reports the following text:

> Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments). Here is a sample document title:

```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A study of population dynamics</TITLE>
... other head elements...
</HEAD>
<BODY>
... document body...
</BODY>
</HTML>

```

For using HTML tags in the page title, you should set it with drupal\_set\_title($title, PASS\_THROUGH), but I would not suggest doing it, as the title is used for both the page, and the browser title, which should not contains HTML tags for what I reported before.
As `PASS_THROUGH` by-pass the call to `check_plain()`, you should check the value you pass as `$title`, and verify it doesn't contain dangerous characters. I would also suggest to use the Page Title module to avoid the browser title contains any HTML tags; as the module set for the browser title a value different from the page title, you could have HTML tags only in the page title.

Apart from separating the text with " | " the only solution is to have the title in a single language; after all Drupal support multi-language content, and the translation of a node to different enabled languages.

# Answer
> 0 votes
It is not possible, at least not directly. Some thoughts:

1. Use Drupal multilingual tools to store multiple-language-versions of node content including titles.
2. Use the Page Title module to generate custom `<title>` tags from CCK fields, tokens, etc.
3. Use a custom field using an input filter that allows HTML to store this "title", theme your content type to display this field instead of the default title field.

Node title is plain text only and will likely remain that way.

# Answer
> 0 votes
Why not use CCK to add a new Arabic title field to the content type(s) and place it immediately after the default title? After that it's just a matter of CSS to position it.

---
Tags: theming
---


# Question
Title: How to add default text that clears on focus with jQuery to a search form text field in Drupal
I would like to have a default text in an Exposed Views Search form that says something like 'type in a keyword to search' which will disappear if the user clicks on the text field and reappear if the user removes the cursor and didn't type anything. I would like the title of the field which is added through Views to become the text in the text field box. Should I use pure jQuery to add the text to the box? Or should I use hook\_form\_FORM\_ID\_alter() to add the jQuery and change the location of the title?

# Answer
You can do this by implementing `hook_form_alter()` in a custom module.

```
function custom_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#id'] == 'search-block-form') {
        $search_text = 'Your search text here';
        $form['search_block_form']['#default_value'] = $search_text;
        $form['search_block_form']['#attributes'] = array(
        'onfocus' => "if (this.value == '$search_text') {this.value = '';}",
        'onblur' => "if (this.value == '') {this.value = '$search_text';}");
    }
}

```
> 9 votes

# Answer
I think the best solution is the both, `hook_form_alter()` like this, you can add the `placeholder`attribute for fallback.

And after, for browsers that don't understand placeholder, you can use pure jQuery.
> 0 votes

# Answer
Unfortunately, because the way Views Exposed filters is structured setting the default attribute also sets the filter which is rendered later. Using the jQuery Input Example plugin I added some custom code to a helper module.

First, I need to add the jQuery to the page. Since I think I might use this in the admin theme also I didn't put it in a theme so it gets added to the overlay.

```
function helper_preprocess_page (&$vars) {
  // Let's add some js to page for the search box.
  $path = drupal_get_path('module', 'helper');
  drupal_add_js($path . '/js/jquery.example.min.js');
  drupal_add_js($path . '/js/helper.js');
}

```

In the helper.js file I added the code to execute the helper plugin.

```
(function ($) {
  Drupal.behaviors.helper =  {
    attach: function(context, settings) {
      $('input#edit-search-job-aggregation').example('Enter a location (optional)');
      $('input#edit-search-api-views-fulltext').example('Enter a keyword (optional)');
    }
  };
})(jQuery);

```
> 0 votes

---
Tags: forms, javascript
---


# Question
Title: Can't choose a Taxonomy term as a Context condition
I'm trying to create a context based on taxonomy. When I use the Context UI, the Taxonomy form is not populated with my taxonomy terms. Here's a screenshot of my empty taxonomy selector.

I have three terms in one vocabulary, and all terms have at least one node associated with them.

What's going on?

# Answer
> 0 votes
Turns out this was user error. I wasn't the one to set up the taxonomy vocabulary in the first place, and it turns out that the guy who did set the vocabulary to be Tags. You can't use Tag vocabs in Context conditions. I unchecked the "Tags" box and now everything works as expected.

---
Tags: 6, taxonomy-terms
---


title: Embed Protected PDF

text:
# Question
Title: Embed Protected PDF
Wondering if anyone has done this in Drupal 7.

I have a set of PDFs which need to be protected (i.e. restrict access). However, they also need to be displayed on a webpage (via the EMBED tags) for those users who have been authenticated.

What I have seen done in other systems is:

The PDFs are stored in a protected directory (e.g. PRIVATE) There is also a PUBLIC directory When the PDF is requested by an authenticated user, the PDF is copied from the PRIVATE directory to the public under an MD5 (with SALT) hashed name, and the filename is returned to the viewer. Does this make sense, and has anyone done this in Drupal?

# Answer
> 1 votes
Set the download method to private and implement hook\_file\_download().

---
Tags: files
---


# Question
Title: Generating Images from image styles in drupal 7
I'm just getting accustomed to the changes in drupal 7, I've created a number of nodes that have an image field. The nodes were created as dummy content from the Devel module. I then created a view, added a number of fields, and chose my image style as a formatted for one of the fields. The only thing I can't figure out is how to get Drupal to generate the the images, I tried re-generating the dummy conent, but it still does not create the thumbnails.

Any Ideas?

# Answer
Are the folders where the images go writable? Also check the tmp folder
> 2 votes

# Answer
image style images should be dynamically generated as needed. Are the links to the images being formed properly? They should be in the files/styles folder
> 0 votes

---
Tags: 7, caching, media
---


# Question
Title: How do I unset the comment form in Drupal 7?
In Drupal 7, the comment form appears on every node. I want to unset the comment form and display a link of "Add new comment" that will display the comment form on click.

Do you have any Idea?

# Answer
Go to "Structure \> Content types", "Content type \> Comment settings", and uncheck "Show reply form on same page as comments."
> 4 votes

---
Tags: forms, comments
---


title: mysql populate a field of a content?

text:
# Question
Title: mysql populate a field of a content?
I have a content type that has the field field\_data\_latitude. I see in the database the existence of a table called field\_data\_field\_latitude that contains the values for this content type . When I populate it via mysql, the value does not show up in the CMS. Are there other tables I'm supposed to populate?

I also noticed a table called field\_data\_field\_latitude..I popualted that as well but the value is not visible in the CMS.

# Answer
> 1 votes
Clear the cache after adding your custom values to the database. Might fix the problem as I have seen it work for some in the past.

---
Tags: 7, nodes, database
---


title: Add Class or ID to Menu Items

text:
# Question
Title: Add Class or ID to Menu Items
**Brief:** I need to add a popup form to the menu links STAY INFORMED on the top-right and sidebar menu. I tried the Popups module, which loads all of my sites pages blank/white when activated. I am using it, but I am not sure how to use it.

The README.txt file has 4 ways of adding it, and I would like to use the second method (adding "popup" as CSS class to an existing link), but I am unable to add a custom CSS class/ID to a specific menu item. Is there a module that can do this, or does anyone know a easy way to setup?

# Answer
I am pretty sure that the Menu Attributes module will work for you. It adds several options to the menu entries, including ID and class attributes. You would just need to edit the menu entries that you need this class on.
> 1 votes

# Answer
POPUPS is right. But you're going to have to implement an override to hook\_menu to iterate through your specific menu items and identify which one you want to put the class='popup' to. With this, I suggest you create your own module to handle all kinds of overrides for your site. You can then drop in there overrides for your own custom menu themes. I think this is a good tutorial for how you can theme menus indvidually here

and do not forget to revisit your theme page or clear your cache to effect the changes. Do not forget also to have popups module (see its configuration) scan all links with popups class.
> 0 votes

# Answer
Module "Menu attributes" will do the trick, you can add Class or ID to each menu item. If you need to add a span to the WORD itself i.e. seperate it from the tag. you need to add this code to your template.php file. As you can see in the code, I used this to add Class Displace to my menu items so I could then use a image as a menu button from CSS.

Can't recall where this code came from but it wasn't mine, so I can't help other then provide it. cheers.

```
function YOUTTHEME_menu_link(array $variables) {
      $element = $variables['element'];
      $sub_menu = '';

      if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
      }

      $element['#localized_options']['html'] = TRUE;
      $linktext = '<span class="displace">' . $element['#title'] . '</span>';

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

```
> 0 votes

---
Tags: forms, javascript
---


# Question
Title: Strange sorting in one facet of Apache Solr Search results
We're using the Apache Solr Search module to allow users to filter search results; for example, if a user searches for Pepsi, they get all results, but along the left of our screen they get facets allowing them to filter by Post Date, Article Type, Trend, etc. (Ignore the HTML under Trends/Seasonal; we have the Themer module turned on.)

We haven't done anything custom to this search that I know of, but there's something strange: all the facets EXCEPT post date sort descending by number of results. Filter by post date actually sorts by post date. We want that one to also filter by number of results. (It's not visible in the screenshot, but 2010, for example, has over 500 posts so we'd definitely like that one to be at the top.)

Is sorting a module setting somewhere? (There are blocks for each filter-by facet, but sort order is not one of the config settings.) I tried looking around in the code, and I found the spot in our search results page template where the entire left filter bar is printed out, but cannot for the life of me find (even with a full-site grep) where the variable it's printing is actually being set.

# Answer
Don't know exact path for D6, but you can got to facet configuration, configure display - and there will be sort options with ability to enable/disable sorts and reorder sorting.
> 0 votes

---
Tags: 6, search
---


# Question
Title: How to efficently use Drupal as a laboratory notebook and information management system?
I am a chemo-informatics researcher looking to find user experiences and feedback on methods to keep laboratory notebooks on a computer and/or online using Drupal ( e.g. plugins to use, taxonomies).

# Answer
> 1 votes
How do you want to organize your information? I would use a content type such as 'notebook\_entry' with a taxonomy 'subjects' and/or 'projects' that allows free tagging of terms.

notebook\_entry should use the body field for the bulk of your content. You can add additional text/image/file fields for storing related information that can be displayed with the content.

I recommend using views to display your notebook entries. You can create an argument in your page view with the taxonomy term or terms you've defined for the notebook\_entry content type. This will make the page only display entries related to that term. You'll have to create a menu block filtered by the taxonomy to access your content. It will list each of the taxonomy terms as links to your page view that displays your notebook\_entries. Create a list of terms and use the global text field to make a link to the path of your page view including the arguments.

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


# Question
Title: problem with printing multiple cck value inside node-type.tpl.php
I am printing out this thing inside node-mytype.tpl.php (D6):

```
$dots = '';
$i = 0;
foreach($node->field_authors as $item) {
    $i = $i + 1;
    if ($i < count($node->field_authors)) { $dots = ',  '; } else { $dots = '.  '; };
    print '<span>'. $item['view'].$dots.'</span>';
}

```

Can somebody explain to me, why in this case printing `$item['view']` == succesfully printing cck field values? Shouldn't it be like `$item[i]['view']`?

When i'm printing cck multiple values im usually do it this way:

```
print $node->field_authors[0]['view'];
print $node->field_authors[1]['view']; // if 2 values

```

Explain to me please, i would really appreciate it...

# Answer
Your code uses foreach which takes `$node->field_authors[0,1,etc]` and relays that value through $item. If you want to know the key for the current field inside your foreach loop, rewrite the code like this:

```
$dots = '';
$i = 0;
foreach($node->field_authors as $key => $item) {
    $i++;
    if ($i < count($node->field_authors)) { $dots = ',  '; } else { $dots = '.  '; };
    print '<span>'. $node->field_authors[$key]['view'].$dots.'</span>';
    // note: $node->field_authors[$key] is the same as $item['view']
}

```
> 2 votes

---
Tags: entities
---


# Question
Title: Embedded Media Field Video: Output both Video Flash Object and Video Thumbnail in Node Display?
I would like to be able to access both the Video Flash Object, as well as the Video Thumbnail filepath from the Node Display. Please let me know if I can provide more info, not sure anything else is relevant! Thanks!

**Clarification**: Basically I want to be able to be able to output both the video with a custom resolution, and the thumbnail through an imagecache preset, from either a custom module, or within template.php. Essentially I would hope to end up with both the final video HTML and image HTML as individual objects or php variables, so I can then output them wherever I like from within the relevant node.tpl.php. I'm assuming there's a simple theme() function I can use for both of the above. The embedded video at this time can come from either Youtube/Vimeo.

# Answer
> 2 votes
One way to do it is to set the video field display mode to full video under `/content/types/CONTENT_TYPE/display` then add the thumbnail via theme\_emvideo\_video\_thumbnail() as a variable using `themename_preprocess_node(&$vars)` in your theme's template.php -OR- print it directly in your node.tpl

The trick to `theme_emvideo_video_thumbnail(($field, $item, $formatter, $node, $no_link = FALSE, $options = array()))` is to provide all the right parameters. Especially `$options`

e.g.

```
<?php
  // code adapted from emvideo.theme.inc
  // ignore the <?php tag

  $system_types = _content_type_info();
  $field_name = 'field_video'; // the machine name of your video field

  $field = $system_types['fields'][$field_name];
  $field['widget'] = $system_types['content types'][$node->type]['fields'][$field_name]['widget']; // get CCK widget data. includes all formatting settings

  $options['return_url'] = TRUE; //return URL
  $options['raw'] = TRUE; // return image path. Otherwise node path is returned

  print theme('emvideo_video_thumbnail', $field, $node->{$field_name}[0], 'video_thumbnail', $node, FALSE, $options);

```

In template.php

```
<?php
// change MYTHEME with the theme's machine name or use phptemplate
function MYTHEME_preprocess_node(&$vars) {
  if ($vars->type == "mynodetype") {
    // see code above
    $vars->video_thumbnail = theme('emvideo_video_thumbnail'...);
  }
}

```

Then `<?php print $video_thumbnail; ?>` where you need it in `node.tpl.php` (-OR- use the first code block directly in the node template)

Hope it helps.

---
Tags: 6, files
---


# Question
Title: Set a page to be only viewed by users who are logged in
I have created a page that I would like to be visible only for logged in users and admin.

# Answer
It sounds like you're looking for a node access module. There are many of these modules available which approach this problem in different ways. But in the end, they all allow you to specify more fine grained access rights to nodes (and other types of content). There's a good overview of the various node access modules on drupal.org. This page explains what you should consider when choosing a node access module and describes quite a few of the popular ones. If none of these quite meet your needs and you're up for creating your own custom module check out the documentation for Node Access Rights (here's the Drupal 6 version just in case).

---

Edit:

In response to the comment from OP, in general you can't set access (view) permissions per content type (though you can set create/edit/delete permissions per content type). So either people can't see any content until they sign in, or they can see all content all the time. So if you have a specific content type that should only ever be visible by logged in users you'll likely need a node access module.
> 3 votes

---
Tags: users, 7
---


title: Customize a View 3 SQL query

text:
# Question
Title: Customize a View 3 SQL query
I've created a view that lists the content based on the first letter of that title matching an argument passed to the page. Now I'm trying to do the same, but with a `0-9` so when the user selects `0-9` the view gets all content types which begin with a number in the range `0-9`.

I'm currently looking at `hook_views_query_alter()`, but I don't get back the results I am expecting. The function I've written is the following one:

```
function module_views_query_alter(&$view, &$query) {
  if ($view->name == 'custom_page' && $view->current_display == 'page_1') {
    if ($view->args[0] == '0-9') {
      $query->where[0]['conditions'][2]['field'] = 'SUBSTRING(node.title, 1, 1)';
      $query->where[0]['conditions'][2]['value'] = array('0','1','2','3','4','5','6','7','8','9');
      $query->where[0]['conditions'][2]['operator'] = 'in';
    }
  }
}

```

# Answer
This is a bit of a cheat following the code that's used by the glossary view, but it works:

```
function module_views_query_alter(&$view, &$query) {
  if ($view->name == 'custom_page' && $view->current_display == 'page_1') {
    if ($view->args[0] == '0-9') {
      $query->where[0]['conditions'][2]['field'] =  "SUBSTRING(node.title, 1, :node_title) in ('0','1','2','3','4','5','6','7','8','9')";
      $query->where[0]['conditions'][2]['value'] = array(':node_title' => 1);
      $query->where[0]['conditions'][2]['operator'] = 'formula';
    }

```
> 4 votes

# Answer
In MySQL, when using the in() operator, you must past the list in a certain format. I'm not sure that views automatically converts PHP arrays to that format or not.

I know that when I've used in() in the past, I converted arrays myself. In your case it would look like this:

```
$query->where[0]['conditions'][2]['value'] = "('" . implode("','", range(0,9)) . "')";

```

You can see the results of the `implode()` & `range()` at this codepad.
> 0 votes

# Answer
since you want to select all the content titles that start with a number why not just put something like

```
ISNUMERIC(SUBSTRING(node.title, 1, 1))

```

or

```
BETWEEN 0 - 9

```

in you WHERE statement.
> 0 votes

---
Tags: 7, views
---


title: Removing repeated field items

text:
# Question
Title: Removing repeated field items
I'm using Flexifield to create a repeating series of CCK field groups via a button that says "Add another item" (I.e., setting the number of field values to unlimited). See below:

My client has requested the ability to remove rows from this list once added. Any idea how I'd do that?

Thanks!

# Answer
There's an issue that does exactly what I was asking for. Problem solved!
> 0 votes

---
Tags: 6, ajax, entities
---


title: views alter query

text:
# Question
Title: views alter query
I have content type `event` that has `date` field and i created view "events" to this content type and added contextual filter "Date".

The problem is in the database the field date value is stored with this format `2007-01-17T00:00:00` and I want to filter like this `events/2007`. Unfortunately, I get no results because the URL should be like this `events/2007-01-17T00:00:00`.

So what is the solution for making it work with this `events/2007` by altering the query using `views_views_query_alter()` instead of creating field that hold the value like this `2007`. I believe that altering the query by this way should solve it but it didn't

```
function views_views_query_alter(&$view, &$query) {
  if ($view->name == 'events' && is_numeric(arg(1)) ) {
    $view->query->where[0]['conditions'][3]['field']=" YEAR('field_data_field_date.field_date_value')";
  }
}

```

# Answer
> 1 votes
Which Drupal and Views versions? From what I can see on my test site when creating:

A Filter Criteria you can specify granularity to year; same thing goes for a Contextual filter. (D7, latest Views).

---
Tags: views
---


# Question
Title: Custom fields added via form api not working as expected
I'm having a whole mess of issues adding text fields to a form in Drupal 6. I want to add a text field with an autocomplete. I tried adding the field in hook\_form\_alter() like so:

```
$form['my_field_name'] = array(
  '#type' => 'textfield',
  '#title' => 'My Title',
  '#required' => true,
  '#default_value' => 'my_default_value',
  '#autocomplete_path' => 'url/to/autocomplete'
);
$output .= drupal_render($form['my_field_name']);

```

When I output this, the field output to html does not have an id or name attribute, and the autocomplete doesn't work (presumably because the id is missing. Additionally, the default value is not populated in the field.

I can overcome some of these issues by adding in a custom #id, #name, and #value, like so:

```
$form['my_field_name'] = array(
  '#type' => 'textfield',
  '#title' => 'My Title',
  '#id' => 'my_field_id',
  '#name' => 'my_field_name',
  '#required' => true,
  '#value' => 'my_default_value',
  '#autocomplete_path' => 'url/to/autocomplete'
);
$output .= drupal_render($form['my_field_name']);

```

This gets the autocomplete working as expected, gives a name and id attribute, and fills in the default value, but unfortunately now the autocomplete does not actually change the value of the field, so I can't enter and submit a new value.

How can I overcome these problems with form\_alter?

# Answer
> 1 votes
AFAIK, `hook_form_alter()` does not require you to perform a `drupal_render()` in it. And I suspect that is why you are not getting a proper rendered for item.

Also, each custom field needs to processed (by you) on form submit. Thus, you need to add `$form['#submit'][] = 'my_submit_function_submit';`, where `my_submit_function_submit()` handles the database inserts.

# Answer
> 0 votes
It's not very clear what you are doing with the $output variable since the return value from hook\_form\_alter() isn't used anyway. zerolab is correct that you should not be using drupal\_render, you're just adding elements to the form, and the form will be rendered as a whole all at once after it has been fetched, altered, built, etc.

While I can't see what's going on, I wonder if you're not passing the $form argument by reference, and that is why you added the drupal\_render to try to make your element show up, make sure that the signature for your function looks like this (note the & symbols):

```
function hook_form_alter(&$form, &$form_state, $form_id) {

```

---
Tags: forms
---


title: problems with hook_form_alter()

text:
# Question
Title: problems with hook_form_alter()
```
function heihachi_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'ipaper_node_form') {
           unset($form['body']);
        }
}

```

the code above removed body field in node/add/ipaper. But how can i remove body inside a node? (mysite.com/node/4420 for example).

And 2nd question is: i did `print_r($form)` inside mymodule.module and now im watching in the page source code and see this:

```
Array
{

    [#node] => stdClass Object
        (
            [uid] => 1
            [name] => heihachi

```

i am on the right way if i use this construction to print the name for example: $form\['#node'\] =\> \['name'\] ?? Guess not.. :) That stdClass Object is confusing me :(

# Answer
A better approach is to edit the content type settings and omit body altogether.

In Drupal 6, you can do this by going to `/admin/content/types/ipaper` and leave the "Body field label" empty.

In Drupal 7, go to `/#overlay=admin/structure/types/manage/ipaper/fields` and delete the Body field.

If you really need to keep old content in the node body, then use `hook_nodeapi()` with `$op == 'view` to unset `$node->body`
> 3 votes

# Answer
The if $form\['body'\] is where the output is being sourced from, unset should work fine, but as this is form\_alter I'm not entirely sure whether the node will already have been rendered by the time it's called.

You'll be able to get to the node name using:

```
$form['#node']->name

```

rather than:

```
$form['#node']['name']

```

which would be what you'd use if it was an array rather than an object
> 1 votes

# Answer
You should implement hook\_nodeapi:

```
function heihachi_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'prepare') {
    unset($node->body);
  }

```
> 1 votes

---
Tags: forms
---


title: %252F in the URL

text:
# Question
Title: %252F in the URL
I have imagecache installed and I'm using views. In my fields in views I have selected one of the presets for my images to resize. When I try to view my completed page the path to the thumbnail is incorrect. It links to http://www.example.com/sites/default/files/imagecache/album/%252Fimages/...

Where does that %252F come from? How can I fix this to show the correct URL?

# Answer
> 5 votes
`%2f` is the url encoding of `/`, if you have `%252f` seems a double encode of the specific string. I guess a bug of imagecache Module, or/and some intermediate module using an encode process.

Also, this documentation related with Drupal drupal\_urlencode could be useful to understand the case when exist `//` that is `/%252F` http://api.acquia.com/api/drupal/includes--common.inc/function/drupal\_urlencode/6

# Answer
> 1 votes
I believe `%252f` represents a slash `/` in URL encoding. When data is passed in urls it is encoded because only certain characters can be in urls, so a mixture of allowed characters are used to represent certain characters that would otherwise be disallowed. Considering that this is a slash `/`, it's likely that you have a beginning or trailing slash somewhere where it doesn't belong - maybe in a field in which you identify a path - resulting in two consecutive slashes, the second being encoded, so look for that.

---
Tags: views, media
---


title: Show menu tab on certain content type

text:
# Question
Title: Show menu tab on certain content type
I have created a menu tab with views and I want to show that tab only on a certain content type. How can I do this?

# Answer
Have you tried this resource? http://drupal.org/node/354423 , if not, could be useful, is about a menu tab to show only with certain content type.
> 0 votes

---
Tags: views
---


# Question
Title: Should I enter data as English and then translate to my language?
For data entry for taxonomy terms and field names, should I enter data in English and then translate to my own language?

Entering directly in my own language has no problem. I just want to know if there is any rule for this.

# Answer
> 0 votes
Well, if you've a only one language website, you can directly enter the values directly in your own language. You can also install your language pack that you can find on localize.drupal.org.

If you gonna start a multi-language website, you should (and its easier) to start everything in english and after start to translate. But in that case, is already important since the beginning to active all languages that you need.

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


title: Theming forms in Profile 2

text:
# Question
Title: Theming forms in Profile 2
I was recently introduced into the Profile2 module for adding fields to the registration process and I think it just solves my problem. Can anyone show me how to theme the fields? All I need are the .tpl files but I don't think there are any since it's form so it uses the Form API. I may be wrong though.

# Answer
By default the form will be rendered using the form rendering system, which doesn't include template files, instead functions like theme\_textfield is used instead. You can choose to let the entire form or certain form elements be rendering by your custom theme function using the `#theme` key.

For certain type of fields, this can be dangerous as they require certain markup.
> 3 votes

# Answer
Ah yes, I too once thought that the Form API was the only way to style my forms. Personally, I think it's a pain in the neck to muck around with form\_alter hooks trying to change elements and add the HTML markup you need to style your form; I'd much rather just use one .tpl.php file for the whole thing. And low and behold, you can!

In the following method I define variables from the form that can be outputted in a template file to fit whatever HTML structure you'd like. This assumes knowledge of the form structure. In this case, I'm guessing your form structure is defined in multiple places, depending on what fields compose your users. I'd suggest using a hook\_form\_alter in your template.php to print out the form array so you can get the form ID and all the info on the elements.

For this method, I put all of my code in template.php, but you can just as easily make a custom module to do this.

1. Add a hook\_theme() implementation

```
function YOURTHEME_theme($existing, $type, $theme, $path){
      return array(
        'YOUR_FORM_ID' => array(
          'render_element' => 'form',
          'template' => 'user-profile-form',
          'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
          //add '/templates' only if you store template files in an additional folder
        ),
      );
    }

```

This tells the Drupal theming system that there's a template file waiting for it in YOURTHEME/templates.
2. Next we'll define some variables to pass into that template in a hook\_preprocess\_HOOK function. We can find the structured array of the form in $variables\['form'\] and assign the form elements to the variables we'd like to throw around our tpl.php file.

```
function YOURTHEME_preprocess_YOUR_FORM_ID(&$variables) {
    $variables['rendered'] = drupal_render($variables['form']['some_form_element']);
    $variables['rendered'] = drupal_render($variables['form']['some_form_element_2']);
  }

```

This example will put both of the selected form elements into a variable called "rendered." Not knowing the structure of the form given from Profile2, I don't know what these elements will be called; again, check the form structure!
3. Now that we have defined a variable, we can output it in a template file. Create a template file named YOUR-FORM-ID.tpl.php in 'YOURTHEME/templates'. This is a demo example:

```
<div id="new-form">
  <?php echo $rendered; ?>
</div>

```

When you visit the page that the Profile2 form is on, you should now see only some\_form\_element and some\_form\_element\_2. Create different variables in the preprocess function to separate out form elements and place them wherever you wish in the YOUR-FORM-ID.tpl.php file, adding whatever markup you like. If you need to change specific things about each field, you can play with each element individually before it's rendered in the preprocess function by changing any of the Form API tags.

This seems like a lot of info; let me know if you have any questions!
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How do I display a custom field from taxonomy term in user list in rewritten field
I'm trying to display a list of taxonomy custom field terms next to a user's name. Though when I use a custom function to get the custom field (abbreviation) and then use it in a rewrite it still displays the original term list.

The taxonomy field is field\_awards, the custom field attached to field\_awards is field\_abbreviation.

This is my custom function to display the abbreviation instead of the full term:

```
function ppw_views_view_field__field_awards($vars) {
    $row = $vars['row'];

    $abbr = array();
    foreach ($row->field_field_awards as $record) {
        $abbr[] = $record['raw']['taxonomy_term']->field_abbreviation['und'][0]['safe_value'];

    }

    return (count($abbr) > 0) ? ", " . implode(", ", $abbr) : "";
}

```

In this screenshot my theme shows the output of the function (it is excluded from display), the user's name with the awards field is rewritten into the output.

I've also tried to implement a custom field format in my theme:

```
function ppw_field_formatter_info() {
  return array(
    'ppw_term_reference_plain_abbreviation' => array(
      'label' => t('Plain text Abbreviation'),
      'field types' => array('taxonomy_term_reference'),
    ),
  );
}

function ppw_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // Terms whose tid is 'autocreate' do not exist
  // yet and $item['taxonomy_term'] is not set. Theme such terms as
  // just their name.

  switch ($display['type']) {
    case 'ppw_term_reference_plain_abbreviation':
      foreach ($items as $delta => $item) {
        $name = $item['taxonomy_term']->field_abbreviation['und'][0]['safe_value'];
        $element[$delta] = array(
          '#markup' => check_plain($name),
        );
      }
      break;
  }

  return $element;
}

```

How do I get the abbreviations next to the name? I've been unable to find what function to implement or what theme file to add to get this to work.

# Answer
> 1 votes
I solved my problem by fixing my field formatter (in its own module).

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


# Question
Title: How to create a task which run at cron time and send emails to users?
Is there a module (based on cron) which can be used to check a date value form a field and to send email to users 2 days before the date?

If there is not, how can I implement this to work with cron?

# Answer
Here is how I did without using any custom modules.

I implemented `hook_cron` like that:

```
function HOOK_cron() {
    // search for expiration date interval
    $result = db_query("SELECT my_date, uid, company_name, nid
            FROM my_table
            LEFT JOIN ...
            LEFT JOIN ...
            LEFT JOIN ...
            LEFT JOIN ...
            WHERE my_date BETWEEN DATE(NOW( ) + INTERVAL 6 DAY ) AND DATE( NOW( ) + INTERVAL 20 DAY)")->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $product) {
        $module = 'MY_MODULE';
        $key = 'MY_KEY';

        $from = 'my_email@test.com';

        $user_account = user_load($product['uid']);
        $product_detail = node_load($product['nid']);

        $to_user_mail = $user_account->mail;

        // build the email
        $message = drupal_mail($module, $key, $to_user_mail, LANGUAGE_NONE, array(), $from, FALSE);

        //$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
        $message['headers']['Cc'] = 'cc_email@test.com';
        $message['headers']['Reply-To'] = 'reply_to_email@test.com';

        $message['subject'] = 'THE SUBJECT';

        $message['body'] = array();
        $message['body'][] = 'Dear ' . $user_account->name;
        $message['body'][] = '...';
        $message['body'][] = 'Regards,';
        $message['body'][] = 'YOUR NAME';

        // retrieve the responsible implementation for this message.
        $system = drupal_mail_system($module, $key);

        // format the message body.
        $message = $system->format($message);

        // send e-mail
        $message['result'] = $system->mail($message);
    }
}

```
> 2 votes

# Answer
this module will help you scheduled actions

you can set the cron trigger by rules
> 0 votes

---
Tags: 7, datetime, emails, cron
---


# Question
Title: Organising content using Taxonomy and Views
I'm just starting out with Drupal and I'm interested in how to display my content and organise it in the site.

I can see that creating basic pages I can use the `Menu` module to add them to the hierarchy of the menu, but is this the only way to organise content?

I'm trying to learn the `Views` module, which is complicated! But it seems more logical to me to create a custom taxonomy and then use the `Views` module to display a subsection of that taxonomy.

Is this possible?

# Answer
Yes it is possible. You should learn Panels too. Panels works very nice with Taxonomy and Views. Try lullabot video tutorial about views, very good.
> 2 votes

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


# Question
Title: Add static images to bottom of view page
I have a view called Courses, which outputs an table of college courses. I'd like to add two standalone images to the bottom of the page. Fairly simple really, but I'm not sure how to implement this layout. How can I achieve this?

# Answer
> 2 votes
In your view edit form, find 'FOOTER' (under Page Settins), click 'Add' and select 'Global: Text area'

In the content textarea, add your images markup (e.g. `<img src="http://example.com/some_image.png" alt="This is my image!"/>`), change text format to "Full HTML" and save.

---
Tags: 7, views
---


# Question
Title: How to remove the top, bottom, left... region when theming a node in Drupal 6
After some revise on the template.php, I can theme a node with specific content type. However, could I remove the default region such as header, footer to make it likes a blank page?

# Answer
> 2 votes
I think You need to create specific page.tpl.php for your content and don't include these regions in the template. You name them page--YOUR\_CONTENT\_TYPE\_MACHINE\_NAME.tpl.php according to this thread. You can also try this module

---
Tags: nodes, theming
---


# Question
Title: How to add 1000 nodes of the same content type in just one step?
I need some advice with the following situation:

I have a content type called: "Flats".

I have to add 1000 nodes for this content type.

The only field I need to complete for all of them is the 'title'

I have the 1000 titles in a comma-separated-value format file called: **title.csv**

Is there any way to upload this file and add all the nodes in just one step.

Thanks

# Answer
Feeds module will also allow you to import content/create nodes via CSV.
> 8 votes

# Answer
If it's sample data, you can use the Devel module. If you want to import data that is in some file or db you can use node\_save(). If the data is exported from another Drupal installation, you can use the Node Import module.
> 5 votes

# Answer
You can try Node Import that supports CSV files
> 2 votes

---
Tags: 7, nodes
---


title: gmap macro doesn´t parse.. why?

text:
# Question
Title: gmap macro doesn´t parse.. why?
I have in my contact form something like

\[gmap markers=big red::40.26041912699509,-3.8385844230651855 |zoom=15 |center=40.26217119406393,-3.840494155883789 |width=300px |height=200px |control=Small |type=Map\]

but it doesn´t parse when I put it into the body of a content type

# Answer
You need to create an input filter that uses the GMAP filter before it can work : Go to Administer \> Site Configuration \> Input format \> Add Input Format and select the gmap filter in the filters list
> 1 votes

---
Tags: nodes, google-maps
---


title: Add comments to profiles

text:
# Question
Title: Add comments to profiles
How do you allow users to add comments to your profile page? I'm already using content profile module but I don't know how to add comments to it

# Answer
> 2 votes
Go to admin \> content types, find your content type used as a profile (default is called 'profile') and click edit. Scroll down to the "Comment Settings" fieldset and expand that and choose "Read/Write" and any other comment options you choose and save the content type.

---
Tags: users, comments
---


title: Server Deployment of Economist.com

text:
# Question
Title: Server Deployment of Economist.com
As documented here, it seems the Economist is using Drupal for most of it's site. I am just curious if anyone has information on the number of servers and their config. Any idea?

# Answer
They have 2 Varnish servers, 10 web servers and 4 database nodes (2 master, 2 slave)

Their workflow is Trunk -\> Stage -\> Live, from bzr.

They are fully Drupal for a month or so, now.

See The Economist: An Informal Technical Case Study session video from DrupalCon London for more information on their processes.
> 5 votes

---
Tags: deployment
---


# Question
Title: How do I write NULL values to the database using drupal_write_record?
I'm using drupal\_write\_record to update records in the database in Drupal 6, but it appears to skip null values entered into my integer fields and just leave the old value. I've also tried the string "NULL" with no success. Regular integer values work fine.

```
$record = array(
  'id' => ##my_id##,
  'int_field' => null
);
drupal_write_record('my_table_name', $record, array('id'));

```

How can I change 'int\_field' back to NULL from an existing value?

# Answer
does this patch suite your needs? http://drupal.org/node/227677#comment-4302522
> 1 votes

---
Tags: database
---


# Question
Title: How to access a table I inserted manually into Drupal 7 db
I just inserted a new table into the Drupal db called `mini_table` with my own custom data using only phpmysql. How do I access this table's data for use in my \*.tpl.php files?

**EDIT:** No cause for alarm. All my code is in `template.php` and not in any *\*.tpl.php* file. Just wanted to clarify that.

# Answer
> 2 votes
You shouldn't do a query from a .tpl.php or include any php logic there. If you have to do it in the theme (this would be better in a small custom module), do it in the template.php in a preprocess function (node or page preprocess, depending on what template you want your variable available).

So you do your query in the template.php file and then through a preprocess function send the variable to your .tpl.php files.

I also don't recommend writing MySQL queries in Drupal, you should use the Drupal API for this. Drupal has a database abstraction layer that gives you lots of handy function you can use.

# Answer
> 1 votes
As @ipwa said, you shouldn't perform queries in template files.

If you'd want to access custom data in Drupal 7 I suggest you use the Entity API. It defines a custom entity with it's own schema (table) in the database.

---
Tags: database, theming
---


# Question
Title: how to add cck field to a content type Programatically in drupal 7?
> **Possible Duplicate:**
> Programmatically create Fields in Drupal 7

I want to to add a cck field to a content type Programatically in drupal 7.

Any one who have some idea about this?

# Answer
The main functions of the Content Creation Kit (CCK) have migrated into core in Drupal 7. Now every object used by Drupal (users, nodes, even taxonomy terms) are "fieldable entities." What does this mean? Simply that you can add fields to most objects in Drupal out of the box, no CCK required!

If you're building a module that alters pre-existing node types, you'll need to check out the Entity API. I'm not too familiar with it myself, however, it doesn't seem that hard to programmatically add fields. As Bojan Zivanovic mentioned, there are many other answers dealing with this on Drupal StackExchange, here are a few for you to peruse:

\- Programmatically Creating Fields in Drupal 7

\- Assign Fields Programmatically to Custom Node in Custom Module

If you're just adding fields to nodes for site building purposes, I'd just use the UI.

To do so...

1. Go to the "Structure" menu.
2. Select "Content Types."
3. Click on "Manage fields" next to the content type you want to add fields to.

You should then be presented with an interface to add new fields to your content type, much like you did with CCK in Drupal 6.
> 2 votes

---
Tags: entities, nodes
---


# Question
Title: comma separated cck multivalues in a view
I've created a cck field and called it authors so the machine name is field\_authors. To print this field in a view template, i'm doing this - `print $fields['field_authors_value']->content;` In case is there 2 or 3 values it prints each value on separate line, and i want something like author1, author2, author3. (comma separated)

Tried to do this way in template.php:

```
function mytheme_content_view_multiple_field($items, $field, $values) {
  $output = '';
  switch($field['field_name']) {
    case 'field_authors_value':
      $output .= '<div class="field-item">'. implode(', ', $items) .'</div>';
      break;

    default:
      foreach ($items as $item) {
        if (!empty($item) || $item == '0') {
      $output .= '<div class="field-item">'. $item .'</div>';
    }
      }
      break;
  }
  return $output;
}

```

but it has no effect. What im doing wrong?

# Answer
> 2 votes
Per the following on drupal.org: http://drupal.org/node/1018198#comment-3993646

> You can do this by copying "views-view-field.tpl.php" into your theme's directory, under a name the view will recognize it selectively. Put the following code in it:
>
> > `print preg_replace('/<\/div><div[^>]+>/i', ', ', $output);`

In your case, I think it would be:

> views-view-field--VIEWNAME--field\_authors\_value.tpl.php

---
Tags: views, entities
---


# Question
Title: Difference between field widget price textfield and price with currency?
What is the difference between the widget field *price textfield* and *price with currency* that you can use on the `commerce price field`?

# Answer
The simple explanation is that:

`Price textfield` only allows the user to enter a price, where the currency code is selected in the field setting, where as `Price with currency` allows the user to select both price and currency and you can setup a default currency in the field setting.
> 1 votes

---
Tags: entities, commerce
---


title: Apache Solr support for custom entities

text:
# Question
Title: Apache Solr support for custom entities
Does apache solr module supports the indexing of fields attached to custom entities?

# Answer
If you want to get an easy to use search, you should consider using Search API where you can use a Solr backend and index entities, fields and even relations to other entities.

The apache solr module is more an API to Solr then a ready made search engine (though the module does offer some various search addons), which means you can index whatever you like, but you might need to write some code for custom entities.
> 0 votes

---
Tags: search, entities
---


title: Using a panel for the homepage?

text:
# Question
Title: Using a panel for the homepage?
I am building a site in Drupal and I'm using the `Panels` module to create my page layouts. I have created the layout that I would like for my homepage and created the content that I'd like in there.

I have set it to 'promoted to homepage' yet, when I visit the homepage, I just get the title and submitted date, and a read more link. The layout isn't being seen, you have to click through in order to see the page.

How can I turn off the 'read more' link and use the panel as the homepage?

# Answer
> 2 votes
Visit `admin/config/system/site-information`, and set the panel's path as the default home page.

---
Tags: 7, panels
---


# Question
Title: Default views argument that can't be overriden?
I have an argument comparing the current user ID to a field to determine what nodes to show, but all you have to do to impersonate another user is enter the argument in the address bar thus circumventing my default value. Is there a way to make an argument only ever use the default value and not exist as far as the address bar is concerned?

# Answer
> 1 votes
If the "User: Current" filter is not an option for you, then you can use a hook\_views\_pre\_execute() to modify the argument before the query is run.

In your custom module (assuming you have one argument):

```
function mymodule_views_pre_execute($view) {
    switch($view->name) {
        case 'name_of_view':
            global $user;
                if ($view->arg[0] != $user->uid) {
                    $view->build_info['query_args'][0] = $user->uid;
                }
            break;
    }
}

```

Even if a different argument is supplied in the URL, the current user's id will still be fed back into the view.

---
Tags: 6, views
---


title: Drupal select module

text:
# Question
Title: Drupal select module
I am writing a module that contains two drop-down lists that are retrieved from a database:

* DDL 1: Region
* DDL 2: Territory

When I choose a region, I need it to have its own territory.

```
function alter_territory(&$form, &$form_state) {
    $territory_options = array();
    $territory_options = filter_territories($Region);
    $form['name']['Region']['#ajax'] = array( 'event' => 'change',
    'wrapper' => 'territory-wrapper',
    'callback' => 'filter_territories_callback',
    'method' => 'replace', );
    $form['name'][''territory']['#prefix'] = '<div id="'territory-wrapper">';
    $form['name']['territory']['#suffix'] = '</div>';
    $form['name']['territory']['#options'] = $territory_options;
}

function filter_territories_callback($form, $form_state) {
    $Region = $form['name']['Region']['#value'];
    $form['name']['territory']['#options'] = filter_territories($Region);
    return $form['territory'];
}

function filter_territories($Region) {
    $select = oci_parse($conn,select code,descr1 from db.table1 where code = $city);
    oci_execute($select);
    $territory = array();
    while ($row = oci_fetch_array($select,OCI_ASSOC)) {
        $territory[$row['CODE']] = $row['Desc1'];
    }

    return $territory;
}

```

What could make the code work incorrectly?

# Answer
```
function filter_territories($Region) {
  $select = oci_parse($conn,select code,descr1 from db.table1 where code = $city);
  oci_execute($select);
  $territory = array();
  while ($row = oci_fetch_array($select,OCI_ASSOC)) {
    $territory[$row['CODE']] = $row['Desc1'];
  }

  return $territory;
}

```

The first argument passed to `oci_parse()` is a variable that is not passed as argument, nor is it declared as global variable; that variable is not containing any useful value for the function.
The second argument of that function should be a string, which is not what you are passing; it's probable that you are getting a syntax error there. The argument passed to the function is not used.

```
$form['name'][''territory']['#prefix'] = '<div id="'territory-wrapper">';

```

The string `''territory'` is using two delimiters; it's probable that PHP is reporting a syntax error, there too.

The correct line should be the following one.

```
$form['name']['territory']['#prefix'] = '<div id="territory-wrapper">';

```

```
function filter_territories_callback($form, $form_state) {
  $Region = $form['name']['Region']['#value'];
  $form['name']['territory']['#options'] = filter_territories($Region);
  return $form['territory'];
}

```

From the shown code, the function is returning a part of the form that has not been defined. The form defines `$form['name']`, not `$form['territory']`.

I think you are not showing all the code; if you did show all the code you are using, then the `alter_territory()` function is not correctly named, which is a problem if that function is a hook implementation.
> 1 votes

---
Tags: 7
---


# Question
Title: How do I create a page consist of more than 100 lines, by custom module?
I created a page which consist of HTML tags. The code for that is the following one:

```
function mynewpage_menu() {
  $items['mypage'] = array(
    'title' => 'my page title',
    'page callback' => 'mypage_page',
    'access arguments' => array('administer page'),
  );
  return $items;
}

function mypage_page() {
  $output='html code here';
  return $output
}

```

Is it the right way to generate a page if i have more than 100 lines? What if I have *iframe* , *img* and *canvas* tags and what if I want to include paths and hyper references?

In what other ways can I generate a page containing 100 HTML tags?

**Update:**
Am I right in associating mynew-page.tpl.php with the following theme function?

```
function mymodule_theme() {
  return array(
    'mypage' => array(
      'variables' => array('account' => NULL),
      'template' => 'mynew-page',
    ),
  );
}

```

# Answer
There isn't a limit on the number of lines returned by a page callback, or on the number of tags it can return.
If the output is getting complex, it's rather better to separate the code into different theme functions; for example, for outputting a link there is l(), for outputting an image there is theme('image'), and for outputting a table there is theme('table'). The first rule is to reuse the existing functions.

In Drupal 7, a page callback can also return a renderable array, such as the following one returned by tracker\_page():

```
  $page['tracker'] = array(
    '#rows' => $rows,
    '#header' => array(t('Type'), t('Title'), t('Author'), t('Replies'), t('Last updated')),
    '#theme' => 'table',
    '#empty' => t('No content available.'),
    '#attached' => array(
      'css' => array(drupal_get_path('module', 'tracker') . '/tracker.css' => array()),
    ),
  );
  $page['pager'] = array(
    '#theme' => 'pager',
    '#quantity' => 25,
    '#weight' => 10,
  );
  $page['#sorted'] = TRUE;

  return $page;

```

In these cases, the page callback doesn't return any HTML tags. This is also the preferred method, in Drupal 7, as it allows to the other modules to easily change the output of another module.

As alternative, you can use a template file for rendering the output. In this case, you need to:

* Define a theme function that uses the template file; that is what is done from the Node module for theme('node'), which is defined in node\_theme() using the following definition (Drupal 7):

```
'node' => array(
  'render element' => 'elements',
  'template' => 'node',
),

```
* Optionally create a preprocess and/or a process function for the template, their purpose is to add variables to the ones that are passed to the template file. In the case of the Node module, those functions are template\_preprocess\_node() and template\_preprocess\_node().
* Invoke the theme function to produce the output. In the case of `theme('node')`, this is done as in the following code:

```
// Drupal 6.
return theme('node', $node, $teaser, $page);

// Drupal 7.
$build += array(
  '#theme' => 'node',
  '#node' => $node,
  '#view_mode' => $view_mode,
  '#language' => $langcode,
);

```

**Update**
This is a common error: The template file name and the theme name must not be different; the only difference can be between using hyphens and using underscores. For the rest, the theme name and the template filename must be the same, which means that "mypage" as theme function and "mynew-page" as template filename don't work; if you are going to use "mynew-page" as template file, then the theme function must be `theme_mynew_page()`, reported in the theme definition as "mynew\_page."
> 2 votes

---
Tags: 7
---


# Question
Title: Drupal doesn't detect my MySQL installation
Does Drupal 7 use some special libraries for MySQL?
I tried to install the 7.8 version, and the only option for the database I have is "SQLite."

I am running Drupal 6 on the same server, and it works fine. I am using PHP 5.2.8, and MySQL 5.1.38.

Do I need any additional library?

# Answer
> 9 votes
You need to have the PDO driver for MySQL installed for Drupal 7. This is indeed different from Drupal 6. Instructions are at http://drupal.org/requirements/pdo. I hope those instructions are sufficient for you.

---
Tags: database, installation
---


# Question
Title: How could I send daily or weekly email in cron() function?
I have a content type in which I have drop down list with the values of "daily" and "weekly" and one field is of email. I want to setup the cron function like when the value of that drop down list is "daily" then email will be send daily to the email address of whatever entered in the email field and when the value is "weekly" then the email will be send weekly.

I don't have any idea about this. How will I do this?

# Answer
How are you generating your email? It sounds to me like you need a custom module that implements `hook_cron`. It would have to save the email address and send\_interval to it's own table (or you'll have to build a query to select the email and interval from wherever you've stored it) in the database during `hook_nodeapi` with the update $op and/or the insert $op. I recommend creating a 3rd column in your table with a date for the last time email was sent. That way if cron gets interrupted it can continue where it left off. Use a sql query to select all of the rows with column interval == daily and date \< NOW() and send emails out. Then do the same if the date is a Sunday or whenever you want to send weekly emails for those. As you process a row, update the date field to the current time which indicates the email was sent.

If you're not up for custom development, you may want to see if the notifications module suites your needs.
> 2 votes

# Answer
use the module simplenews and schedule your emails, you don't need programming for that or use triggers and input the time as your variable
> 0 votes

---
Tags: emails, cron
---


title: Migrating user data

text:
# Question
Title: Migrating user data
I am trying to migrate user data. There aer around 500 users that needs to be migrated. Problem is that these 500 users are registered in old site and i cant just insert these to new DB as new users are registered so uid of new user and these 500 users will collide , to avoid these i wrote a script to read all these data again and using user\_save i am re inserting them , but the problem is

```
$new_user = array(
        'name'   => $row[name],
        'mail'   => $row[mail],
        'pass'   => $row[pass],
        'status' => $row[status],
        'init'   => $row[init]
    );

```

Here 'pass' is already md5 so when saving using `$account = user_save('',$new_user);` it is md5 hashed again ! Is there a better way to do this ?

# Answer
> 2 votes
I'm not sure if there is a drupal way of doing this that does not use md5.

My first thought is to save the user w/o a password. The user object should then have a uid which you can use in SQL to insert the existing hashed password into the user's password field.

```
db_query("UPDATE {users} SET pass ='%s' WHERE uid = %d", pass, $new_user->uid);

```

---
Tags: 6, users, migrations
---


# Question
Title: How to create custom 403 page for a particular content type?
For a particular content type in my Drupal 6 web site, I do not want the users to see the "access denied" message when viewing an unpublished node. Instead I want to show a more meaningful message. I have tried various modules like http://drupal.org/project/customerror, but I can't find a way to restrict the message for only a single content type. There is a similar question here http://drupal.org/node/888312.

Do you have any suggestion on how this could be achieved?

# Answer
Try looking at the Custom 403 module, or the Teaser 403 module .

> ### Custom 403
>
> This module provides helpful messages to users when they encounter a 403 (Access Denied) page. Depending on different role(s) permissions set on the specific node or content type, the administrator can specify messages accordingly. The user who encounters the 403 will obtain more specific information on how to obtain the role(s) required to access the node.

> ### Teaser 403
>
> This module is designed to expose teaser content for sites which normally require users to login to view nodes.
> 1 votes

---
Tags: 6, nodes
---


# Question
Title: How does a Rule access a variable defined in the event info?
I'm looking at the Drupal Commerce module in Drupal 7, and it has a Rule to send an email notification that the order was completed after checkout. Perusing the code in commerce\_checkout.rules.inc, the `hook_rules_event_info()` has a variable of type `commerce_order()`.

How does Rules retrieve the tokens and the `$order` object? Or how does the Commerce Order module define a variable type to use with Rules?

# Answer
I was looking in the wrong place and thought about how Rules work the wrong way. The event for when an Order entity is part of the Rule is triggered by the Commerce module on checkout.

```
rules_invoke_all('commerce_checkout_complete', $order);

```

And for the other entities, Rules already takes care of most by invoking events from its events.inc.
> 1 votes

---
Tags: 7, rules, commerce
---


# Question
Title: Select all nodes that reference the current node
I'm new to Drupal and am wondering if anyone could provide direction on this.

Basically I have 2 content types - one called 'clinics' and one called 'clinic groups'. Each 'clinic' has a node-reference to a 'clinic group' node. What I'm trying to achieve is basically, if I'm on the 'clinic group' page - I'd like to pull back all the nodes 'clinics' under it, that reference it.

Is this possible in views?

Thanks everyone.

# Answer
You could do this using views.Create a view where under

```
Fields you select your group as Node, Under that choose Title.

For Filters select Node Type, Operator: Is one of and select Clinic content type.

Under Arguments select your group as Content. Under that choose Clinic_group (the node reference field).

```

You can add additional parameters to your view like Number of items to display, more fields like Node: Body and maybe a filter that Node: Published, select yes.

To see a preview, under live preview give the arguments as node number and click Preview.

Hope this helps!
> 1 votes

# Answer
Not sure if it works with Views by itself, but the Node Relationships module uses customized views for output.
> 0 votes

---
Tags: nodes
---