# Question
Title: How to deny access to invalid $_GET parameters
For example, there is a pager with 10 pages. How to deny access if $\_GET\['page'\] is bigger than 9 or is not numeric?

# Answer
There's no 'catch-all' method for this sort of thing, but on an individual basis you would probably want to perform a manual check in `hook_init()` in a custom module:

```
function MYMODULE_init() {
  if (isset($_GET['page'])) {
    if (!is_numeric($_GET['page']) || $_GET['page'] > 9) {
      drupal_access_denied();
    }
  }
}

```

I imagine you'll need to add further conditions to the above code to make it more contextual to your specific situation.

**EDIT**

As MPD mentions it might be better to use `drupal_not_found()` in place of `drupal_access_denied()`...it's a better semantic representation of what you're actually doing.
> 2 votes

---
Tags: security
---


title: TinyMCE doesn't affect on nodes

text:
# Question
Title: TinyMCE doesn't affect on nodes
I've installed TinyMCE editor but when I change font style or anything else, I don't see any change in the published node. what should I do?

# Answer
> 1 votes
By default filtered html does not include text color and background color (No class or style or javascript attr) so be sure you choose full html not filterd html

# Answer
> 1 votes
Check to ensure the content has full HTML input filter, it may be that even though the source includes the customised html inserted by TinyMCE upon save it is all being stripped out.

---
Tags: 7, wysiwyg
---


title: Missing image file previews with Media

text:
# Question
Title: Missing image file previews with Media
I'm not sure if that was me messing around with Media, or is it Media's fault by de\**fault*\*. I'm using that module mainly for its ability to re-use uploaded media, but for some reason I cannot get the images real preview. What is the crucial setting to have an image file display its preview in the library and in the content type editor?

I must say with more and more experience using Drupal, I'm still perplexed when it comes to configuring Media file types and display options. Seems like one could fall into an endless loop when trying to manage files' display options.

# Answer
OK, the answer is: I turned off the view mode named "Preview" in Media. As it turns out, the name is strongly recognized by the plugin and restoring the mode brought back the preview thumbnails. Thanks to Devin Carlson for providing support on that.
> 0 votes

# Answer
Are you saying that the thumbnail images for file uploads aren't displaying (a broken image icon the browser)?

If so, depending on how you installed Drupal ... drupal (well your webserver) needs to own the /sites/default/files/styles directory, or else drupal cannot create thumbnails for preview on-the-fly.

This is a known Issue: theme\_image\_style\_preview() and image\_requirements() should check whether style directories are writable.
> 2 votes

# Answer
It may depend on your file system configuration (admin/config/media/file-system). If your site uses "private" file system you may meet Media "Known Issues" case.

If you have installed and use any other "stream wrapper" (you can see it in the list of choices in Download method section on the config page mentioned above), you may meet Image module problem - it can use either "public", or "private" file system for image styles.
> 0 votes

---
Tags: media
---


title: Browser specific javascript inclusion

text:
# Question
Title: Browser specific javascript inclusion
It seems like the browser conditionals:

```
  drupal_add_js(drupal_get_path('module', 'cufon') . '/js/cufon-drupal.js',
 array('group' => JS_THEME, 'browsers' => array('IE' => 'gte IE 9', '!IE' => TRUE),
'weight' => 999, 'preprocess' => FALSE));

```

included in template.php (or a module) are not working due to the fact `browsers` option is supported for `drupal_add_css()` but not for `drupal_add_js()`.

Can one state a not-hackish/patchy solution to exclude this file `cufon-drupal.js` on older browsers?

A solution like

```
<!--[if gte IE 9]>
<script src='<?php drupal_add_js(drupal_get_path('module', 'cufon') . '/js/cufon-drupal.js'); ?>'>
</script><![endif]-->

```

in html.tpl.php is not working.

# Answer
> -1 votes
Seems like there is a non-drupal solution:

```
if(jQuery.browser.version.substring(0, 2) != "8.") { alert("not ie8"); }

```

It is not very handy as I have to paste inside the brackets the content of cufon-drupal.js content.

---
Tags: javascript
---


# Question
Title: drupal_is_front_page() fails when using alias
If I set the default front page to use a node with an alias, e.g. 'home', `drupal_is_front_page()` fails as it compares the un-aliased path (`$_GET['q']`) with the value of the 'site\_frontpage' variable. Would it not be better to save the 'site\_frontpage' variable as un-aliased path, or am I missing something?

Sorry, this is actually what happens. The variable must have been set to 'home' by something else.

# Answer
> 3 votes
`drupal_is_front_page()` compares the content of the "site\_frontpage" variable with an un-aliased path because the content of that variable is set to an un-aliased path, on the page at admin/config/system/site-information.

In system\_site\_information\_settings(), the form builder for that page, the content of the "site\_frontpage" field is set using the following code:

```
'#default_value' => (variable_get('site_frontpage') != 'node' ? drupal_get_path_alias(variable_get('site_frontpage', 'node')) : ''),

```

In system\_site\_information\_settings\_validate(), the form validation handler for that page, the value of the "site\_frontpage" field is set using the following code:

```
  if (empty($form_state['values']['site_frontpage'])) {
    // Set to default "node".
    form_set_value($form['front_page']['site_frontpage'], 'node', $form_state);
  }
  else {
    // Get the normal path of the front page.
    form_set_value($form['front_page']['site_frontpage'], drupal_get_normal_path($form_state['values']['site_frontpage']), $form_state);
  }

```

What is being saved in the "site\_frontpage" variable is the normal path (a.k.a. the un-aliased one). It is the correct what `drupal_is_front_page()` does.
If there is a module that set the value of that variable to a path alias, then the code of that module should be changed, as that module is not working with the actual Drupal code.

---
Tags: uri
---


# Question
Title: Drupal ignores my table definition when installing a module
What am I doing wrong? This is what I have in commerce\_xpay.install.

```
function commerce_xpay_schema() {
    $schema = array();

    $schema['commerce_xpay_ipn'] = array(
            'description' => 'Stores processed IPNs.',
            'fields' => array(
                    'ipn_id' => array(
                            'description' => 'Serial numeric ID of the IPN in the local database.',
                            'type' => 'serial',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                    ),
                    'transaction_id' => array(
                            'description' => 'The X-Pay transaction ID.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'terminal_id' => array(
                            'description' => 'The X-Pay terminal id',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'response' => array(
                            'description' => 'The response of the server',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'payer_email' => array(
                            'description' => 'The e-mail of the payer.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'transaction_date' => array(
                            'description' => 'The date of the transaction.',
                            'type' => 'date',
                            'not null' => TRUE,
                    ),
                    'card_type' => array(
                            'description' => 'The type of the card used in the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'amount' => array(
                            'description' => 'The amount of the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'transaction_type' => array(
                            'description' => 'The type of the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'mac' => array(
                            'description' => 'The amount of the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'currency' => array(
                            'description' => 'The currency used for the transaction.',
                            'type' => 'varchar',
                            'length' => 255,
                            'not null' => TRUE,
                            'default' => '',
                    ),
                    'order_id' => array(
                            'description' => 'The order ID the payment belongs to.',
                            'type' => 'int',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'txn_id' => array(
                            'description' => 'The payment transaction ID the payment belongs to.',
                            'type' => 'int',
                            'unsigned' => TRUE,
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'created' => array(
                            'description' => 'The Unix timestamp when the IPN was received.',
                            'type' => 'int',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'changed' => array(
                            'description' => 'The Unix timestamp when the IPN was last updated.',
                            'type' => 'int',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'test_ipn' => array(
                            'description' => 'Boolean indicating whether or not this was a test IPN sent by the Sandbox.',
                            'type' => 'int',
                            'size' => 'tiny',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
            ),
            'primary key' => array('ipn_id'),
            'foreign keys' => array(
                    'order_id' => array(
                            'table' => 'commerce_order',
                            'columns'=> array('order_id' => 'order_id'),
                    ),
                    'txn_id' => array(
                            'table' => 'commerce_payment_transaction',
                            'columns'=> array('payment_id' => 'payment_id'),
                    ),
            ),
            'indexes' => array(
                    'transaction_id' => array('transaction_id'),
            ),
    );

    return $schema;
}

```

# Answer
> 3 votes
It's hard to know without seeing an error message, but at first glance I'd guess it's because of the `transaction_date` column.

`date` is not a valid data type in Drupal 7 (see Data Types). You can either use an `int` column and store a UNIX timestamp, or use the `mysql_type` property instead of `type`, and set that `datetime`.

---
Tags: 7, hooks, database
---


# Question
Title: Where do I put image style definition in a module?
I'm writing a custom node formatter that needs to use a certain image style. Since I don't want to rely on that image style being defined by the admin, and I want to be sure the style is not deleted, I am going to provide the style definition in code.

Should MYMODULE\_image\_default\_styles go into the .install or .module file?

# Answer
Most of the hook implementations go in the module file, not the in the installation file.

Hooks that needs to be in the installation file are, for example, `hook_install()`, `hook_requirements()`, `hook_schema()`, and `hook_uninstall()`.
hook\_image\_default\_styles() needs to be in the module file, or the file that hook\_hook\_info() reports to contain that hook implementation.

image\_image\_default\_styles(), for example, is contained in the image.module file.
> 0 votes

# Answer
I think its better to use features and export it, then in your .info file add dependency to it.

other solution is what you say, put it inside MYMODULE\_image\_default\_styles in your .module and re-install your module to make it locked in admin
> 0 votes

---
Tags: hooks, media
---


# Question
Title: What's good form for calling views within a module (template, etc)?
I have about three views that will be used; Here's Daniel Wehner's answer:

```
 $view = views_get_view();
 $view->set_display();
 $view->filter['foo']->value = 'bar';
 print $view->preview($display_id, $args);

```

I built this based off his code, which while works, could be improved if including views is going to be a regular activity throughout your project:

```
$view = views_get_view('nodequeue_3');
$view->set_display();

$content['raw_markup'] = array(
  '#type' => 'markup',
  '#markup' => $view->preview(),
);

```

I'm also thinking this might not be done that often, because if you can build a module, why use views?

The utility of views should not be overlooked, in combination with (or without) a custom module.

Thanks for the patience, this community is awesome!

# Answer
I prever to use this small helper function:

```
function mymodule_embed_view($view_id, $display_id, $arguments) {
    $view = views_get_view($view_id);
    $view->set_display($display_id);
    $view->set_arguments($arguments);
    $view->pre_execute();
    $view->execute();
    return $view->render();
}

```
> 1 votes

---
Tags: views
---


title: Setting up an features server?

text:
# Question
Title: Setting up an features server?
I've found dev seed's article on this issue: http://developmentseed.org/blog/2009/sep/03/5-minute-feature-server/

Is it the same process for Drupal 7?

# Answer
> 2 votes
I don't think there is a D7 of the feature server but you can host your D7 specific features on a D6 feature server.

---
Tags: features
---


title: "An illegal choice has been detected"

text:
# Question
Title: "An illegal choice has been detected"
I have an image field attached to a content type created. When I upload images to it, it gives me an error "an illegal choice has been detected please contact sight administrator." I get this error when uploading images only on this content type.

I cleared watchdog entries, form and image cache tables; it started working again, but when I create a second page, the problem shows again.

How can I avoid this error?

# Answer
> 2 votes
I found the answer here.

The required field radio button was not selected, when the image was uploaded. It seems an error with the form validating when the image is uploaded.

---
Tags: 7, forms
---


# Question
Title: How to redirect a user to his own content after log in?
I want to redirect a user after log in to his own content.For example lets say a user created a node/3.After log in I want to redirect the user to node/3.How can I do that with rules or with something else?

# Answer
> 1 votes
To list the contents of a ( the current) user you can set-up a view and add a filter ar URL argument. To redirect the user to this view after login you can use rules.

# Answer
> 0 votes
Edit: Ah, I misread the question. BetaRide's answer is good. I would just add that the action you will want in Rules is `Page redirect` (under System).

---
Tags: rules, redirection
---


# Question
Title: How can I determine if a form exists in my Drupal installation?
I have a form with a simple textfield where the user enters a string. I want to check if this string is a valid form\_id in the website. I thought about using the drupal\_get\_form but even if it would work, it would be kind of an overkill to retrieve the whole form array just to check if it exists.

Any ideas are more than welcome.

# Answer
Since the 'ID' you pass to `drupal_get_form()` is actually the name of a PHP function, the simplest way to see if it exists is using plain old PHP:

```
if (function_exists('form_id')) {
  // ...
}

```

If you need to check that the return from the function is a suitable Drupal form array, you'll need to use one of the methods described by MPD.

This will only work for forms for which the name is explicitly defined as the string you're passing in; i.e. forms whose root function is provided by a `hook_forms()` implementation will not match using this method.

It's worth bearing in mind that with whichever method you use, any form you're trying to identify will have to exist in a file that's included in the current page request. With that in mind it might be wise to keep all the form functions in question in the `.module` file of an enabled module, which will always be included.
> 5 votes

# Answer
When tasked with this like this, your best place to start is the API function that you know about, and start working backwards though the code until you find what you need.

Take a look at the code for `drupal_retrieve_form`, which gets called from `drupal_build_form`, which gets called from `drupal_get_form`. You should be able to clone/modify that for your needs.

Personally, though, I suspect I would just call `drupal_retrieve_form` and see if I get back something valid.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Omit the Front Page when Using Contextual Filters?
Content on my site is set up via taxonomy term, and I've created a view using contextual filters which does a fabulous job of sorting all the content to the appropriate page.

However, on the front page we want to present that content differently, so I have created a block which presents anything marked "front" to appear inside it.

The two are mutually exclusive, as I have filtered the data so that ONLY front page stuff appears in the block, and NO front page items appear in the page view.

This is problematic, however, as some of these highlighted items should appear on other pages in the Web site. Removing the 'exclude home' filter from the page view, however, makes the page view of items marked "front" appear beneath the block, which we don't want.

In order to get the content on the home page AND elsewhere content owners are required to enter the data twice -- unless I can get this fixed.

Any ideas?

Thanks!

# Answer
> 0 votes
First : NEVER enter data twice. You're sure you'll regret it sooner or later, and it's always the sign something's wrong with the design.

As for your problem, you could probably set up a Views Attachment or a plain other view to add nodes with different criteria.

Or perhaps you could use Flag or another module of that kind to differenciate your nodes more precisely ?

---
Tags: blocks, views
---


title: Filter a view by the value of a field

text:
# Question
Title: Filter a view by the value of a field
I have just started using Drupal (Drupal 7) and I would like your help to do something. I have created a field called : Current Project where each user writes the project they are currently working on. I want to create a view in each user's profile page that will show all the other users that work on the same project. I tried to create this using the Views module but I can only insert a specific value as a filter. What I would like to do is to create a view that will show all users that have the same Current project as the viewed user. Thank you very much for your help.

# Answer
I don't think that's the best way to make this but here is an quick and dirty way :

* Create your view and instead of using filter Click advanced and add contextual filter , then chose your field.
* enable the PHP filter in modules
* Create a block in admin/build/block and chose php filter there you will embed the php code below
* now you have to load the profile of current user profile for this use this function, there you will find the current working project field and pass it to the views (I suppose that you added this field in profile 2) : $path = drupal\_get\_path\_alias($\_GET\['q'\]); $path = explode('/',$path); // if the position of viewed user id in the path is 1 $uid = $path\[1\]; $current\_user = profile2\_load\_by\_user($uid); //make print\_r($current\_user) to find your field of project currently working on $arg = $current\_user\["main"\]-\>your\_custom\_field\["und"\]\["value"\]; // if I remember print views\_embed\_view('your\_view\_machine\_name','your\_view\_display\_machine\_name',$arg);

//to find out the machine name of your view hover over its ling and you will see then name in the link below

This solution is for just one argument , if you have multiple field value (more than one current project) you will have to select mut pass arguments like this :

foreach ($current\_user\["main"\]-\>your\_custom\_field\["und"\] as $record) { $values\[\]= $record\["value\]";
} $args =implode('+',$values); views\_embed\_view('your\_view\_machine\_name','your\_view\_display\_machine\_name',$args);

Hope this will help
> 1 votes

---
Tags: views
---


# Question
Title: Menu block is not being displayed on the front page
I'm using the Menu Block content type to provide a list of the secondary level menu items down the left hand side of the website.

it works perfectly other than on the front page where I can't seem to make the menu Block display.

I'm using a Theme heavily based on Bartik (just with logos and colours changed), I can't find a specific front page template and have no idea what else to do.

I have changed the site configuration to use a basic page as the Home Page (but with this or the default home page it still doesn't work.

Anyone got any suggestions please?

Dave

# Answer
> 3 votes
This sounds like a bug that I ran into myself and has been brought up here: http://drupal.org/node/1468420 (submenus of a parent menu item that links to the front page (`<front>`) do not show when viewing the site's front page). At the time of writing the bug has not been fixed, but there are 2 workarounds that might help you out:

1. Set the menu link with the `<front>` path to 'show as expanded'.
2. Do not use `<front>` as the menu link path, but instead use your actual front page path (same as in 'admin/config/system/site-information').

---
Tags: blocks
---


# Question
Title: Generating hierarchic URI's based on taxonomy
I was wondering whether it is possible to have a taxonomy whose URL's are based on taxonomy. Example: I have a taxonomy list called 'Gallery type' which exists of the following items in which 'Pictures' and 'Movies' are higher in the hierarchy than the subitems:

pictures

* pictures-2009
* pictures-2010
* pictures-2011
* pictures-2012

movies

* movies-2009
* movies-2010
* movies-2011
* movies-2012

I also have a (gallery) content type in which it is obliged to select an item from the taxonomy list (actually a submitter should select two items: one main item and one subitem (e.g. 'pictures' AND 'pictures-2012'). Then I have made a view for every item in the taxonomy list so that every taxonomy term is a page that contains links to the pages that are created with the term as obliged option (I know that this is hard to follow, but please bear with me)

Example: I create a new gallery named 'Animals' and select the options 'pictures' and 'pictures-2012'. This gallery 'Animals' will be visible on the corresponding views, i.e. `/pictures` AND `/pictures-2012`. The page its URI however will be /content/animals. My question is then if it is possible to make the URI follow the hierarchy posed in the taxonomy. In this case it would be: `/pictures/pictures-2012/animals`

If anything is not clear, please do tell me! English is not my mother tongue, so forgive me if it contains a lot of syntactic and/or grammatical errors!

# Answer
> 1 votes
From the comments, this is one way how I would do this:

1. create a taxonomy vocabulary called gallery type.
2. create a taxonomy vocabulary called year.
3. populate them with the appropriate terms.

Then I'd create a view:

1. filter it on gallery type (or whatever content types are tagged by the above vocabs)
2. also filter it on all nodes that are published

In arguments (d6) or contextual filters (d7) I'd put in two arguments. They would be taxonomy terms and you can select them from the dropdown list from taxonomy:

1. For the first, select taxonomy term and then in validation, select taxonomy and term again and restrict it to the gallery type vocabulary.
2. For the second select taxonomy term and then in validation, select taxonomy and term again restrict it to the year vocabulary.

Then, in the Fields, select whatever fields you want displayed. For ease here, just select node title, but once in production I'd imagine they'd be title, a picture or image or two, a description, etc.

Now, create a page display in the view, and in the path enter

myfirstview/%/%

Change `myfirstview` to whatever makes sense on your website's hierachy. What the two `%`'s do is substitute in the taxonomy terms above.

Save everything.

Now you have created a View that does all that hierarchy for you. So, if someone goes to...

www.yourhost.com/myfirstview/movies/2009

...Views will create the page for you and display the title of whatever content has been tagged with both `movies` and `2009` (views takes the hardcoded myfirstview and substitutes in the movies and 2009 and then matches them against what content is tagged with those terms) and if they went to...

www.yourhost.com/myfirstview/pictures/2012

...Views would create a page of all pictures from 2012 doing the same logic.

What is nice is that you can then create a views that filter on only one of the vocabularies, eg,

www.yourhost.com/mysecondview/pictures

that would list all pictures

or

www.yourshost.com/mythirdview/2012

that would list all content from 2012

As you get more comfortable with Views you can then add all kinds of different sortings, eg, sort by posting or last edit date, sort alphabetically by title, etc, but this should get you on your way. Just play around with the settings and hit Preview a lot. You'd be amazed how simple it is once you get past the up front daunting nature of all the various options you have.

---
Tags: taxonomy-terms, uri
---


# Question
Title: Is there a way to add a button to my form that does not submit the form but performs a mini validation and adds more inputs to the form
In my module's admin configuration page, I have a simple textfield that needs to be filled out before any other input of the form even appears. I thought that this could be done by adding a small button next to the textfield that, when pressed, will perform all the validation that I need (I have already created the functions that will be used) and then additional "select" form elements will be generated. Anyone knows how I can do this?

# Answer
1. You can use `#limit_validation_errors` to limit the fields validated when a form is submitted with the button you add.
2. If you set `$form_state['rebuild']` in the validation handler you add for the button the form will be rendered again instead of being submitted.
3. Then all you have to do it add some logic to the form that will display the extra fields. This can be done with the data in the `$form_state`.
> 4 votes

# Answer
if its not too complicated business logic you can look into the `#states` value for FAPI elements. See this is article as an example.
> 1 votes

---
Tags: 7, forms
---


title: Cash on delivery extra fee

text:
# Question
Title: Cash on delivery extra fee
I use cash on delivery payment method. When the user select this payment method an extra fee should be added to the order total. NOT to the product line items. Any ideas? I read i a post that a workaround for that is to add a custom line item and charge it the extra fee. Anyway I didn't understand how i should that

I put this code to my custom rule action in order to add a price component via a line item. The problem is it throws an error when i finally save the order in the last line. The error is:

```
Warning: Invalid argument supplied for foreach() in commerce_price_components_combine() (line 972 of /Users/Sakis/Sites/Under_Construction/e-wireless/profiles/commerce_kickstart/modules/commerce/modules/price/commerce_price.module).

$default_currency_code = commerce_default_currency();
if ($balance = commerce_payment_order_balance($order)) {
   $default_currency_code = $balance['currency_code'];
}
$line_item = commerce_line_item_new('cod_fee', $order->order_id);
dsm($line_item,'line_item');
// Wrap the line item and order to simplify manipulating their field data.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
$line_item_wrapper->line_item_label = 'Αντικαταβολή';
$line_item_wrapper->quantity = 1;
$line_item_wrapper->commerce_unit_price->amount = '200';
$line_item_wrapper->commerce_unit_price->currency_code = $default_currency_code;
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
    $line_item_wrapper->commerce_unit_price->value(),
    'cod_fee',
    $line_item_wrapper->commerce_unit_price->value(),
    TRUE,
    FALSE
);
commerce_line_item_save($line_item);
// Add it to the order's line item reference value.
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order.
$order_wrapper->save();

```

# Answer
> 1 votes
If you create the COD payment method yourself you can in the code that would normally process payments ect. add the fee to the order by adding a line item to the order. You could use a custom price formatter instead of showing the line item.

I have answered how add a line item in code here.

---
Tags: 7, commerce
---


# Question
Title: Error When Create Drupal Commerce Product Display
I have managed to create a product type and import my product data, so I now have a list of products. then i follow ryan szrama instruction http://drupalwatchdog.com/1/1/building-commerce-product-display

After that i get this error. EntityMetadataWrapperException: Unknown data property commerce\_product. in EntityStructureWrapper-\>getPropertyInfo() (line 339 of C:\xampp\htdocs\drupal7\modules\entity\includes\entity.wrapper.inc).

what i should do??

# Answer
This in a known bug, you should either start fresh or use the Commerce repair. The problem is most likely that a field that was expected wasn't installed properly. This could happen if you add `hook_line_item_info` to a module that's enabled.
> 2 votes

---
Tags: commerce
---


title: Drupal Commerce Line Item Revisions

text:
# Question
Title: Drupal Commerce Line Item Revisions
Has anyone seen a module capable of providing line item revisions? I am calculating the cost of a custom line item type via rules. It is essentially a booking and may need to be altered in the future.

I am therefore looking for some information from anyone who may have had a similar issue? This is what I need.

1. Every time I recalculate the price of a line item on an order to create a new revision.
2. Always display the latest revision to the user.
3. Provide a view showing other revisions in the admin panel.

# Answer
The line item entity doesn't have revisions, so you would need to add this for all line items. Which means, you need to alter some of the very core of Drupal Commerce. It's possible, but maybe it would be better to store bookings in a custom table and save a reference on the line item instead.
> 1 votes

---
Tags: commerce, nodes
---


# Question
Title: How to migrate custom user fields to Drupal 7?
I would like to migrate custom user fields from an external USER database table to the custom tables of Drupal 7.

I created custom fields for my users (First Name, Last Name, ...) under administration/configuration/account settings and I can confirm that these fields are created if I go to administration/people/ and click "edit" next to each user.

I also know that for each individual custom field that I have created, D7 created a new table of the form "field\_data\_field\_\[FIELD\_NAME\]" (ie. field\_data\_field\_first\_name, field\_data\_field\_last\_name, ...)

The specific commands I would like to find more information about are:

```
MigrateDestinationUser::getKeySchema();
$this->destination = new MigrateDestinationUser();

```

I understand the above command is the default used to import users to the default "users" database.

How can I migrate my content to another D7 table? Such as migrating the First Name from the external table to field\_data\_field\_first\_name?

# Answer
An example migration is here (not my own) and there are some followup comments in that GIST: https://gist.github.com/893241

What you are talking about is mapping old fields of data to new fields of data in drupal.

You do this by calling `addFieldMapping()` in your Migration class constructor. The migration `__constructor()` function typically has 3 big pieces.

1. Where is the data from. Your $this-\>source() SQL query.
2. What fields map from what to where -- per field.
3. Is there any default values or further cleanup needed of data. By using `addField('new_drupal_field', 'old_value')->default('is_published', TRUE);` or for instance `addField('new_drupal_field', 'old_value')->seperator(',')` for more than 1 entry per row.

See documentation on these pages:

The whole migration class, and more importantly its constructor, is basically a recipe of what drupal does per-row of the migration.

So after you have your source $query (basically a SELECT field1, field2, field3 from OLD\_TABLE) you call the following:

```
// this is like saying field_first_name = old_field1
$this->addFieldMapping('field_first_name', 'old_field1');

```
> 3 votes

---
Tags: 7, entities, migrations
---


title: Weird Add Content problem?

text:
# Question
Title: Weird Add Content problem?
I have been dabbling with Drupal 7 and I am not quite sure what I did but turns out that after the interval of that mindless exploring, if I decide to add a specific Content type, it redirects me straight to only one content type (a custom content type I created using the Add Content type option) without consenting me on what kind of content type I specifically want.

I am not sure where I goofed up but does anybody know how the 'Add content' redirects you to a specific content type happen. Maybe I disabled the existing content types somehow, but I am not quite sure.

# Answer
Try looking at Content \> Content Types. If there is only one content type listed on this page, then it means you probably deleted all other content types. This may be your problem.
> 1 votes

# Answer
Check your "add content" links in the navigation menu (admin/structure/menu/manage/navigation/list). Make sure all of the links to your content types are enabled.
> 1 votes

# Answer
To expand on Steve's answer, you should also check that the links for creating content of each type are nested under the "Add content" link in the "Navigation" menu. If there is only one menu link nested under "Add content" it will automatically redirect to that content type's creation form when you click the "Add content" link. After a standard install (which create's two content types) your Navigation menu structure should look like the screenshot below. Check your site's menu against that.
> 1 votes

---
Tags: 7, nodes, redirection
---


# Question
Title: What's a good way to split a 'item_list' into two columns?
I'm working in a custom module that will output to my custom theme in D7. This theme & module will never be used apart.

Say I have a simple list in a block (six items), I want it split into two adjacent columns of three items...

1. Can this be done only with CSS? (just curious, not a constraint)
2. What seems easier; should I render two lists & just float the second right?

# Answer
> 2 votes
You can do this just using CSS by giving the list items a width and floating left:

```
.list-class li { width: 50%; float: left; }

```

You might need to adjust the width to a static number depending on the padding you have on the `<li>`s.

---
Tags: theming
---


# Question
Title: Programmatically create field instance of field and content type created in module code
In my module, I define a custom content type, and custom fields by using `hook_node_info()` `hook_field_info()`, and so on. I'd like to programmatically add field instances of my field to the created content type when my module is enabled/installed.

I know there is the possibility of creating the content type, and the field in the database by using `node_type_save()` and `field_create_instance()`, but this is not what I want, since during the development the field definitions will change, and in the latter scenario I would have to uninstall and reinstall the module every time I change a field/content type.

I tried using `field_create_instance()` in my module's `hook_install()` and `hook_enable()`, but Drupal says that the field I try to add does not exist or is inactive.

Is there an elegant way to let the module define fields, and attach them to content types when enabled (and of course detach them on uninstall or disabling it)?

# Answer
Field helper attempts to handle the creation/deletion of fields and instances for you and allows you to define them in hooks. It will not update the field definitions since that is not something Drupal core supports. Otherwise Features handles creation of field instances on content types if you were to make your module a feature.
> 1 votes

# Answer
there is also a sandbox with Field Fairy. Due to it being a sandbox, I wouldn't recommend it for production.
> 0 votes

---
Tags: entities
---


title: Drush one line command to create field

text:
# Question
Title: Drush one line command to create field
I want to create field with name `img` for content type `announcement`

From the documentation, I can type `drush field-create announcement`. After that typing the field name `img`, after that type `2`, lastly type `1`.

Is there any ways achieving this through one line command?

# Answer
> 5 votes
just type : drush field-create announcement img,image,image\_image

the last two are field\_type,widget\_name

---
Tags: 7, drush
---


# Question
Title: Custom Webform Email Response to two different recipients
When a customer fills out a webform, I create a customized email response by creating a custom email template (e.g. webform-mail-26.tpl.php). I needed to create this so that the customer could see exactly what options he chose and not options he did not. The email also has some nice instructions. But I also need to send the admin an email with all the information that was in the form. How can I send two emails, one to the customer and one to the admin, but have each email display different content?

# Answer
> 0 votes
We ended up doing this by creating a custom email template (e.g. webform-mail-26.tpl.php). And then we created another email recipient but chose to over-ride the "default" template with a "custom" template where I used the same text and tokens as the "default" template. It was counter-intuitive but it worked.

---
Tags: webforms
---


# Question
Title: Best approach for creating databases for sub-sites
I have to create a website that has about 1000(in future thousands) sub-sites. How should I create database for this sub-sites? Creating a separate database per site, or creating for example 10 databases, each one for 100 sites(using table prefixes), or ...?

# Answer
Each site should have it's own database if possible. The only reason to use table prefixes is if your host limits the number of databases you can create. You can share data without prefixes. Another thing to look into is Domain Access, if you wish to share a lot of content between the sub sites.

By having separate databases it will allow you to easily scale horizontally; move the DB to a new DB server; if they are all prefixed it makes it a lot harder to move databases to different servers.
> 1 votes

# Answer
The option to use table prefixes exists because some hosting providers limit the number of databases. Don't use this feature unless your hosting provider is one of those.
> 1 votes

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


# Question
Title: Programmatically accessing a field group relationship
I believe I am using the default Fieldgroup module. I have added a new group using "Add new group", then I have created a couple test fields and nested them under that group.

I see the entry is added in my 'field\_group' table in my database. What I am wondering is how I can programmatically see that relationship. Please bear with me. After adding content I am using `field_info_instance` to view each field for that node. I do not see any field that shows a connection to the group I created. Is there a function that would let me see this relationship on a field by field basis??

Thank you,

# Answer
> 2 votes
I couldn't find one in the module anywhere but I cobbled this together and it seems to work ok:

```
function field_get_field_group($field) {
  $group_info = field_group_read_groups(array('entity_type' => $field['entity_type'], 'bundle' => $field['bundle']));
  foreach ($group_info[$field['entity_type']][$field['bundle']]['form'] as $group) {
    if (in_array($field['field_name'], $group->children)) {
      return $group;
    }
  }
  return FALSE;
}

```

Usage:

```
$field = field_info_instance('node', 'field_image', 'article');

if ($field_group = field_get_field_group($field)) {
  $group_name = $field_group->group_name;
  // etc...
}

```

You'll probably want to add some error checking ;)

---
Tags: 7, entities
---


title: Remove link from content header

text:
# Question
Title: Remove link from content header
The website I'm building has a lot of content that I do not want linkable to the actual node. Is there a way to remove the link in the content headers?

# Answer
There are a lot of different methods for doing this.

The basic idea is to detect the content type using one of a few methods and calling `drupal_not_found()`. When doing this, I typically set the pathauto for these to `no-view/[nid]`, and then detect the `request_uri` in a hook. There are some variations, but the all do something really similar.

However, there is a newish module called Rabbit Hole that eliminates the need for custom modules and provides a lot of flexability to how you hide the content. I had been working on a general use module that did something similar, and abandoned developing it when I found this. From the project page:

> \[It\] works by providing multiple options to control what should happen when the node is being viewed at its own page. You have the ability to
>
> * Deliver an access denied page.
> * Deliver a page not found page.
> * Issue a page redirect to any Drupal path.
> * Or simply display the content (regular behavior).
>
> This is configurable per content type and per node. There is also a permission that lets certain roles override Rabbit Hole completely.
> 1 votes

---
Tags: 6, nodes, navigation
---


# Question
Title: How to set the breadcrumb for view defined pages
I have created a page using views 3 like this

node/%/classroom

How can I set the breadcrumb and title for this page.

I tried to set using views menu option but restricts me to use normal menu for path with %.

Thanks in advance for your help.

Umar

# Answer
You can set with hook\_page\_alter()

```
if (request_path() == 'your/page/path') {
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l('Whatever', 'whatever');
    drupal_set_breadcrumb($breadcrumb);
}

```
> 2 votes

---
Tags: views, uri, breadcrumbs, 7
---


title: How to create menu item with panels?

text:
# Question
Title: How to create menu item with panels?
I am using Drupal 7. In one of my projects I used Panels to create a custom layout to one of my pages. As per the needs I also created a menu "item" with the panels. But when i access the menu path of "item" i get the menu to be displayed. When i click the home or other tabs the menu "item" disappears.

Is this a bug in panels or am I missing something that can term me as a novice?

# Answer
It may or may not be important to understand, but Panels does **not** handle menues at all, it only deals with the layouts their UI. Page manager, a part of Ctools, however does handle menues, which is probably what you are using.

To figure out where the issue is:

1. Start by going to admin -\> structure -\> menues and check, is the expected menu entry in the right menu? If so, go to step 2. If not, you have a miss-configuration or bug in Page manager.
2. Page manager seemingly has done it's part, and now the question is, how do you render the menu on the different pages? Do you output the menu at all on the page where it doesn't show up?
> 3 votes

---
Tags: routes, panels
---


# Question
Title: How to show the description of primary links
> **Possible Duplicate:**
> How can I add a caption to my navigation menu?

I would like to print my primary links description too in my navigation like this website.

# Answer
The answer in your previous question should help you with this. The `$link['description']` will contain the description you set in the drupal menu item via the ui. You can then just print this below the title to achieve your example.

As a side note, you would be best amending your original question rather than starting a new one which is so similar.
> 0 votes

---
Tags: 6, theming, navigation
---


# Question
Title: How can I add a caption to my navigation menu?
How can I add a caption to a navigation menu in Drupal 6? I am trying to achieve this effect:

# Answer
```
function MYTHEME_menu_item_link($link) {
  // Debug:
  // dpm($link);

  // Check menu item localization settings:
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }

  // Target the desired menu:
  if ($link['menu_name'] == 'primary-links' && $link['options']['attributes']['title']) {

    // Theme menu item description:
    $desc = '<span class="menu-item-desc">' .
      check_plain($link['options']['attributes']['title']) .
    '</span>';

    // And title:
    $link['title'] = '<span class="menu-item-title">' .
      check_plain($link['title']) .
    '</span>';

    // HTML should be enabled:
    $link['localized_options']['html'] = TRUE;

    // Theme the menu item title as a link, then append the description:
    return l($link['title'], $link['href'], $link['localized_options']) . $desc;
  }
  // For other menus:
  else {
    return l($link['title'], $link['href'], $link['localized_options']);
  }
}

```
* Place this into your theme's `template.php`
* Don't forget to flush your Drupal cache at *admin/settings/performace* (D6)
> 3 votes

# Answer
You will need to apply some theme overrides in template.php, the most important function for you would be the theme\_menu\_item I would imagine, this will allow you to change the structure of the LI and include a description from the menu item. The images should be achievable from using css id's.

Also see the documentation

Example:

```
function theme_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE, $extra_class = NULL) {
// Dont forget to include code from the default for active trails etc, then add something like below to add on the description:
if ($link['menu_name'] == "*YOUR MENU WHICH YOU WOULD LIKE TO CHANGE*"){
  $link['title'] .= '<span class="description">'.$link['description'].'</span>';
}
return l('<span>'.$link['title'].'</span>', $link['href'], $link_options);
}

```
> 1 votes

---
Tags: 6, theming, navigation
---


# Question
Title: Retrieving image fields by user from database
I am creating a custom module for user specific image gallery for my website. I have created a content type and added an image field for uploading multiple images. Now I want to create an image gallery with jcarousel type slideshow. But I am not able to retrieve the images uploaded by a particular user and show them on their profile page creating a gallery tab

# Answer
I did it for this cg related image gallery (cgart.ir).

to display user created images on his/her profile I did these steps:

1. create a views named `artworks`
2. create a display within `artworks` named `page_1` and add `CONTEXTUAL FILTERS > (content: Author uid)` to it
3. edit `user-profile.tpl.php` and add below codes to it:

print views\_embed\_view('artworks', 'page\_1', $account-\>uid);
> 1 votes

# Answer
The other way around is to use the 'PWI' - Picasa Webalbum Integrator javascript library. Picasa Webalbum Integrator javascript librarywhich fetches photos from your picasa account + it also comes with an slideshow, which applies everywhere on the site. Which is good as it also saves hosting space.
> 0 votes

---
Tags: 7
---


title: New content doesn't appear in database

text:
# Question
Title: New content doesn't appear in database
I have the strangest thing going on here: I just created a new content type ('jobs'), and a new job (its node ID is 1706), but for some reasons there is no node that node ID in the database; even when I search for `type = jobs`, I get no result.

What could be the cause why I'm getting no results?

# Answer
If the content was created it's also there in the database. Most obvious reason for you not finding it, would be silly mistakes, like a typo in the search, or you looked in the wrong database (either created the node the wrong place or looking in the wrong database).

It's not possible to have a node in a drupal site that doesn't exist in the database unless you believe in fairies ;)
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: How to show Forms in nodes stored in the node tables
Mine is shared hosting account with limited CPU usage so I want to minimize CPU and mysql usage. I'm generating 100,000s of nodes which contain some information. I also want to add a form in those pages. Since these nodes will be stored in node table how can I generate form on the fly? I think using filters but that'll not use Drupal caching hence it'll affect the shared hosting CPU quota due to this performance issue.

I don't want to use \_menu to generate those pages on the fly because 1) it will slow down my site 2) It'll be difficult to use Drupal Taxonomy to classify "these" generated pages on the fly. Generating pages from the node table will be faster and also cacheable.

Another way is to insert the Form code in the nodes at the time of generation with the option that it won't contain/verify dynamically generated tokens(eg without #token) but it'll be security risk for my site.

What is the best way to handle this case?

# Answer
> 1 votes
What do you mean "generate form on the fly"? As in: the form for page "page/form" doesn't exist in a canonical state but is generated based on variables such as date/url/taxonomy? Or is it just the default values for the form etc?

In anyway: the options to have a form on a page are:

1. Hardcode HTML into the node content, e.g. `<form><input>` etc
2. Use hook\_menu to create the page and use the form API
3. Use hook\_menu to create the page and use the straight HTML
4. Use hook\_nodeapi to add a form to the content with the Form API
5. Use hook\_nodeapi to add a form to the content using HTML
6. Use a module such as webforms to add the forms

I would suggest either 2 or 4. When you say that hook\_menu generates these plages "on teh fly": that's not true. hook\_menu is only run on cache clear, and assuming you're using caching then the generation of forms isn't going to make much difference to your server. This may be a case where you're sweating about optimisation unnecessarily.

Using Form API gives you a load of tools that you'd otherwise have to handle yourself - validation, submission, sanitising, standardising, etc.

---
Tags: 6, forms
---


title: Views relationship question

text:
# Question
Title: Views relationship question
I have an Article node type where Expert node's can be referenced via autocompletion (as in: X Expert was consulted for this article)

I created a views for internal use, listing all the experts with exposed filters, easing up the journalist workflow to find suitable experts to contact for certain situations.

I'd like to list under each expert the Article nodes that they were referenced in, but as to how, I'm baffled, I attempted to create a relation with:

```
Content: Expert (field_expert_nid) - reverse
Relate each Content referencing the node through Expert.

```

But that's about how far I've gotten, any help or suggestions how to tackle this greatly appreciated :)

# Answer
I had similar situation and resorted to using viewfield. Works like a charm. Recommended.
> 1 votes

---
Tags: views
---


# Question
Title: Combine multiple Fivestar rating fields into an average
I'm building a rating site and using Views to display top rated (Fivestar + Voting-api) content -- but calculating what is top rated is where I'm lost now. Here's my View:

http://dl.dropbox.com/u/2188345/views-sorting.png

As you can see I've got things nicely set up, they are sortable etc. but now I'd need to add a final column showing the average score of those three combined, per node. I first thought I'd achieve this easily by creating a views template, and it was ok partially, but sorting didn't work as one would expect (since values were summed on the fly, not before the actual sorting happens).

Is there some smart way to combine values of those three relations via Rewriting - or some other means?

# Answer
> 1 votes
I managed to solve this by using the numeric value of the ratings in the table, but rewriting the display to show the star amount - this way drupal understands how to sort it and the users see the star values.

Sometimes simplest way is the best :)

# Answer
> 3 votes
Would Computed Field be of use to you here? You might need to duplicate the three ratings fields with a different output (and hide them) but then you should be able to do some calcs on the result.

# Answer
> 2 votes
that's a tricky one, don't have a good answer, just an idea: You might want to setup a "final" rating.

Then use rules to add each of the individual rating to the final rating. Your vote count would be off but the average rating should work.

---
Tags: views, rating
---


# Question
Title: Security issues concerning including external code for module
I would like to implement some external code in my custom module and if I understand correctly (correct me if I'm wrong), you can drop those folders in both sites/all/libraries as well as in sites/all/modules/custom/myModule/libraries.

What would the better security-wise place to include the folder be?

If you can think of another reason why to place it in the first folder or the second, I'm happy to hear it.

# Answer
> 2 votes
If your web server is set up correctly then both of the paths you've mentioned will have the same permissions (readable but **not** writeable by the server), so they would be equally secure/insecure depending on the rest of your server setup.

I must admit I haven't come across a path like the second one you mention, although I know most contributed modules that have been updated to Drupal 7 use the `sites/all/libraries` folder for storing external code libraries.

---
Tags: 7, theming
---


title: Section for logged-in users

text:
# Question
Title: Section for logged-in users
I've been asked to create a member's area in the site I am currently constructing.

This area should be accessible via a menu section that should only appear to logged in users.

Furthermore, if the user's role is a specific one, the menu should have one extra entry in which the user (let's say he is a baker, and the site is about a pastry shop), can see his earnings in a calendar like mode, assuming each of the cakes sold give's him a percentage.

So all in all, we have very conditional menu items.

Furthermore, the /user page, if the user is logged in (if it's not it's just a themed version of the original Drupal /user page), should be a view, or Panel, or collection of View blocks, that should depict a summary of the 4 links that follow.

At the moment my /user page shows the default "History" and some other stuff some modules have added. How can this page be styled?

The other menu items are: Your Account, Your Cart, Wish List, Order History, pretty much self explanatory, and more or less accessible using Menu Tokens.

The menu's structure is something like this

> -You (if user is logged in should change to his first name)
> |-Your Account (should lead to a form just like user/register (already themed) where the user can edit his information)
> |-Your Cart (commerce cart - kinda easy)
> |-Wish List (commerce wishlist - easy too)
> |-Order History (commerce orders - easy too)
> |-Earnings (for 'Baker' role only)

So the /user page should show (in a different fashion of course) all this information condensed.

So, to recap, the difficulties I am facing are:

1. Conditional name of the "You" item
2. Conditional appearing of the 4 sub-items
3. Conditional appearing ofthe 5th sub-item according to role
4. ~~Theming of the /user page (when logged-in)~~ (fixed using panel with UID as argument)

Any help for any of those would be highly appreciated.

# Answer
> 2 votes
You should check out Context module, can solve your needs listed above.

One way you can do is to create different menus for different roles.

For example, you create a menu called 'menu for anonymous' , add links for anonymous in the menu; create another menu called 'menu for member', add particular links in the menu. and so forth.

With Context module, you can set 'menu for anonymous' to display for anonymous user; set 'menu for member' to display only for user has whatever role.

For changing 'You' to username, I am thinking that you can use hook\_block\_view\_alter, loop to all menu items in the menu block, replace 'you' to user's name.

Again, with context module, you can add a section variable to the theme for the context of user logged in.

then you can customize your template in page--user.tpl.php

```
if (!empty($section_title)):
        ... theming for logged in user  ...
else:
    ... theming for general ...
endif;

```

Hope my answer make sense.

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


# Question
Title: How do I select a table using a variable with db_query()?
I'm trying to find records from a table based on a variable that is grabbed from user submission. This is my query:

```
$field = t('field_data_' . variable_get('tabbed_content_field'));
$fieldValue = t(variable_get('tabbed_content_field') . '_value');
$query = db_query('SELECT :fieldValue FROM {:field}', array(':field' => $field, ':fieldValue' => $fieldValue));

```

However, whenever I run this query I get the following error:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''field\_data\_field\_news\_release\_date'' at line 2: SELECT :fieldValue FROM {:field}; Array ( \[:field\] =\> field\_data\_field\_news\_release\_date \[:fieldValue\] =\> field\_news\_release\_date\_value )

I can retrieve the records successfully with:

```
$query = db_query('SELECT ' . $fieldValue . ' FROM { ' . $field . '}');

```

However, as I understand it this would be insecure.

Does anyone know why the first query won't work?

# Answer
This is one of the reasons the new query builder exists in Drupal 7, so you can dynamically substitute parts of the query:

```
$table_name = 'the_table';
$field_name = 'a_field';
$query = db_select($table_name)->fields($table_name, array($field_name));

```

Using `db_query()` you only get parameter replacement, which would only be applicable to substitutions in `WHERE` conditions. This means that you cannot use `db_query()` to replace table names, the names of fields selected, etc., only `WHERE` conditions.

Have a look at the `db_select()` docs for more in-depth examples, including how to add conditions to the dynamic query.
> 6 votes

---
Tags: database
---


# Question
Title: How can I change message set on form.inc?
I am using taxonomy module in my site and have used the "Add vocabulary" form by `hook_form_alter()`.

I want to change the error message for machine name (Machine name in use) to some other message. This message and validation is thrown from form.inc function. How can I change this message in my `hook_form_alter()` function?

Some code

```
function resources_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
    if(strstr(current_path(), 'admin/structure/resources'))
    {
        $form['#validate'][] = '_error_preservation_helper';

    }
}

function _error_preservation_helper($form, &$form_state) {
debug(form_get_errors());
    $errors = form_get_errors(); // works shows error array
    if(is_array($errors) && array_key_exists('machine_name', $errors))
    {
        // now change the error message
        form_set_error('machine_name', 'custom message', TRUE); // not works
    }
    debug(form_get_errors());   // same results

}

```

# Answer
> 1 votes
It's not `hook_form_alter()` that can change the error message, since there isn't any error message when that hook is invoked. The error message is output from the form validation handler, which calls form\_error(), or form\_set\_error() to set the error for the field that doesn't pass the validation.

If you want to change the error message for the specific form, and not globally, you can:

* Add a new form validation handler that is executed after the default one.
* In the validation handler, look for the error string in `$_SESSION['messages']`, and replace it with the string you want to show.

`$_SESSION['messages']` is the variable where drupal\_set\_message() store all the messages it receives. `drupal_set_message()` is the function called by `form_set_error()`, which is the function called by `form_error()`. The minimal code the validation handler should execute is similar to the following one.

```
if (isset($_SESSION['messages']['error'])) {
  $messages = array_flip($_SESSION['messages']['error']);
  $message = t('The machine-readable name is already in use. It must be unique.');
  if (isset($messages[$message])) {
    unset($messages[$message]);
    $messages = array_flip($messages);
    $messages[] = t('your message error');
    $_SESSION['messages']['error'] = $messages;
  }
}

```

There is still a place where the error message is stored, and it is the static variable returned from `form_get_errors()`. It doesn't seem there is any module that looks for a specific value in that array; if there is any module doing that, for compatibility reasons is better not to change the error message reported in that array.

If the message error is used in a single form, you want to change that error message in any form, or there isn't any reason the error message is dynamically altered, then the easier way to change the error message is to:

* Use the String Overrides module as Clive suggest.
* Add the following code to settings.php.

```
$conf['locale_custom_strings_en'][''] = array(
   'The machine-readable name is already in use. It must be unique.' => 'Your error message.',
);

```

In the latter case, the string can be altered for any language; the following code changes the string for Italian.

```
$conf['locale_custom_strings_it'][''] = array(
   'The machine-readable name is already in use. It must be unique.' => 'Your error message, in Italian.',
);

```

Between the two solutions, the first is preferable because it doesn't require you to alter the settings.php file; the second is preferable because it doesn't require any module, and it is preferable if the strings to alter are not too much, and you don't have many languages enabled in the site.

# Answer
> 2 votes
It's notoriously difficult to target/replace specific messages in the Drupal system. It's not impossible but it's a bit 'messy'.

I'd strongly recommend instead that you install the String Overrides module and use that to replace the specific message instead. String Overrides:

> Provides a quick and easy way to replace any text on the site.

It is available for any string in the system which is passed through the `t()` function, which all core error messages are.

# Answer
> 0 votes
On top of what Clive and kiamlaluno said above, you can override the string for any language other than english by going to the Interface Translation Overview (URL depends on your Drupal version).

---
Tags: forms
---


# Question
Title: Find slowest loading / longest time to generate pages
Is it possible to find pages that take the longest time to generate? I am aware Devel can collect query log per page, but is there a module that collects these per page and displays a list of slowest pages?

# Answer
> 5 votes
The Performance Logging and Monitoring module was split out from the Devel module last summer, but is mostly the same.

The summary logging page is sortable by all of the table columns. For example, if you want to show the slowest pages first, you just need to click on the "MS (MAX)" column heading until it sorts descending. The direct URL would be at `/admin/reports/performance-logging/summary?sort=desc&order=ms+%28Max%29`

You can also do a manual query on the database if that is where you are storing results:

```
SELECT *
FROM {performance_summary} performance_summary
ORDER BY ms_max DESC

```

# Answer
> 4 votes
This is a roundabout way of getting at the data, but if you have Google Analytics setup on your site, it's also possibly the fastest and easiest. Specifically, check out the Site Speed reports.

GA uses the new "HTML5 Navigation Timing" spec, which allows it to track server response time, latency between server and client, as well as the actual browser execution time.. and you can slice and dice the data by any of those dimensions.

---
Tags: 7, debugging, performance
---


title: Downgrade jquery from 1.5.2 to 1.4.2

text:
# Question
Title: Downgrade jquery from 1.5.2 to 1.4.2
How can I downgrade the jQuery library on Drupal 7 from 1.5.2 to 1.4.2; it looks like i've lost some functionality in Panels and Views after enabling the jQuery Update module.

# Answer
The jQuery Update module updates Drupal's jQuery library from 1.4.4 to 1.5.2. If you don't *want* version 1.5.2 then you just need to uninstall the jQuery Update module and everything will go back to normal.

If you want to use jQuery Update *just* to update the jQuery UI library to v1.8.11 it looks like you'll have to patch the jquery\_update.module file directly, as the version numbers for the base library are hardcoded into the `jquery_update_jquery_replace()` function using this code:

```
switch ($version) {
  case '1.5':
    $trueversion = '1.5.2';
    break;
  case '1.7':
    $trueversion = '1.7.1';
    break;
}

```
> 3 votes

---
Tags: 7, javascript
---


# Question
Title: about constructing a database for student multi-step form
I need to construct a database for students. I am wondering how to implement the database. Do I add the students data into the users table? Do I create a student's table, and when a new student is added add part of the data of the student into the users table and the other part into the students table?

# Answer
The "users" table is for containing information about what the Drupal site sees as authenticated users, which means the users with a login in a Drupal site.

If you are adding information about users that don't need to login on the site, e.g. people working for an organization for which you keep information, then you should not use the "users" table. You should create your own table that contains the necessary dat; possibly, you should create a custom module that creates that database table when installed.

If you are adding users as authenticated users, and you need to store extra information about those users you can:

* In Drupal 7, you can add extra fields to the user's account.
* In Drupal 6, you can enabled the Profile module, which allows you to add extra fields for the user profiles.
* In Drupal 6, and Drupal 7, you can create a module that handles that information.

Of the two solutions, on Drupal 7 it is better to use the fields provided by the field API; if you need to handle the fields in a specific way, you can implement a new type of field in a module.

If you need something more customized, such as a multi-step form to fill the information, then you could write your own custom module that creates its own database table, and uses the user ID as primary key. In this case, you would need to write more code, such as the one that deletes rows from the database table when a user has been deleted from the "users" table. In Drupal 6, that could would be in a hook\_user('delete') implementation, while in Drupal 7, it would be in a hook\_user\_delete() implementation.
> 0 votes

---
Tags: database
---


# Question
Title: Child navigation sidebar or drop-down navigation displaying child items
I have a 'basic page' which is a parent and is provided a menu link. This page has several children (subpages).

How would I display the subpages for each nav item either in the following cases?

* Drop-down menu from the main navigation menu, or some close alternative
* Display all the children for that page in a sidebar

# Answer
> Drop-down menu from the main navigation menu, or some close alternative

Use Superfish. It integrates the jQuery Superfish dropdown plugin with your Drupal menus.

> Display all the children for that page in a sidebar

Use Menu Block. It provides configurable blocks of menu trees starting with any level of any menu. And more!
> 3 votes

---
Tags: routes, navigation, 7
---


title: Drupal 7 custom module for menu

text:
# Question
Title: Drupal 7 custom module for menu
I am developing a custom module that will have the functionality to show a particular menu link active on the desired path. For this I have implemented **hook\_form\_FROM\_ID\_alter()** hook for **menu\_edit\_item()**. In the edit form of each menu item there I have provided options similar to block modules page visibility options

* Active on all pages except listed
* Active only on listed pages
* Active depending upon given php code

But I need to match the path listed with any existing path. Do I need to implement other hook or create more functions to implement this or this functionality should be implemented in hook\_form\_FROM\_ID\_alter(). I have also created a database table for this that stores

* menu link ID
* Visibility (i.e. flag to the option chosen by the user 0, 1, 2)
* Pages (i.e the paths given by the user in the textarea eg: node/4, etc)

Thanks for your help in advance

# Answer
> 1 votes
This is an existing module which does part of what you want to do. The module is Menu item visibility. I recommend looking at how it works and extending it (it says it's extendable) to add the extra pieces you are requesting: visible per page, or visible on PHP code. It probably has hooks you can use to complete your business logic.

In fact, this issue talks about adding "per page" or "php code" conditions essentially.

---
Tags: 7
---


# Question
Title: Restrict Menu Item from anonymous users and redirect to Login page
I created a simple menu link and need it to be visible for both authorized and anonymous users. But when a unauthorized/anonymous user click it should check authorization and if not it should redirect to login page. How can i do this. Thanks

# Answer
> 1 votes
Create a custom module In your\_custom.module

```
function custom_init(){
global $user;
$current_path = request_path();
if (!in_array(array('your roles','your roles'),$user->roles) && $current_path=="node/add/yourcontent type" ) {
  // for mutiple row
  drupal_goto('/user');
}
}

```

# Answer
> 0 votes
If you made the link via the drupal admininstration area and Menu or Menu Items ... or you've made the menu item using hook\_menu() ... then you just need to define an 'access callback' for the menu item. See hook\_menu() documentation for how to do this -- if the user is anonomous then you will return False from this custom callback function.

If you dont have a custom hook\_menu() in a function but made the menu item via the Adminstration UI, then implement hook\_menu\_alter() to change the menu item stored in the database and add the "access argument".

If you're just echoing an html link in some page without having the link come from the database .... good luck.

# Answer
> -2 votes
Yes you can do this just go to admin/config/system/site-information (if using drupal 7) there you will see a **Error Pages** title at the bottom of the form there you can see an option as **Default 403 (access denied) page**. You can mention your login page path within that text box **user/login**. I hope this works for you

---
Tags: routes
---


# Question
Title: Breadcrumb trail not displaying correctly in custom module
I'm working on developing a custom module for Drupal 7. Part of the module that I'm creating is a form editing component (with an entirely different aim from something like cck, which is why I am re-inventing the wheel here). I've got one page registered to display a list of all the forms, and another registered for viewing and editing a specific form. I would like the breadcrumb on the viewing page to include a link to the listing page, however it does not appear. I am getting "Home » Administration » Jarrow ETD System", while I would like to have a "Form Editor" component on the end. The relevant hook\_menu code looks like this:

```
$items['admin/settings/jarrow'] = array(
  'title' => t('Jarrow ETD System'),
  'description' => t('Configure the core settings for the Jarrow ETD system'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('jarrow_configure'),
  'access arguments' => array('administer etd'),
  'type' => MENU_NORMAL_ITEM,
);

$items['admin/settings/jarrow/forms'] = array(
  'title' => t('Form Editor'),
  'description' => t('View All Forms'),
  'page callback' => 'jarrow_list_forms',
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_LOCAL_TASK,
  'weight' => 40,
);

$items['admin/settings/jarrow/forms/%/view'] = array(
  'title' => t('Form View'),
  'description' => t('View a Form'),
  'page callback' => 'jarrow_view_form',
  'page arguments' => array(4),
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_NORMAL_ITEM,
);

```

There are a significant number of other pages registered, which I have omitted. Aside from the fact that I probably shouldn't be using 'admin/settings' as my base url, I can't see anything wrong with the menu structure. Oddly enough, if I add in the following code to hook\_menu, I get the right result:

```
$items['admin/settings/jarrow/stuff'] = array(
  'title' => t('Stuff Editor'),
  'description' => t('View All Forms'),
  'page callback' => 'jarrow_list_forms',
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_LOCAL_TASK,
  'weight' => 40,
);

  $items['admin/settings/jarrow/stuff/%/view'] = array(
  'title' => t('Stuff View'),
  'description' => t('View a Form'),
  'page callback' => 'jarrow_view_form',
  'page arguments' => array(4),
  'file' => 'form_editor.inc',
  'access callback' => 'user_access',
  'access arguments' => array('administer etd'),
  'type' => MENU_NORMAL_ITEM,
);

```

This is exactly the same entry into hook\_menu, down to the function it's calling, except for the url having "stuff" in it instead of "forms". However, the breadcrumb trail displays properly: "Home » Administration » Jarrow ETD System » Stuff Editor".

I took a look at the inner workings of menu.inc, and traced the execution. It appears that when Drupal assembles the menu tree for the form, it is including the child /view, whereas for "stuff" it does not. I can't for the life of me figure out why, and I am hoping someone with experience dealing with drupal's menu system can provide some explanation as to why the menu would be constructed as such.

# Answer
After making a completely unrelated change to my hook\_menu, the breadcrumb fixed itself. I don't know why though.
> 0 votes

---
Tags: 7, routes, breadcrumbs
---


title: What's the best way to store time

text:
# Question
Title: What's the best way to store time
I need to store "time" in a content type. The time is actually duration (how long it took people to perform various tasks), with the time varying between a few minutes to several days.

Is there anything already out there (Date doesn't seem to cover it)?

If not, what's the best way to create this?

Ideally I'd like dropdowns for days, hours, minutes, seconds, tenths.

It seems to make sense to store a computed value in the database (total seconds, rather than save everything in five separate fields. Are there any good tutorials on doing this?

I assume I then use a field formatter to break out 300.3 seconds into 6:00.3 or whatever format I want?

# Answer
> 4 votes
Sounds like you're looking for something like Time Period.

That one stores the interval in seconds, so if you need smaller values you will probably have to write your own field widget/formatter but the module might still serve as a base.. or maybe you could extend it to cover this use case as well and e.g. store microseconds.

---
Tags: 7, entities
---


# Question
Title: Multiple blocks on single page, pager issue
I have 3 blocks made by views on the front page. Each have 4 of the newest node teasers showing with a pager to see the rest. However, when I click on one of the pager's next button, it will load the next 'page' for all the blocks on the page.

What would be the best way to make it so pressing the next button will only load that specific blocks next page and not the other blocks?

# Answer
You can configure each block's pager to have a different pager ID and then they will/should only update the one you clicked on.
> 6 votes

# Answer
You may also test enabling AJAX and the different views should page individually.
> 2 votes

---
Tags: 7, views, blocks, paging
---


title: Conditionals based on taxonomy

text:
# Question
Title: Conditionals based on taxonomy
editing node.tpl.php, I want to create a conditional statement based on the node's taxonomy which will not print the submitter info and de-links the title from the node.

How would I get the value of the node's taxonomy when it passes into node.tpl.php?

I've tried $sTaxonomy = $node-\>taxonomy and doing a strpos($sTaxonomy, 'static') and a in\_array('static', $sTaxonomy) which neither returned true (or not false). I've tried attaching 1-3 terms on the content and trying both methods without luck.

# Answer
> 2 votes
In D6, $node-\>taxonomy is an array of term objects keyed by the term id, eg:

```
  [145] => stdClass Object
    (
        [tid] => 145
        [vid] => 5
        [name] => nineohfour
        [description] =>
        [weight] => 0
    )

  [147] => stdClass Object
    (
        [tid] => 147
        [vid] => 5
        [name] => anotherterm
        [description] =>
        [weight] => 0
    )

```

Just put a `drupal_set_message('<pre>' . print_r($node->taxonomy,true) . '</pre>');` in your template to take a closer look. You can then go through that array with a `foreach` (or `in_array`)to find if a term is set and then act upon that. I would do this in a `_preprocess_node()` hook though and set a variable to act upon in your node template instead of putting all that php logic in it.

---
Tags: 6, nodes
---


# Question
Title: field_info_instances() returns an empty set in hook_uninstall but not in module file
Why would `field_info_instances()` return an empty set in `hook_uninstall()` when it returns the expected results in the main module file?

I've used the exact same code to delete the fields for a set of bundles in both the .install file and the main .module file:

```
  $bundles = array('property', 'open_house', 'agent', 'office');
  // Delete fields
  foreach ($bundles as $bundle) {
    $instances = field_info_instances('content', $bundle);
    if (!empty($instances)) {
      foreach ($instances as $instance) {
        dpm($instance);
        //field_delete_instance($instance);
      }
    }
  }

```

The following code (pulled from `_field_info_collate_fields()` in field.info.inc) outputs the fields in a list:

```
  $definitions = array(
    'field_ids' => field_read_fields(array(), array('include_deleted' => 1)),
    'instances' => field_read_instances(),
  );

```

as shown here:

```
 ... (Array, 2 elements)

     field_ids (Array, 149 elements)
     instances (Array, 8 elements)

```

It was suggested that I need to use `drupal_load()` and/or `drupal_load_include()` to load the field module or field.info.inc to use the `field_info_instances()` function. I also tried using `drupal_load()` to load my module, but the following code also does not work:

```
  $bundles = array('property', 'open_house', 'agent', 'office');
  drupal_load('module', 'field');
  module_load_include('inc', 'field.module', 'field.info');

  // Delete fields
  foreach ($bundles as $bundle) {
    $instances = field_info_instances('content', $bundle);
    dpm($instances);
    if (!empty($instances)) {
      foreach ($instances as $instance) {
        field_delete_instance($instance);
      }
    }
  }

```

Does anyone know why `field_info_instances()` would be unable to read the information about the field instances?

**UPDATE**:

When I run the following code: `dpm(field_read_instances(null, array('include_inactive' => TRUE)));` my fields are displayed. Why are they inactive, is it because the module is being uninstalled and is disabled? What should I do to work around this?

# Answer
> 0 votes
I found out that this has been fixed in 7.8. #943772 by jpsoto, yched, catch, bojanz, pillarsdotnet, steinmb: Fixed field\_delete\_field() and others fail for inactive fields.

---
Tags: 7, entities
---


# Question
Title: Is there a module to track future revisions of published content in Drupal 6?
I need to track a future revision of a published node that can be reviewed, edited, and eventually published over the currently published revision of the node.

The idea is that you have a page that is published and public but you are able to start making edits on a copy of the published page that are not visible to the public. When you are ready you can then publish this revision over the published, public one.

This feature is provided by the (excellent looking) Workbench module. However, Workbench is only for Drupal 7. Is there a Drupal 6 module that provides this future revision support?

# Answer
In D6, you can do this with Revisioning and Rules. You may also need to throw views, etc. into the mix.

Revisioning provides the ability to add pending revisions to content types. You can set it so that you are tracking only one pending revision per node or you can even track revisions of pending revisions. Revisioning provides actions and events to rules so you can make your own workflow. It's not as easy to set up as the Workbench module, but I've implemented a similar workflow with these two modules.

There's also the Workflow module but I don't have any experience using it.
> 1 votes

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


# Question
Title: Views 3, 2 different node types, filtered by the same contextual filter
I have two node types. Node A and Node B, both node types can have a reference to to a taxonomy term.

Now I am trying to construct a view which shows a list of both Node A and Node B, filtered by the taxonomy.

So Node A and Node B have different names for the the taxonomy field (field\_nodea\_taxonomy, field\_nodeb\_taxonomy). If add both of these fields as contextual filters and then try to filter on taxonomy term with id 10, by writing "10/10", i get only contents for the first filter.

How can i make it so to that it will show both content types, but filtered?

# Answer
If field\_nodea\_taxonomy and field\_nodeb\_taxonomy use the same taxonomy vocabulary, this problem can be addressed differently with a shared field.

I generally define a single shared field for each taxonomy vocabulary, and use it in every content type where it's needed (e.g., nodea and nodeb). If your requirements permit you to use this approach, your problem goes away, since a term filter on that single field will work for all content types.
> 2 votes

# Answer
Filtering on two fields with the same value is not supported via UI. You have to code a plugin and/or handler to manage this use case.
> 1 votes

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


title: Adaptivetheme Subtheme usage

text:
# Question
Title: Adaptivetheme Subtheme usage
I'm using Adaptivetheme with the pixture\_reloaded sub-theme. Keep in mind, it's structured as:

```
Adaptivetheme
  -Adaptivetheme_Subtheme
      -Pixture_Reloaded

```

I'm creating custom edits to template.php to add a node preprocess which creates a custom variable for me, and then editing node.tpl.php to add my variable to the output.

Editing adaptivetheme\_subtheme node.tpl.php and adaptivetheme\_subtheme node preprocessor gives me the output I want. I understand that the best practice is to edit the sub-theme files...

**In my case is the "sub-theme files" the adaptivetheme\_subtheme files or the pixture\_reloaded files?**

Pixture\_reloaded itself doesn't have a node.tpl.php file, so I've tried copying both the one from adaptivetheme and adaptivetheme\_subtheme to the pixture\_reloaded directory, but it's like it never reads the file.

EDIT:

> Pixture\_reloaded itself doesn't have a node.tpl.php file, so I've tried copying both the one from adaptivetheme and adaptivetheme\_subtheme to the pixture\_reloaded directory...

I had shutdown my server yesterday, and after bringing it back up, my output was correct.

I had cleared out the cache in the backend of the site... shouldn't that have done it for me?

# Answer
> 1 votes
To answer my own question, `pixture_reloaded` is the sub-theme I want to edit, as that is the last child/sub theme in the hierarchy.

# Answer
> 0 votes
Although it's possible to edit Pixture Reloaded directly, best practices are to make a subtheme of Pixture Reloaded and edit that instead. If you don't have experience making subthemes, you can use Footheme, which Jeff Burnz (the developer behind Adaptivetheme/Pixture Reloaded) provides for making subthemes of his themes.

Why should you do it this way? Well, Adaptivetheme is in the process of getting a major update to do responsive design, even in Panels. Updates to Adaptivetheme Core and Pixture Reloaded will be required. If you customize Pixture Reloaded directly, to use the new features you will have to update your version of Pixture Reloaded yourself. If you instead use a subtheme based on footheme, the amount of customization you will have to do to use the new features will be much less.

---
Tags: theming
---


# Question
Title: Recreating a media_gallery using a view?
I have a site that includes a photo gallery, using the Media Gallery module. I am now trying to create a mobile site, and the media gallery page, and all of the galleries look horrible on mobile (I'm using the Mobile Jquery theme.) I am trying to create my own view displaying all of the galleries, and a view displaying each image (depending on the photo gallery) I have seen tutorials on how to create a photo gallery from scratch using content, but the media gallery doesn't seem to create individual nodes for each image. How do I make a view for the media galleries, and out of curiosity, how does the media\_gallery module its self work?

# Answer
I haven't used Media Gallery, but have used a few others - they all do similar things though often in quite different ways.

First off, it's not really necessary to create a new node for each image - Image Field can contain multiple images, depending on its configuration.

I recently created a Gallery content type with two image fields - one for the gallery "cover" with a single image and one with unlimited images allowed, for the gallery contents. I then used Views to create a View with several Page displays (one to display a list of galleries, another to display each gallery's contents), along with the Colorbox module for image display in a lightbox, and the Plup module (and plupload jquery plugin) to do drag and drop all-at-once uploads into the gallery. Works like a champ and very easy for site maintainers to deal with - all they have to do is upload a "cover" image, drag the whole mess o' images into the plupload area, give it a title, and save it.

Doing it this way lets you leverage image styles in several places - the cover image, the gallery page images, and the colorbox display images - plus Colorbox makes it possible to set up the gallery slideshow as automatic or manual advance. Pretty cool, and no custom code to write. You can fiddle with the View's output options as needed and, should you need more styling action, you have the option of writing theme templates to get the output looking the way you need it.

You can see it at work at http://betheldrupal.m-so.com/galleries \- not in production yet but working well so far...

Let me know if you want details - I can export the views and stuff if need be.
> 3 votes

# Answer
In Views, choose to display Fields. And under Fields, add the media\_gallery\_media, uncheck "multiple...", because each media\_gallery\_media field contains many images.
> 0 votes

---
Tags: views, media
---


# Question
Title: Adding a 'Add New Listing' (Create Content) Link on Local Tasks Menu
I am working on making user pages for a certain type of user who can add/edit/delete content on my Drupal site. I've figured out how to use Views to create a 'Manage Listings' tab which appears on the user's profile, now I need to make another Local Task tab (or any kind of link) that allows the user to add new content.

I tried just adding a header to the view using basic markup text that contains:

```
<a href="node/add/">Add New Listing</a>

```

But because the link is displayed from the 'users/admin/' page, the link ends up bringing them to 'users/admin/node/add/' which doesn't exists (obviously). How can I create a create content link without messing up the path?

I would provide a screenshot, but my reputation isn't high enough to do so. Thanks.

# Answer
> 0 votes
Add a forward slash at the beginning:

```
<a href="/node/add/">Add New Listing</a>

```

---
Tags: views
---


# Question
Title: How do I reload the theme .info file on Drupal 7
How do I reload the theme .info file on Drupal 7? I added the following line of code in order to add my own Javascript file to the pages:

```
scripts[] = myJavaScriptFile.js

```

Now I need to refresh the .info file somehow. It doesn't seem to be doing this on its own. How do I do this?

# Answer
You need to clear the theme cache.
> 4 votes

# Answer
If you have drush, enter

```
  drush cc all

```
> 0 votes

---
Tags: 7, javascript
---


title: Change select list to radio buttons.

text:
# Question
Title: Change select list to radio buttons.
I want to modify my register page and add some fields from 'profile' content, for example: gender.

So Ive got:

function mysite\_preprocess\_user\_register(&$variables) { unset ($variables\['form'\]\['Personal Information'\]\['profile\_gender'\]\['#description'\] ); .... }

In this point when i print\_r profile\_gender Ive got:

```
Array ( [#type] => select [#title] => Gender [#default_value] => [#options] => Array ( [0] => -- [Select] => Select [Male] => Male [Female] => Female ) [#required] => 0 [#post] => Array ( ) [#programmed] => [#tree] => [#parents] => Array ( [0] => profile_gender ) [#array_parents] => Array ( [0] => Personal Information [1] => profile_gender ) [#weight] => 0.003 [#processed] => 1 [#attributes] => Array ( ) [#input] => 1 [#size] => 0 [#multiple] => [#process] => Array ( [0] => form_expand_ahah ) [#name] => profile_gender [#id] => edit-profile-gender [#value] => [#defaults_loaded] => 1 [#sorted] => 1 )

```

And when I want to change #type to **'radios'** displays me nothing..

Like:

```
  $variables['form']['Personal Information']['profile_gender']['#type'] = 'radios';
  $variables['form']['Personal Information']['profile_gender']['#options'] = array('0'=>t('Male'),'1'=>t('Female'));
  $variables['form']['Personal Information']['profile_gender']['#default_value'] = 'Male';

    $variables['gender'] = drupal_render($variables['form']['Personal Information']['profile_gender']);

```

Any ideas how to change that from select list to radios(male/female)?

# Answer
> 2 votes
The preprocess functions are about rendering the output. Removing and adding form element with FAPI must be done earlier.

You have to do this with hook\_form\_alter. It's also very likely that you have to *add* a custom submission handler to process and save the user input. You can hook in your handler in hook\_form\_alter as well.

---
Tags: theming, forms, users
---


# Question
Title: Where should I begin in creating a page to allow authenticated users to submit a short story that will become it's own independent page?
I have installed the most recent version of Drupal on my computer using xampp as the local host.

I would like to allow authenticated users to be able to publish content (ie a short story & accompanying imagine) that would appear on a stand alone page, not like a blog; for example, if a user submits 3 stories, then each story could be accessed independently.
Ultimately, during the submission process I would like the user to identify the category of the story (adventure, romance, sci-fi, etc) that would then appear in the appropriate section of the website.
In my mind it would be similar to a user submitting a recipe on a cooking site. I imagine the submission page would not be dissimilar to the page I'm on now to submit this question.

All of which is to say, where do I begin? What modules will best assist me? Can I develop the submission page and then institute the taxonomy?

# Answer
Hope this gets you off the ground. Of course you need some more reading/googling.

1. Give users the right to register an account on your site.
2. Create a content type with all the fields you need. You can do this with the built in fields features.
3. Create a role that has the right to create/edit/delete a this content type. This is a drupal core feature as well.
4. Assign a role to this users up on register (auto assign role module).
5. Make sure nice descritptive URLs are created automatically from the node titles (and maybe some fields) (path auto module)
6. Done.
> 1 votes

# Answer
Start at the library :) . Drupal is a content management system so it does not create static pages. It can do what you want right out of the box but may not be doing it the way you expect. Go to admin/content/create content and create a page. Everything you asked for should be right there. However, take the time to learn the basics from several excellent Drupal primers out there. As soon as you do, you will want more to do more!

There is also a lot of help available at this site.
> 0 votes

# Answer
Everything you need is in the out of the box installation. You might have Views installed, but first you must master the basics.
> 0 votes

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


title: Setting up permissions

text:
# Question
Title: Setting up permissions
My cars data is as the following:

```
id    make        no         parent
1     bmw         NULL          0
2     bmw         bmw987        1
3     bmw         bmw654        1
4     ferrari     NULL          0
5     ferrari     ferrari987    4
6     ferrari     ferrari654    4

```

(Note: I am using two tables for above data. This is just to get an idea of data.)

I am creating permissions to book cars as:

1. `Book bmw`; the user will have permission to book bmw987 and bmw654 means children of BMW
2. `book bmw987`; the user will have permission to book bmw9987 only.
3. `Book ferrari`; the user will have permission to book all Ferrari cars.

In my car booking portal, I have 100's of cars and many makes. When I used hook\_permission() and loop through all available cars to create book permission on each car, it pollutes my permission page (admin/people/permission) and believe me handling these many permission will faint Admin.

Is there any other alternative to handle such huge permission?

# Answer
> 0 votes
I think you should try something like this

```
function mymodule_menu() {
  $items['example/car/%'] = array(
    'title' => 'Example RSS feed',
    'page callback' => 'example_feed',
    'access arguments' => 'mymodule_abc_view',
    'type' => MENU_CALLBACK,
    );
    return $items;
}

function mymodule_abc_view() {
    return 'TRUE after checking something';
}

```

your URL should pass the car id or something to check the permission.

---
Tags: hooks, users
---