# Question
Title: Drupal-7 - Lists and Custom Content Types
I've just started with Drupal-7 coming from Drupal-5 that I last used a few years back and made a few customisations too. It seems to be Drupal-5 was much easier for modification, though Im starting to work out where all the data is saved processing through all the examples.

What isn't clear is when is a node not a node. For example, there are various support lists that I would like in my customisations, for example "salutation" (mr, mrs, miss, dr, revd etc) that should be user maintainable and stored in a database. It seems a bit overkill to create a separate content type and node just for this.

The current project Im working on is for Events, but I need to sub-categorise those Events twice by Event Type and Sub-Event-Type. Both of these should be user maintainable and therefore database driven. I can put them in a Content Type/Node but it does seem overkill.

I can't figure out if there's a programmatical way to insert, alter, delete (like the old days) into their own tables and then reference them in the Event node I will create generating a dynamic list.

There are lots of information out there about using Values, Taxonomy and Views etc. Seems everybody shys away from programming now and there's no examples anymore!

Any thoughts where to start? It seemed much easier finding the information before.

# Answer
> 1 votes
Organizing content with taxonomy (category) is a very powerful tool of Drupal.

> What isn't clear is when is a node not a node. For example, there are various support lists that I would like in my customisations, for example "salutation" (mr, mrs, miss, dr, revd etc) that should be user maintainable and stored in a database. It seems a bit overkill to create a separate content type and node just for this.

According to this, you can manage "**salutation**" with taxonomy . The"**salutation**" is a **vocabulary** and "mr, mrs, miss, dr, revd" are **terms** of the vocabulary. They will be stored in the taxonomy table and the path **admin/structure/taxonomy/your\_vocabulary** will be user maintainable list page.

You can create a custom field ( **term reference** ) to your vocabulary ( "**salutation**" in this case ) for your content type. They can be chosen from a list when user creates a node.

Same concept for your Event Type and Sub-Event Type. The Taxonomy Manager module may help you.

---
Tags: 7
---


# Question
Title: Is there a way I could display a token (for exmaple user ID) as a default field content to a content type?
Is there a way I could display a token (for exmaple user ID) as a default field content to a content type?

Id like to display a node form to users /node/add/content type

when a user goes to that page the field "name" automatically displays the user id.

name: \[user:uid\] - something like that

Is it possible, If so, how can I achieve this?

Thanks

# Answer
Do you want it to be editable or not?

Either way, its going to take a small custom module with hook\_form\_alter or hook\_form\_FORM\_ID\_alter if you want to target a specific form.

If you want it editable:

http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#default\_value

If you want it set at a value:

http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#value

Start with downloading and enabling devel and a small module with just this to get a list of all the form elements on a page:

```
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  dsm($form_id);  // print form ID to messages
  dsm($form);  // pretty print array using Krumo to messages
}

```
> 0 votes

# Answer
Unfortunately there isn't a module for that.

Check these links though; people posted some patches but I haven't tried any of them.

http://drupal.org/node/1070878

http://drupal.org/node/700230

http://drupal.org/node/700230

http://drupal.org/node/1308564

On the other hand, I think you can use hook\_form\_alter() to set the default field value on that node add form.
> 0 votes

---
Tags: entities, tokens
---


# Question
Title: want to ask if there is a way that I can display a field from another content type to a field of another content type
Im quite new to drupal (7) and want to ask if there is a way that I can display a field from another content type to a field of another content type and applying condition at the same time?

Here is the scenario:

I have created content types: Courses and Course schedules

I will be creating more than 50 contents for courses (containing their description, objectives etc as fields).

I will create different course schedule contents (data in here changes regularly including fields like time, date, venue, etc).

What i want to accomplish is to display the course article with a field that is linked to the courses schedule content, thus showing the available class sched data for each course.

I dont want to do it with views because im thinking it would be tedious to create a view for each course.

Is there a best way you can recommended to accomplish this? or is there a module that does this?

Thanks so much for your time.

# Answer
You can use the entity reference module for accomplishing your requirements.

On the "Courses" content type you will add a field type entity reference which refer to the "Course Schedules" content type.

Then in the "Courses" content type Manage Display, You can choose that the referred node link to appear, I think you can also choose that the rendered node to appear.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Printing individual components of comment-form in comment-wrapper.tpl
In my comment-wrapper.tpl.php I was doing

```
print render($content['comment_form']);

```

which worked fine. But to render the comment-form according to given theme, I tried doing this:

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

   print render($content['comment_form']['author']);
   print render($content['comment_form']['field_email']);
   print render($content['comment_form']['comment_body']);
   print render($content['comment_form']['actions'['submit']);
   print drupal_render_children($form);

 if ($content['comments'] && $node->type != 'forum'):
     print render($title_prefix);
    <h2 class="title"><?php print t('Comments'); ?></h2>
     print render($title_suffix);
endif;

```

This code is printing all the components of the form but the submit button is not working as it should. When I click the submit button it is not giving any reaction. Do I need to add any more lines of code to make this comment form work ? Thank you.

# Answer
You forgot to render hidden form fields that are required for the correct work.

Just add this line of code after outputting all visible form fields:

```
<?php
  print drupal_render_children($form);
?>

```

Also if you output form elements outside form template you need manually add {form} tag In your case you will get

```
<form id="comment-form" class="comment-form" accept-charset="UTF-8" method="post" action="<?php print url('node/' . $node->nid); ?>#comments">
<?php
  print render($content['comment_form']['author']);
  print render($content['comment_form']['field_email']);
  print render($content['comment_form']['comment_body']);
  print render($content['comment_form']['actions']['submit']);
  print render($content['comment_form']['actions']['preview']);
  print drupal_render_children($content['comment_form']);
?>
</form>

```
> 2 votes

---
Tags: comments, forms
---


# Question
Title: Drupal 7 timestamp insert into mysql error
i get error when i want to insert current time to my table-field **date**,

> i get this error PDOException: SQLSTATE\[22007\]: Invalid datetime format: 1292 Incorrect datetime value: '1345724717' for column 'date' at row 1: INSERT INTO {users\_history} (uid, nid, points, date, reason) VALUES ('31', '107', '2', '1345724717', 'session'); Array ( ) in points\_node\_insert() (line 57 of /home/www/live\_project/htdocs/sites/all/modules/custom/points/points.module).

i have table like this:

```
uid int
nid int
points int
date datetime
reason enum

```

this is my query(this query works fine if i delete **date field**)

```
  $date = time();
    db_query("INSERT INTO {users_history}
       (uid, nid, points, date, reason) VALUES
       ('$uid', '$nid', '$points_for_post', '$date', '$reason')");

```

# Answer
The 'datetime' value assumes the "YYYY-MM-DD HH:MM:SS" formatting, if I got it, you're trying to insert a 'timestamp'
> 2 votes

---
Tags: database
---


title: Getting field from code

text:
# Question
Title: Getting field from code
I have difficulties with getting a render Date (ISO) field from code. The field has machine-name `field_date`. By default, the Date field has three formatter: "long", "medium" and "small". The default formatter for node is set to "medium". (I've checked that, if the field is displayed in usual node's view, it's formatted as it should be) Here's the code:

```
$node = node_load($nid);
$field_date = field_get_items('node', $node, 'field_date');
$render_field_date = field_view_value('node', $node, 'field_date', $field_date[0]);

```

But the output I get is in "long" variant. Drupal.org says that by default it uses "default\_formatter" which is defined in `date_field_formatter_info()` (having inspected the code, I figured out that that 'default\_formatter' actually means 'long'). Well, I want it to be formatted in "medium" way. I write these lines:

```
$render_field_date = field_view_value('node', $node, 'field_date', $field_date[0], array('type' => 'medium') );

```

but it's still in its "long". What is wrong with the code?

# Answer
Solved that! I should have gone a bit deeper in the Date source code.

The solution is this line:

```
$render_field_date = field_view_value('node', $node, 'field_date', $field_date[0], array('type' => 'date_default', 'settings' => array('format_type' => 'medium') ) );

```
> 2 votes

---
Tags: entities, datetime
---


# Question
Title: Corporate website, each page different style
I need to create a corporate business website under Drupal 7, and on each page (home, about, sevices, contact, etc.) the design is really different.

What would be the best way to structure/build this in Drupal? I'm used to Wordpress theme per page, but this does not look like it's built in Drupal.

Like thi theme: http://demo.drupalizing.com/?theme=corporateclean http://drupal.org/project/corporateclean

The design change quite a bit for each page. But when I download the theme, I don't see how they did that, since there's only that general page...

# Answer
You can create a new theme using one of the many starter themes, and then override templates to get as specific as you please.

For example, to override a particular content type's look, you'd edit node--contenttype.tpl.php where contenttype is your custome content type.

The template guide contains further info, including naming conventions to get your templates applied in the right place.
> 1 votes

# Answer
In such case what I do is: I write the following code in my template.php of the theme

```
function themename_preprocess_page(&$vars) {

     if (isset($vars['node']->type)) {

     $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;

 }
    }

```

Then I create a page.tpl.php for each content-type. For example if it is for content-type hotnews, then I create a page--hotnews.tpl.php file in my templates folder. In page--hotnews.tpl.php I write the things that I want to appear in my hotnews page.

For the front page, I create page--front.tpl.php. And I write the things like menu, header and footer that are common in all pages, in html.tpl.php.
> 1 votes

---
Tags: theming, 7
---


# Question
Title: Button that executes php function, or custom VBO action
I have a function that pushes a node to a sugarCRM database. There have been some problems with the sugarCRM database recently and some of the nodes that were supposed to be pushed were not. I need to be able to build a button that can execute the function manually and push the selected node to the database. Is there a way that I can accomplish this via VBO?

# Answer
You can create a menu item that does what you want along the lines of

```
function YOURMODULE_menu() {

  $items=array();

  $items['sugarme/%'] = array(
    'title' => 'Send this node to sugarCRM',
    'page callback' => 'YOURMODULE_sugarme',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // other menu items here

}

function YOURMODULE_sugarme($nid) {

   if (YOURFUNCTIONTOSENDTHISNIDTOSUGARCRM($nid)) {
     return 'Sent to sugar';
   } else {
     return 'Send to sugar failed';
   }

 }

```

which in the very simple form above (no security, no argument sanity checks, etc) creates a path on your system `www.yourhost.com/sugarme/####` that will call your function with the nid passed to it.
> 3 votes

---
Tags: nodes
---


# Question
Title: Restrict creation of content type by user reference
I have two content types, Location and Event. The Location has a user reference field containing the owner of the Location. The Event type has a node reference field containing the Location node it belongs to. Now I want the owners to be able to create Events only for *their* Locations based on this reference field.

Currently I "solved" this by having a Views reference in the Event type that only shows Locations where the author is "Drupal"-owner of the nodes. But this has two downsides:

1. Administrators get an empty Views reference and thus can't save Events
2. I have to change the author of the Location node instead of using the user reference field I added

So, is there a way to solve this?

# Answer
I would create a custom module that uses Entity Field Queries to do the following:

1. First, use EFQ to select nodes of type "location" where "user" matches the "user" specified in the selected "event" AND also the "location" value matches the "location" specified in your event. This has essentially the same effect as the Views solution you've worked out, I believe.
2. The advantage over Views here is that now you can node\_load() the nodes you find or you can execute more complex logic if there are no matches (i.e. if the user should not have permissions).
3. Use hook\_node\_grans() or hook\_permission as needed.
> 0 votes

# Answer
Check out the http://drupal.org/project/nodeaccess\_userreference and http://drupal.org/project/nodeaccess\_nodereference modules. Extremely flexible for creating entityreference based view/update/delete permissions.
> 0 votes

---
Tags: 7, views, entities, users
---


title: Does #AJAX work on the body field?

text:
# Question
Title: Does #AJAX work on the body field?
Does the #AJAX FAPI property work on the body field? I've got it to work with things like submit buttons and textfields such as the title. When I alter the node edit form, and attach an `#ajax` array to the body field though, nothing happens. I've tried multiple event types (keyup, keypress, focus). Is there anything special that needs to be done to get `#ajax` to work on the body field?

```
  // This works (creates backend xhr call).
  $form['title']['#ajax'] = array(
    'wrapper' => 'autopreview',
    'callback' => 'autopreview_ajax_callback',
    'method' => 'replace',
    'event' => 'focus',
  );

  // Doesn't work.
  $form['body']['#ajax'] = array(
    'wrapper' => 'autopreview',
    'callback' => 'autopreview_ajax_callback',
    // 'method' => 'replace',
    'event' => 'focus',
  );

  // Doesn't work.
  $form['body']['und'][0]['#ajax'] = array(
    'wrapper' => 'autopreview',
    'callback' => 'autopreview_ajax_callback',
    'method' => 'replace',
    'event' => 'focus',
  );

```

# Answer
> 1 votes
According to the FAPI docs textareas do support `#ajax`, yes.

I'd imagine the problem is because you'll be using a WYSIWYG editor on that field. Such an editor will replace the textarea with an iFrame, and the AJAX events aren't bound to that iFrame (or its inner textarea), so won't get fired when you change the text.

If that is the case, I don't think there's any easy way to overcome the problem except to turn of the WYSIWYG editor for that field.

---
Tags: 7, forms, ajax
---


# Question
Title: I get an exception when re-installing a module
I have re-installed modules before, but I can't get it this time. These are the steps I take:

1. Uninstall the modules (by deselecting them on the module list and clicking submit changes)
2. Remove the Module Files from the module folder
3. Check the database for any potential left over tables (specifically sms\_feed)
4. Check the system table for any left over rows dealing with my modules
5. Delete anything related to my modules in the database
6. Clear the cache
7. Reinstall the modules

I always get the following error:

> DatabaseSchemaObjectExistsException: Table sms\_feed already exists. in DatabaseSchema-\>createTable() (line 657 of C:\xampp\htdocs\amaware\includes\database\schema.inc).

Do you have any idea?

# Answer
What you have done in the first step is disabling the module, not uninstalling it. To uninstall it, you need to click on the "Uninstall" tab, select that module, and then click on the "Uninstall" button.

The exception raised from DatabaseSchema::createTable() is because it contains the following code.

```
  if ($this->tableExists($name)) {
    throw new DatabaseSchemaObjectExistsException(t('Table %name already exists.', array('%name' => $name)));
  }

```

The code in DatabaseSchema::tableExists() is then the following one.

```
  $condition = $this->buildTableNameCondition($table);
  $condition->compile($this->connection, $this);
  return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();

```

You could also manually remove the database table, but if the information about that table is still contained in information\_schema.tables, `DatabaseSchema::createTable()` will raise an exception.
> 2 votes

# Answer
The step you are missing I believe (and what is likely causing the "table still exists error") is after your step 1 (and before step 2) you should visit admin/modules/uninstall (on D7) admin/build/modules/uninstall (on D6). Check the module you previously disabled and click uninstall. This should remove all associated tables and will allow you to avoid your steps 3, 4 & 5.
> 0 votes

---
Tags: database
---


title: How do I create a block?

text:
# Question
Title: How do I create a block?
I am trying to create a block using hook\_block, in Drupal 7. I have the following code in my module file (module.module its not actually called that but, this is an example).

```
function module_race_results_block_info($op = 'list'){
  $block = array();

  if ($op == 'list') {
    $block[0]['info'] = t('Race Results Block');
  }

  return $block;
}

function module_race_results_block_view($delta = 'raceresults') {
  $block = array();

  switch ($delta) {
    case 'raceresults':
      $block['content'] = module_race_results();
      break;
  }

  return $block;
}

function module_race_results() {
  $content = "Testing Race Results Block";

  return $content;
}

```

How can I test this? The block is not showing up in the blocks list (/admin/structure/block).

# Answer
> 2 votes
Quickly, it's `$block['content']=module_race_results();` in your `hook_block_view()`, and `$blocks['raceresults']...` in your `hook_block_info()` so it matches your `hook_block_view()`.

More precisely, this is probably more of what you are trying to accomplish:

```
function module_race_results_block_info() {
  $blocks = array();

  $blocks['raceresults']['info'] = t('Race Results Block');
  // any more blocks here

  return $blocks;

}

function module_race_results_block_view($delta) {
  $blocks = array();

  switch($delta) {
    case 'raceresults':
      $blocks['subject'] = t('Race Results');
      $blocks['content'] = module_race_results();
      break;

    // any more blocks here

    }
  }

  return $blocks;
}

function module_race_results() {
  $content = "Testing Race Results Block";  // eventually this should become a renderable array instead of plain text or html
  return $content;
}

```

---
Tags: blocks
---


# Question
Title: Any modules for editing files in the browser?
I need a way to edit any file in my template directory, but not through a local editor and then by using FTP, but by using my browser. I was wondering if anybody knows a Drupal module or another product that lets you do this.

# Answer
Well, elFinder, and this page may help you. At least elFinder supports inline file diting. Good luck!
> 2 votes

---
Tags: files
---


# Question
Title: How much server-side resources does the Omega theme use? Is the Omega theme scalable?
The omega theme is pretty 'fat'. Currently its probably the biggest theme on drupal.org. You can do anything and everything in the GUI. You can completely customize the layout, turn responsive design on/off...I could go on for awhile.

My question is, do all of the extra settings eat up server resource to serve a page to the client? If I have a website that receive 100,000+ page visits a day, should I use omega, or create my own theme?

# Answer
> 7 votes
Yes there is some extra overhead involved (especially at the templating level); how much this will effect your response times will completely depend on the setup of your server. An easy test would be to enable the basic Garland theme, profile the site, then enable the Omega based theme and do the same. You should get a pretty good idea of how much extra overhead you're likely to get for a single page load.

If you're able to, go further. Stress test your server (using something like ab) with both themes enabled. That'll give you an even better idea.

If you've got a site with 100,000+ visitors per day though, your efforts might be better spent setting up a decent caching strategy, both in Drupal and on the web server. That will help to offset a lot of the overhead that Omega/Alpha can add.

# Answer
> 1 votes
I cannot speak to your specific question, as I have not measured the performance of Omega myself. However, you should see John Albin's comments in http://www.palantir.net/blog/all-new-zen-same-guiding-principles, which speaks briefly on the issue of performance. It would For a site with 100k+ hits per day, I would recommend learning zen grids and building your theme based on zen. Omega will give you faster development time, but you will gain some performance benefit from spending extra time on Zen. Amazon claims small decreases in performance can have a measurable effect on sales, so spending extra money on performance will likely pay off if your site is commercial.

You should also employ a good cache strategy and take measurements on your results using your own site.

---
Tags: theming
---


# Question
Title: How can I specify the URL alias when importing nodes into Drupal 7 (with the Feeds module)?
I'm importing a site into Drupal 7, using the Feeds module. I don't see any way to specify the URL alias for each node (which I want to control on most every page). How can I do this? (If the Feeds module cannot do it, is there a way to do it in bulk after the import?)

***Update***: in case it's not clear, I want to have a column in my CSV that lists the URL alias that I want for a particular node. I don't want the URL automatically generated. I want completely control over the URLs, without having to manually specify them in the Drupal admin UI.

# Answer
Try the Pathauto module to do this. I found it helpful for auto-aliasing URLs in bulk, and it is customizable... it works pretty well if you use taxonomy to improve work site flow.
> 2 votes

---
Tags: 7, feeds, uri, path-aliases
---


# Question
Title: Preventing a duplicate node from being created
I'm building a site with a content type that includes a URI. Is there a module that would prevent a node of that content type being created if the URI it includes is already referenced in an existing node? i.e., so that the site can't have two nodes with the same URI field?

# Answer
> 4 votes
There is the Unique Field module that does this.

# Answer
> 1 votes
There might be a quicker solution for this. If not, you could use hook\_validate() function. For e.g your\_module\_name\_validate(). Inside that function, you could make a query to the database to make sure the the entered url does not match with the existing url in the database for that cck field.

---
Tags: entities
---


# Question
Title: How can I put a time-delayed lock on a node?
I'm using Drupal 7, and would like to add a time-delayed lock to a specific node type: when a node of that type is created, the creator of the node has fifteen minutes to edit that node. The node then locks and its state changes in workflow.module.

What's the best way to achieve this result?

# Answer
http://drupal.org/project/user\_alert is a good module combined with "Job scheduler" or a trigger module for timing should be Fine. but you may have to get creative with the setup. also try http://drupal.org/project/notifications
> 0 votes

---
Tags: nodes, workflows
---


# Question
Title: Shipping address, rates selection asked even if there's no physical products
We have made a Drupal 7 website with Commerce module. The website has a combination of physical and non-physical products.

**The shop has a small problem (or potentially big), in that it asks for shipping address and shipping rates (flat rate) from the shopper even if they only buy non-physical products.**

We have used the Physical Product module and Physical Fields module to accomplish the physical product functionality.

I found a similar question, regarding a different (older) commerce version (7.x-1.0), but this question had no accepted answer, so I decided to ask my own question for my relative version of Commerce (7.x-1.3).

Any help, pointers on where to look/investigate this problem, or even a confirmation whether the single answer posted on the similar question is the right way to go about accomplishing this would be greatly appreciated.

If you need any more information from me, please ask.

---

Ok I just found a Rules rule with machine name `commerce_shipping_method_flat_rate`. So I added a condition to this rule "The order contains shippable products". I also unchecked the tickbox labelled "Require a shipping service at all times, preventing checkout if none are available." in Store-\> Configuration-\> Checkout Settings, and Shipping Service pane config.

This seemed to have done the job. However I had the Shipping Service pane in the "Shipping" part of the Checkout process, so now if you're buying non shippable products, you enter your details in the first page, then go to the Shipping page it displays a blank form with a Continue or Go back buttons to proceed to the Review page.

Is there a way to go straight to the Review page if there's no shippable products?

# Answer
> 0 votes
I've been able to sort this out by adding the condition "Commerce order contains shippable products" supplied by the physical product module to the existing shipping rules, and also added a new shipping flat rate service called "No Payment". And this new flat rate shipping service is £0.00 amount and checks for condition "**NOT** Commerce order contains shippable products" (Negated, hence the "**NOT**").

I also unchecked the tickbox labelled "Require a shipping service at all times, preventing checkout if none are available." in Store-\> Configuration-\> Checkout Settings, and Shipping Service pane config.

---
Tags: 7, commerce
---


# Question
Title: Change #default_value of a textarea on admin pages
I need to change specific textarea max-length (currently 100 letters).

Where is the default value stored or how it is possible to override this setting?

# Answer
The teaxtarea form field doesn't have any property for the maximum length of the accepted text. The module showing the textarea can implement a form validation handler to limit the length of the entered value, and (generally speaking) that limit is not saved in a module settings; it is generally hard-coded.

In the case the value contained in the textarea field is saved in a database table created from the module showing the form, there is another issue: The value contained in the textarea field must be contained in the database field. If it is longer than what the database field can store, you would get SQL errors.
> 0 votes

# Answer
Is this for editing content? If it is, edit the content type that you want to change, find the field with the text area you want to change, and update the number of rows you want displayed by default.
> 0 votes

---
Tags: 6
---


title: Running feeds in order

text:
# Question
Title: Running feeds in order
I just ran into a situation where I need to run three imports, one after another using the same file providing successful import. Does anyone know how to do this? I looked briefly at Feeds rules but I don't think that will work unless I'm missing something?

Thanks

# Answer
I would recommend using a small custom module to add your own queue:

http://api.drupal.org/api/drupal/modules!system!system.queue.inc/group/queue/7

Then use your callback to run each item through feeds.
> 1 votes

---
Tags: 7, rules, feeds
---


# Question
Title: How can I change the year range displayed by a FAPI date field?
I have created a FAPI form with an element of #type =\> date and it works as expected.

```
$form['date'] = array(
  '#type' => 'date',
  '#title' => t('Event date:'),
);

```

However, the options displayed in the year field range from 1900 - 2050. I would like to be able to limit this to a much smaller range starting with the current year. What would be the best way to accomplish this?

# Answer
If you don't want to change every date field—which might have side effects else where on the site—you can easily do it on specific form elements.

```
function example_form(&$form, &$form_state)  {
  $form['birthday'] = array(
    '#type' => 'date',
    '#title' => t('Birthday'),
    '#required' => TRUE,
    // Add a second process function so we can change the years:
    '#process' => array('form_process_date', 'example_fix_year_range'),
  );

  return $form;
}

/**
 * Follow form_process_date() and re-do the years.
 */
function example_fix_year_range($element) {
  $year = format_date(REQUEST_TIME, 'custom', 'Y');
  $element['year']['#options'] = drupal_map_assoc(range($year - 120, $year));
  return $element;
}

```
> 7 votes

# Answer
You can implement hook\_element\_info\_alter() to alter the definition of the form element given from system\_element\_info().

The default definition is the following one:

```
  $types['date'] = array(
    '#input' => TRUE,
    '#element_validate' => array('date_validate'),
    '#process' => array('form_process_date'),
    '#theme' => 'date',
    '#theme_wrappers' => array('form_element'),
  );

```

form\_process\_date() is the function that set the year sub-element. If you replace it with your own process function, or add it, you can alter that limit.
The code used from the default preprocess function is the following one.

```
  // Output multi-selector for date.
  foreach ($order as $type) {
    switch ($type) {
      case 'day':
        $options = drupal_map_assoc(range(1, 31));
        $title = t('Day');
        break;

      case 'month':
        $options = drupal_map_assoc(range(1, 12), 'map_month');
        $title = t('Month');
        break;

      case 'year':
        $options = drupal_map_assoc(range(1900, 2050));
        $title = t('Year');
        break;
    }

    $element[$type] = array(
      '#type' => 'select',
      '#title' => $title,
      '#title_display' => 'invisible',
      '#value' => $element['#value'][$type],
      '#attributes' => $element['#attributes'],
      '#options' => $options,
    );
  }

```

As alternative, you can implement hook\_preprocess\_date(), which is executed when theme\_date() is called. (In Drupal 7, every theme function executes preprocess hooks, not just a theme function using a template file.) Doing so, you can alter the form element the preprocess function gets in `$variables['element']`.

I would rather use the latter method, even though both the methods would work; it is simpler, as it doesn't require two hooks.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Drupal7 REST webservices API KEY vs OAUTH two-legged authentication for clientside JS consumer library
I'm working on an Drupal7 API, using REST services, and consumer JS library (no server code). I'm not trying to authenticate/authorize the end-users, only to identify and allow access to the 'application' using an API KEY.

The goal is to have the 'developers' create an account, request an API KEY, register domains for this api key, and use this key to 'identify' their application to the Drupal7 API. This is pretty much the same API-KEY model that Google Maps is using in v2.

I've looked into OAUTH 2legged approach, which would have been great if my client library was running on the server side, so the secret key wouldn't be exposed, but in our case, the library *is* JS only (client side), and it doesn't seem a good idea to expose the secret key.

Am i missing something about OAUTH that will allow this? Any pointers will be welcome.

Thanks!

# Answer
> 0 votes
The solution came from Kyle Browning (thanks!) - the current dev version of services 7.x-3.x-dev has support for the following OAuth authentications methods:

* None, OAuth authentication will be disabled by default
* Unsigned with consumer key
* Consumer Key, also known as 2-legged OAuth
* Consumer key and access token, also known as 3-legged OAuth

With this version I ended up using the consumer key for the client libraries as identification token for applications.

---
Tags: javascript, services, users, 8, authentication-authorization
---


# Question
Title: Overriding template without killing the page?
I would like to override the template for node creation. In the past when I've overridden a template, I've usually just copied the theme's generic template for that type (page, node, etc), given it the proper name, and edited it as I saw fit.

Now, for the first time I need to override a template that I can't simply make a copy of. I'm editing the node editing template and I have created a file with the correct name and location and everything, and it overrides the edit form, all right. Now there's nothing on the page except what's in my new template (unsurprisingly).

So, how do I create a template without getting rid of what was already there? Or, where can I find the template that Drupal is using to create my node edit form?

I'm using Drupal 7 and the theme is a custom one written by the previous maintainer of the site. It's not a child theme of a base theme, it's all by its lonesome.

# Answer
> 2 votes
Because the Node Edit page is a form, it is recommended that you use hooks for theming it. You can create custom template file for it, but theming it within template.php is the most common solution.

Theming Node Forms in Drupal 7 is the best resource I've seen so far for this.

---
Tags: forms, theming
---


# Question
Title: List all tags associated from specific content type only?
I'm trying to make a view which is listing all taxonomy tags associated from nodes of a specific content type only.

How can I make this?

I can make a view which is listing all taxonomy tags, but I can't figure out how to filter it with a specific content type only.

Any ideas?

\Thomas

# Answer
Thomas - the answer is going to assume you are using Drupal 7, since you didn't specify.

Likely, the issue here is that you are using **Taxonomy terms** as the base of your view and therefore not able to select **Content: Type** as a filter.

To get that filter to show up, you need to add a **Relationship** (under the Advanced section of the view options) for **Taxonomy term: Content with term**.

After you do that, then **Content: Type** will show up in your filter list.
> 1 votes

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


# Question
Title: add pre-registered links to user menu via hook_menu
One step before being forced to using internationalization (i18n) module!

I'am trying to add translatable `Register` and `Login` links to `secondary menu` via `hook_menu` in way which `user module` dose for `Account` and `Logout` links via `user_menu()`:

```
// user module:

function user_menu(){
  ...
  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );
  ...
}

```

but as this two links (user/register and user/login) re pre-defined via user\_menu(), I whould like to know how can I add my links to primary menu?

so simplified question is:

how can I add pre-registered links to menu via hook\_menu() ?

# Answer
> 0 votes
You can use `hook_menu_alter()` to override properties for existing paths:

```
function MYMODULE_menu_alter(&$items) {
  $items['user/logout']['menu_name'] = 'primary-links';
}

```

# Answer
> 0 votes
With Clive's help, here this final code:

```
<?php

function MYMODULE_menu_alter(&$items) {
  $items['user/register']['menu_name'] = 'user-menu';
  $items['user/register']['type'] = MENU_NORMAL_ITEM;
  $items['user/login']['menu_name'] = 'user-menu';
  $items['user/login']['type'] = MENU_NORMAL_ITEM;
}

```

---
Tags: 7, routes
---


title: Slideshow module in D7

text:
# Question
Title: Slideshow module in D7
Is there any slideshow module in D7 similar to this one - http://www.cnngo.com/shanghai/life/facekini-woman-chinas-latest-beach-sensation-680659

In D6 the Views Slideshow can do this but not sure in D7. Any ideas?

# Answer
> 1 votes
The views slide show in Drupal 7 in my opinion is even better than in 6 as it start right of the bat with the jQuery Cycle library and that alone will give you a lot of nice effects plus all the extra tools like pagers, counters and controls.

Check the last tutorials on the modules pages page to learn more about the installation and configuration including the thumbnail pagers.

---
Tags: 7, media, javascript
---


title: Views Link Issue

text:
# Question
Title: Views Link Issue
I am having an issue with a views photo gallery. I am using something similar to this http://www.lullabot.com/articles/photo-galleries-views-attach the only difference is I am using Drupal 7.

My question is how could I make the image that shows on the galleries page link to the gallery itself and not the single image?

Thanks, Justin

# Answer
> 1 votes
The secret is on rewriting the link back to the gallery on the image node so that instead of the regular text it will show the image.

In your view fields:

1. Add the image and set the format to thumbnail and hide it from the display.
2. Add the entity that links back to the gallery and make sure to check "Link label to the referenced entity".
3. Go to the rewrite results section and in the "Rewrite the output of this field" add the replacement pattern that correspond to your image and click "Apply".
4. Limit the view results to 1 and hide the pagination.

---
Tags: 7, views
---


# Question
Title: Deciding between (CCK) Fields and Taxonomy for a list of options. Pros and cons?
Sometimes I wonder why to choose *Term reference* or a regular *List (float/integer/text)* over the other, when I would like to "force" my users to select one or multiple values from a list.

Taxonomy vocabulary and a ***Term reference*** field **pros**:

* new terms can be added right in the textbox (see *"Autocomplete term widget (tagging)"*)
* separate sites are created automatically for the different terms where referenced nodes are listed (no separate view has to be added, but can be if necessary)
* views can easily be created
* terms hierarchy
* terms can be reordered easily
* list of terms can be extended easily
* terms are easily fieldable, which means more display possibilities when viewing a given node
* ?

***Term reference*** field **cons**:

* ?

***List (float/integer/text)*** field **pros**:

* views can easily be created
* the field is closely related to the given content type, no separate vocabularies have to be added
* ?

***List (float/integer/text)*** field **cons**:

* after adding some nodes with the given field, and going to *"Field settings"* for changing them, I get the message: *"There is data for this field in the database. The field settings can no longer be changed."* (example screenshot)
* ?

I would appreciate if you could tell me some other pros/cons over the other when having to force the user to select some values from a list.

# Answer
> 3 votes
This is my personal opinion:

Use taxonomy terms is you might need to change them later, re-arrange them, add or remove (yes remove, bad, but ok), share them between content types and have a page per each listing all the content that have it and also provide an RSS feed of the same.

Use options list or CKK option list is you know for sure the options will never change, if you need to have a key-value configuration if you want to share them between content types, but don't want to have listing pages of the content that have it. Also fields can have grain level permissions and don't generate RSS feeds.

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


# Question
Title: How to set Media Styles in Media 7.1.2 / Media 7.2.X?
Where is the latest form of the component in the Media project family that allows styles to be defined for Media files?

I see a lot of references to the idea that the Media module contains, once contained, or can be compatible with, a UI component that is similar to the Drupal 7 core Image Styles system that allows formats to be defined. Apparently, once upon a time this lived at `/admin/config/media-image-styles`

There's a module, Styles, by Aaron of Media fame, that has a sub-module called File Styles. On the Styles project decription, it suggests that the Media module implements the API this provides in its bundled sub-module Media Styles. But the latest 7.2.x dev (and also, the latest stable version of the 7.1 branch) of Media that I have downloaded contains no such module, the URL path given for it above goes nowhere, and I can't find any such module as a seperately distributed module. Styles contains a UI module, but this seems to be unrelated to Media, and Styles hasn't been updated since 2011, whereas Media has been in near-constant development since then (with latest Media 7.2.x dev enabled, for me the Styles UI url crashes out with a fatal error `Call to a member function getExternalUrl() on a non-object in...` ). Also, Styles isn't even mentioned on the current Media project page.

From the way people talked about this media styles UI, it sounds like it was once a very important part of the Media project. I understand the Media project has been in a state of flux for years and documentation has lagged behind the current state of the project.

Where is the latest form of that component that allows styles to be defined for Media files?

Here's some (seemingly now all out of date) related reading:

---

Edit: Found a clue, buried at the bottom of a "Configuration" documentation page:

> The Media module used to rely heavily on the Styles module before Media was converted to prefer the file entity and file fields... defining new 'display' or view modes... can be implemented using http://drupal.org/project/entity\_view\_mode

But I can't see anything in that linked module that seems to support the kind of functionality I've seen discussed. There's a limited tutorial for the 7.2 branch which involves using Entity View Mode, but it uses it to define image styles for images, using the regular image style interface. Doesn't look to be anything for file styles for non-image files such as videos, or anything that could do anything more advanced, like have one style that shows a video's thumbnail image and another style that shows a video player. The search is still on...

# Answer
> 30 votes
A lot has changed since the madness that was http://drupal.org/node/1092444. Thankfully, theming and setting display formatters for file entities is now much easier and more straightforward.

**The following documentation is for Media 2.x and File Entity**, although much of it works with Media 1.x with slight alterations (e.g., in Media 1.x, the link to the "File Types" page is in Configuration instead of Structure).

# Displaying Media

The File Entity and Media modules work together to provide a unified method for storing, managing, and displaying Media in Drupal. They allow a user to create file fields that can be configured to store and display many different types of media, including images, video, and audio. among others. In order to display these different types of media, file fields need formatters, often provided by the module that provides the Media type, and a little extra configuration.

## Definitions

I'll explain a couple of the moving parts first, and then get into customizing the display of files on a site.

### File types

Files are grouped into *File Types*. Each file type is defined by a list of mime types, a universal way of specifying file formats on the internet. The default file types are Application, Audio, Image, Text, Video, and Other. There is currently no way to define new file types in the UI.

### View Modes

View Modes are used to tell Drupal 7 (and soon 8) that a piece of content is in a certain context. The content can then be altered or displayed in a way that best suits that context. Two view modes that most people are probably familiar with are the default **teaser** and **full** modes. Custom view modes can be defined with modules like Entity View Mode, Display Suite, or in a custom module with `hook_entity_info_alter()`.

## The Good Stuff, or: Managing the display of your File Field

A file field's display is managed per **file type**. Navigate to Structure -\> File Types. You will see a list of available file types with links to "Manage fields", "Manage display", and "Manage file display" for each.

### Manage Fields

The File Entity module makes all files full fieldable entities, the same as nodes and taxonomy terms. Just like in the "Content types" section, you can add custom fields to each file type.

### Manage Display

Again, like in "Content types", you can manage the display of custom fields on each file type. **This section does not control the formatting of the files themselves**, only the display of fields attached to the file entity.

In this section you will also see a toggle for "Custom Display Settings". When expanded you can enable and disable view modes available for this entity. **A view mode must be checked here in order for it to be available in "Manage File Display".** At this time it's recommended to use only custom view modes defined by the user and the following default view modes; the rest are left over from Styles module integration and will eventually be removed:

* "Teaser" (Currently not included by default. You can add it with the patch in the issue above or define it as a custom view mode)
* "Full"
* "Preview" (Used in admin contexts, e.g., for placeholders in WYSIWYG fields, in the Media browser, and in the Media field widget)

### Manage File Display

**In "Manage File Display" you can configure formatters for your file types** (yes!). Many Media provider modules add their own formatters here; for example, Media: Youtube and Media: Vimeo both provide a "Preview Image" and "Video" formatter.

Formatters can be enabled and configured for each view mode enabled in their file type's "Manage Display" section. For example, a user may want to display a Media: Vimeo preview image when a node is viewed as a teaser, the Vimeo video when the full node is viewed, and a video with different width and height formatter settings when the node is viewed with a custom view mode called "video gallery". Many formatters (notably "Image") allow the user to select the image styles they have defined in Configuration -\> Image Styles.

Because multiple media providers can use the same field, formatters are arranged in a top-to-bottom cascade. Drupal will use the first formatter that can be applied to the output of a field. If a video field enables the "Media: Youtube Video", "Media: Vimeo Video", and "Large filetype icon" formatters for the "Full" view mode, Drupal will use the Youtube formatter if the file's mime type is `video/youtube`, the Vimeo formatter if the mime type is `video/vimeo`, and fall back to the large filetype icon if the mime type is `video/{anything else}`.

### Configuring the File Field to display using "Manage File Display" settings

In order for the file field to display using the formatters defined in "Manage File Display", it must be set to display the "rendered file". Navigate to the "Manage Display" page for the *content type* that contains your file field. Choose "Rendered file" as the file field's format for all view modes in which you would like to use the formatters defined in "Manage File Display".

## Further Theming

You can create custom theme functions and template files for even more control with *theme hook overrides*. The theme suggestions provided by the File Entity module are:

```
file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}

```

Replace all '/' and '\__' in mime types with '\_' for theme functions and '-' for template files.

Some Media provider modules replace these with their own templates and theme hook suggestions. You can view all available theme hook suggestions with the Devel Theme Developer module, Mothership's Poor Themer's Helper, or hopefully consult the provider's docs for more info.

## Outro

Hope this helps. I plan on adding this to the Media documentation, so if I missed something, misspoke somewhere, or a section needs clarification please let me know.

And some short answers to the OP's specific questions:

* Media 1.x vs 2.x: even though 2.x is unstable, it's as reliable as many stable version modules on Drupal.org. I think it's worth using for the vastly improved features, but because there's so much work going on support in the issue queue is slow, and as with any dev branch new updates may break your implementation. Still, I use it on production.
* Media is in development. Some things don't work as you would hope yet (e.g., non-image WYSIWYG integration). But it still works better at what it does than the combination of modules you have to install to do what it does without it. And it's getting better.

---
Tags: 7, media, theming
---


# Question
Title: Feeds with Xpath Parser won't import images using image URL in XML file
Importing images into a multi-valued image field using image URLs from an XML file is not working for me. The Xpath Parser debug output shows the multiple image URLs being parsed correctly, but the images don't get imported. No problem with other ordinary fields.

The XML structure is:

```
<units>
  <unit>
    <unit_details>
      <images>
        <image>
          <uri>
             http://www.example.com/files/content/villa-102-1.jpg
          </uri>
        </image>
        <image>
          <uri>
             http://www.example.com/files/content/villa-102-2.jpg
          </uri>
        </image>
      </images>
    </unit_details>
  </unit>
</units>

```

The context is: `//unit`

The Xpath query for the image field is: `unit_details/images/image/uri`

I played around with the image grabber module for feeds, but it failed also - doesn't seem suited to this task.

1. Is it possible to import images using the image URL from the XML file?
2. Is it possible to import multiple images into a multi-valued image field?

I'm using Feeds version 6.x-1.0-beta12+18-dev, and Feeds Xpath Parser version 6.x-1.12

---

UPDATE:

I was able to import images using the CSV importer and the image URL, so this appears to be a problem with Xpath Parser.

---

UPDATE 2:

I'm seeing no errors in the dblog or the server log. That patch is for D7. The images do not show up in the node display, but the other fields do.

Looks like the "enclosure" error gets thrown if the local file name isn't in the right form, but I just have an external URL. As I mentioned above, the image with the same URL does get imported using the CSV parser, so it doesn't appear to be a problem with the Feeds module, just the Xpath Parser.

The relevant code in D6 (FeedsParser.inc) is:

```
    /**
       * @return
       *   A path pointing to a file containing the resource referenced by the
       *   enclosure. This method downloads the resource if it is not local. The
       *   file path must be considered temporary and is only valid for the current
       *   page load.
       *
       * @todo Get file extension from mime_type.
       * @todo This is not concurrency safe.
       */
      public function getFile() {
        if (empty($this->file) && $this->getValue()) {
          // Check if this enclosure contains a local file.
          if (!parse_url($this->getValue(), PHP_URL_SCHEME)) {
            if (file_check_location($this->getValue(), file_directory_path()) || file_check_location($this->getValue(), file_directory_temp())) {
              if (file_exists($this->getValue())) {
                $this->file = $this->getValue();
                return $this->file;
              }
            }
            throw new Exception(t('Invalid enclosure %enclosure', array('%enclosure' => $this->getValue())));
          }
          $filename = basename($this->getValue());
          if (module_exists('transliteration')) {
            require_once drupal_get_path('module', 'transliteration') . '/transliteration.inc';
            $filename = transliteration_clean_filename($filename);
          }
          $dest = file_destination(file_directory_temp() .'/'. $filename, FILE_EXISTS_RENAME);
          if (ini_get('allow_url_fopen')) {
            $this->file = copy($this->getValue(), $dest) ? $dest : 0;
          }
          else {
            $this->file = file_save_data($this->getContent(), $dest);
          }
          if ($this->file === 0) {
            throw new Exception(t('Cannot write content to %dest', array('%dest' => $dest)));
          }
          $this->delete_file = TRUE;
        }
        return $this->file;
      }

}

```

# Answer
1. yes it's possible.
2. Feeds is buggy sometimes.

Try this patch: http://drupal.org/node/1482530

Can you give more information about what isn't working? What errors are produced etc.
> 0 votes

---
Tags: media, importing-exporting, feeds
---


# Question
Title: Rename images while uploading and put in specific folder
I am using drupal 7.

I have created an Advertisement content type. This contains a field where end user can upload images of their Brands.

I want to rename the images which are uploaded by the field of content type and put in specific folder named user id of the user. So uploaded file location would look like it: /sites/default/files/images/user\_id/

# Answer
File (Field) Paths let you set file name and file path for file field:
> 2 votes

---
Tags: entities, files
---


title: cck dynamic select list in a array

text:
# Question
Title: cck dynamic select list in a array
I have used the code like this

```
$ch2 = curl_init("http://openexchangerates.org/api/currencies.json");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);

$json2 = curl_exec($ch2);
curl_close($ch2);

$currency = json_decode($json2);

$opts = '';
foreach($currency as $key => $val)
{
$opts .=$key.'=>'.$val.',';
}

return array($opts);

```

Here I am getting the combo like this everything in a single line

```
AED=>United Arab Emirates Dirham,AFN=>Afghan Afghani,ALL=>Albanian Lek,...

```

What can I do for all the currencies listing 1 by 1 ??

# Answer
> 1 votes
This works for me:

```
<?php

$ch2 = curl_init("http://openexchangerates.org/api/currencies.json");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);

$json2 = curl_exec($ch2);
curl_close($ch2);

$currency = json_decode($json2);

return (array)$currency;

```

---
Tags: entities
---


# Question
Title: Is there a way to create field collection table dropbox for added content in form
Im creating a form in content type form format I will enable public users to create content type for this form.

I have integrated a field collection module within this form like adding multiple participants

The fields in the field collection contain fields for name, address, contact info, etc.. The user can add as many participants they want in the field collection.

My question is: Whenever i try to click the button "add another Item" the whole field collection form stacks up in the page. So when I add 10 participants it will make the page longer and difficult to navigate.

What im thnking is, is there a way that i can create a table that contains the added info (displaying limited fields only) when I click the add another item.

similr to hierarchical Hierarchical Select dropbox function if you are familiar with this

Is there a module that performs similar to this?

# Answer
> 0 votes
There's the field collection table module which provides a table-based widget and formatter for field collection fields.

It's not the same as the hierarchical select Dropbox but its worth a look, and would probably serve as a good place to start if you're thinking about coding your own solution.

---
Tags: 7, entities
---


title: Designing User Profile Page Manually

text:
# Question
Title: Designing User Profile Page Manually
I am thinking of designing users profile page manually. But as a beginner I need your ideas. Can you tell me about what to know all of its variables to design it?

# Answer
In order to add your own custom template file, you should create a new file named `user-profile.tpl.php` in your theme directory.

To see what variables that are available in the template, checkout the default one, that is located under `modules/user/user-profile.tpl.php`.

Have a look at user profile
> 3 votes

# Answer
Drupal 7 core contains Profile, you can add as many fields as you like to it. Once that is done,

1. you can use the Panels module, to oevrride the template of user profile page.
2. Use context and take the user id as argument from the URL, this should make the user object available to the panels.
3. Now you can add you fields as you want.
4. You can group them or add them in any layout as per you design using Panels itself.
5. Write CSS.

The beauty of this approach is it will avoid writing code all you will have to write is CSS.

Cheers, Swarad
> 0 votes

---
Tags: users
---


# Question
Title: Update node with services doesn't work for text_list widget
I'm setting up a REST server with Drupal 7 and Services 3.x.
Everything work fine (authentication, node creation, etc..), except that I can't update a text\_list field of a node.
I've tried to use &node\[title\]=testnode&node\[type\]=story&node\[field\_test\]\[0\]\[it\]\[value\]=testtting as suggested in the Services Handbook. The node is updated (I get the system message for successfully updating), all fields are updated, except the selectlist.
Anyone facing the same problem has found a solution?

# Answer
> 1 votes
Maybe how you are updating the node i.e node\_save() , The $node object that needs to be passed might not have the correct structure for the select list,

```
$node->body[LANGUAGE_NONE][0]['format'] = 'something';

```

You can always try to node\_load($nid) and watchdog it to see the structure of your select field, and then verify if you are creating the $node object correctly before doing node\_save().

This is just my guess, I can provide more correct answer once I can see the relevant code.

Cheers

---
Tags: 7, entities, services
---


# Question
Title: hook_node_load for currently viewed node?
I am trying to modify $node via hook\_node\_load but I do not have the current node in the list of $nodes handled by hook\_node\_load when I check it with devel's dpm. I only have some nodes from a node\_load\_multiple call I make in the module. Should I use hook\_node\_view instead? But hook\_node\_view says it can only modify node content.

# Answer
It depends on when and where you trying to modify the $node. hook\_node\_load runs every time a node is loaded,whereas hook\_node\_view runs only when a node is about to be rendered on the page.

The reason you might not be having the node id in question in you hook\_node\_load may be because the context in which you are calling hook\_node\_load might be wrong. In order to test you can create a dummy callback and call the node\_load() in it with you nid in question. You can see that once you call the node\_load() api, it will invoke a call to hook\_node\_load.

Cheers
> 1 votes

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


# Question
Title: How to have separate private comments for nodes apart from the general comments?
I have a specific requirement. Apart from the general comments which everyone can view or post for my custom node I also require private comments thread which will be shared only by the node created user and selected few. Using the same comments form will not work as it will be viewed by all. Any inputs on achieving this?

Thanks.

# Answer
For Drupal 7 see the Reply module. It lets you create your own set of "comments" attached to any Entities you want.

With some custom code you could limit the field to a specific user role or set of users. Be sure to read the README in the module.
> 0 votes

# Answer
If you are up for a bit of code you can try the following approach,

Create a content type "private comments", it will have the title and body field that you need by default, you need to add a node reference field to the content type on which you want this private comments enabled. Now you need to create a block that will render the node add form for this content type. You can then enable this block where you want your private comments.

On the submit function, the title and body will be saved by Drupal, you need to add a submit handler so that the reference between your content type and comments is saved.

The advantage of creating a content type is you will get integration with views and you can then show your comments anywhere.
> 0 votes

---
Tags: nodes, comments
---


# Question
Title: How do you replace text surrounded by a custom delimeter with <span> around it?
## Overview

I want to have action asterisks in my posts. Basically, asterisks surrounding certain words. Examples: \*gasp\* or \*giggle\*

Simple enough. Now I could type that exactly into the editor but it needs to be styled via CSS. This of course calls for span tags.

However, I don't want to have to surround the text with span tags every time. Too tedious. I'll be using this often.

So, **how can I make it so Drupal takes some text and replaces it with span tags surrounding it?**

## In Other Words...

I want to be able to write simple custom tags around text like:

```
[=gasp=]

```

and then have Drupal automatically convert it to:

```
<span class="action">*gasp*</span>

```

## A Possible Solution?

I've been led to the Custom Filter module and this seems closest to what I want. Now, it's already installed but in trying to add a 'rule', the module asks for the 'Pattern' to look for and the 'Replacement text'.

**The problem is I am terrible with regular expressions.**

Assuming this module is the right path, *can someone tell me what to put in these two forms so the filter works?* I have been holding this off for months because I was scared to ask for help.

If the Custom Filter module isn't what I need, what is the solution?

### On a sidenote

I don't know what's a good custom tag to use. I came up with \[=gasp=\] but maybe you can recommend something better? Just as long as its short. I already use Markdown and don't want it to conflict with it.

Either way, **thanks for any help in advance**.

# Answer
> 0 votes
You can use preg\_replace as the following in your custom module:

```
<?php

$string = '[=waves=] words <br/> words <br/> words [=jumps in air & rolls in ground=] <div>words</div>';
$pattern = '/\[=(.*?)\=]/i';
$replacement = '<span class="action">*$1*</span>';
print preg_replace($pattern, $replacement, $string);

```

which return:

```
<span class="action">*waves*</span> words <br/> words <br/> words <span class="action">*jumps in air & rolls in ground*</span> <div>words</div>

```

---
Tags: input-formats
---


title: Devel and XHProf configuration!

text:
# Question
Title: Devel and XHProf configuration!
I have installed Devel and XHprof to profile (kind of performance analysis) my website . Configured everything but i am confused with this setting

> **XHProf URL**: Path to the publically accessible xhprof\_html - required to display profiler reports. You will need to set this up outside Drupal, for example at http://xhprof.localhost/xhprof\_html

my drupal installation is in inside /www/ please help

# Answer
You need to set up a virtual host on your server and put the xhprof front-end HTML files on it (the ones that come with the the xhprof download). Give the host an address (e.g. http://xhprof.localhost/xhprof\_html as suggested), then give that path to Devel.

Then you should get the link at the bottom of each page to check the profiling information for that request.
> 3 votes

---
Tags: 6, performance, debugging
---


# Question
Title: How to add embedded YouTube video at the end of ViewSlideshow
I have a Slideshow view which loads two fields, **main images** ('group multiple values' unchecked to create rows) and **video** ('hide if empty' checked). It takes these from one node which it gets from the nid argument.

The slideshow currently displays 13 images but each image also has a seperate instance of the video attached to it.

I've tried playing about with the views-slideshow.tpl.php file and I've also tried excluding the video from display then manipulating the view ovject from withing hook\_views\_prerender() and hook\_preprocess\_views\_view(), all with no luck.

I just want the 13 unique images with the single instance of the video link added to the end, therefore creating 14 unique slides. Ideally I would want to add 2 or 3 videos so the solution needs to account for this.

# Answer
> 0 votes
* first tick exclude from display for video field
* then create view tpl (check view -\> edit \> theme information for suggestion and markup
* then manually include an `<li></li>` at just after loop
* -inside `<li></li>` , echo the video field name, mostly its something like this `$rows[0][VIDEOFIELDNAME]`

---
Tags: views, 6, javascript, nodes
---


# Question
Title: Login not redirecting to SSO (external) server login page
I'm trying to replace Drupal authentication with the authentication from a SSO server, in a scenario discussed here. I'm trying to modify the `login_block` (on "Homepage" as well as "Access Denied" page), and `login_block_form` (at `mysite.com/user/login`). I did reset the default "Log in" button and replaced it with "SSO Log in" button, and on its `#submit`, using `drupal_goto`, I'm trying to redirect it to SSO server Login page. But, I'm still getting redirected to `mysite.com/node?destination=node`. I'm not able to figure out what the problem is. And inputs would be appreciated.

```
function MODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // Add a button to form, used to login to SSO
        $form['foo'] = array(
            '#type' => 'button',
            '#value' => t('SSO Log in'),
            '#submit' => array('MODULE_user_login_foo_submit'),
            '#limit_validation_errors' => array(),
        );
        // unset the current default login button of Drupal
        unset ($form['actions']['submit']);
  }
}

function MODULE_user_login_foo_submit($form, &$form_state) {
  drupal_goto('PATH/TO/SSO-SERVER-LOGIN-PAGE.ASPX', array('external' => TRUE));
}

```

# Answer
> 2 votes
```
//implements hook_form_alter()
function MODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['#action'] = 'PATH/TO/SSO-SERVER-LOGIN-PAGE.ASPX';
  }
}

```

# Answer
> 4 votes
Unset the destination before calling drupal\_goto():

```
unset($_GET['destination']);
drupal_goto('PATH/TO/SSO-SERVER-LOGIN-PAGE.ASPX', array('external' => TRUE));

```

Another option would be to code the redirection logic yourself (brought up as an answer by Dave here).

The problem exists because drupal\_goto() is overriding the given path with the destination if the latter is not external (check the function code).

Additionally:

Since you are using the button type the submit handler isn't being invoked (documentation). For my solution to work you would have to change the type to 'submit' or move the redirection logic into the validation handler (by changing '#submit' to '#validate').

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


# Question
Title: Entity Reference + Views + Profile 2 | User Filtering
As the title is kinda vague (couldn't for the life of me think of something more creative) here is the case.

I have an Entity Reference field on one of my Content Types that's limited to Users.

The field searched through the users via a dedicated view.

I've installed Profile 2 and added first and last names to the users of my site.

I've added all the view's fields as search parameters in the views settings (username, first name, last name, email) but only the username and email (core drupal 'fields') seem to be able to be searched for whereas the first and last name are the ones I need mostly.

Am I missing something?

# Answer
I believe its because profiles are an entity unto themselves. So you are referencing users which means that if you want the profile fields to be searchable you will need to add a relationship in the view to User:Profile. Then use this relationship on the profile fields you want searchable.

Alternatively you could use entityreference to refer to the profiles directly from the content type.
> 1 votes

---
Tags: views, entities, users
---


# Question
Title: How to block a content type from the RSS feed
I simply want to remove one of my content types from being displayed in the feed, I can't find a solution anywhere - I would have thought there would be an option under Content Types which says "Don't put in feed" lol

# Answer
> 4 votes
> I would have thought there would be an option under Content Types which says "Don't put in feed"

Yes, it's as simple as that. Simply uncheck the *"Promoted to front page"* from the content type settings and that content type's nodes won't be included in the RSS feed. :-)

# Answer
> 2 votes
You can You can use the Views module to generate an RSS feed, rather than relying on the default feed that Drupal provides. This Tribute Media post will step you through the basics.

# Answer
> 2 votes
It seem's that in Drupal 7 we cannot hide some content types from the RSS feed.

What I suggest you to do is to use the Views module and then:

* Create a new view of type "Feed".
* In "Feed settings", set the "Path" to `/rss.xml` so it will overwrite the main feed.
* In `Filter criteria` add a filter criterion to "Content: Type" and set it to the content types that you want.

---
Tags: 7, feeds
---


title: Using "Profile" Data

text:
# Question
Title: Using "Profile" Data
I have used "Profiles 2" module, and created a form where users can input their profile data.

I have also defined a content type, say "Blog" for example, which has a title and a body. I have used "Views" module to generate the output.

The question is, I would like to display a line like : 'Posted By : '

Is there a way I can extract the data from Profiles?

# Answer
Yes, you use relationships under advanced to first expose the Content:Author. Then you use relationships again which will now show the User:Profile relation. Now you will have access to all the user details :)

It should look like this when you are done:
> 0 votes

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


# Question
Title: How to use the value element to pass values internally from $form to $form_state['value']
I have a form and i want to pass some values without user see them.

At the beginning i was using the default values:

```
$form['field_devis_lien_fiche']['und'][0]['value']["#default_value"] = t("@path",array("@path" => $path));

```

It was working fine but it's not the behavior i wanted because all the user could see the value.

So i buy "pro drupal 7 developpment" and at page 283, he describe the **element value** and i think this is what i have to use.

```
$form['title'] = array(
 "#type" => 'value',
 "#value" => $titre,
);
$form['field_devis_lien_fiche'] = array(
 "#type" => 'value',
 "#value" => $path,
);

```

The $form\['title'\] works fine but all my other fields trigger an error.

```
Warning: array_values() [function.array-values]: The argument should be an array in _field_filter_items() (line 517 of ***/modules/field/field.module).
Warning: Invalid argument supplied for foreach() in text_field_validate() (line 119 of ***/modules/field/modules/text/text.module).
Notice: Undefined index: #language in locale_field_node_form_submit() (line 405 of ***/modules/locale/locale.module).

```

When i want to edit my content type, my value doesn't exist.

So i tried another solution with the hidden element:

```
$form['title'] = array(
 "#type" => 'hidden',
 "#value" => $titre,
);
$form['field_devis_lien_fiche'] = array(
 "#type" => 'hidden',
 "#value" => $path,
);

```

In spit of the fact that my hidden fields are created when i inspect the form, i have the same error again (with array\_value problem)

i don't understand why it's works for the title field and why it's not working for my other field. And i don't understand too, why i have an error with the hidden field as they appears well when i inspect element with firefox.

Do i have to create a validation function because of my element value? Maybe i have forgotten a step...

Thanks for the help.

# Answer
The problem is that you'll need to set the type of the correct element to `value`, and that isn't what you've got at the moment. Notice how you use:

```
$form['field_devis_lien_fiche']['und'][0]['value']["#default_value"]

```

To access the field the first time round (which you've confirmed to be working). Logically then, if you want to change the same field to a `value` type, you need to do so on the same element:

```
$form['field_devis_lien_fiche']['und'][0]['value'] = array(
  "#type" => 'value',
  "#value" => $path,
);

```
> 1 votes

---
Tags: 7, forms
---


title: template.php check user and profile

text:
# Question
Title: template.php check user and profile
I created a custom tpl file for one of my content types and I would like to check the users profile as well if they were the publisher and if it all checked out then proceed to the tpl file.

Here is an example

```
if(publisher and profile){
   proceed to tpl file
}else{
   You are not authorized to view this page.
}

```

If someone can point me in the right direction that would be great, thanks.

# Answer
> 2 votes
This is not something that should be done in the theme layer. I would look at solutions like ACL or Content Access.

If you really need to code your own solution for some reason, create a custom module and use the necessary hooks, such as hook\_permission.

---
Tags: 7, theming
---


# Question
Title: Commerce: Hide "Save and Add Another" button when saving new product
I'm trying to hide the "Save and Add Another" button on the form used to save new products.

I can access the "Save" button in the $form array at `$form['actions']['submit']`. However, I'm not seeing the "Save and Continue" button in `$form`.

I looked in commerce\_product\_ui.module and found the place where this form element is being added. It's called `$form['actions']['save_continue']`. I would expect to see it in the `$form` array, but again - it just doesn't seem to be there.

Thanks for your help.

# Answer
implement hook\_form\_alter

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_product_ui_product_form') {
    unset($form['actions']['save_continue']);
  }
}

```
> 1 votes

# Answer
I finally realized why this element didn't exist in `$form` at the time.

The Commerce Kickstart module had a higher weight than the module than I wrote, hence it included elements in `$form` after my call to `hook_form_alter()`.

There are two distinct solutions to this:

1.) Increase the weight of my module (to make sure it's called after Commerce Kickstart.)

2.) Optionally, you can add an `#after_build` array to `$form`. This will let you add functions that are called after the form is built.
> 1 votes

---
Tags: 7, forms, commerce
---


title: Main Menu vs Navigation Menu

text:
# Question
Title: Main Menu vs Navigation Menu
Is there a commonly accepted "best practice" for how to use the "Main Menu" vs the "Navigation Menu"? The descriptions in Core add to my confusion:

"The Main menu is used on many sites to show the major sections of the site, often in a top navigation bar."

vs

"The Navigation menu contains links intended for site visitors. Links are added to the Navigation menu automatically by some modules."

I don't intend to start a debate. I'm curious if there's a best practice for how to use these, or is it entirely subjective?

# Answer
My personal opinion is that this is pretty subjective.

We typically just use the main menu for just top level section links (ie, all links are at the top-level and don't have children), and then will have a menu per site section. We will also typically have a sub menu for extra header links and extra footer links. Our theme will take care of displaying the proper menu on pages.

Keep in mind that we also do highly custom themes for large sites, so this scheme may not apply for your needs.
> 0 votes

---
Tags: routes
---


title: Display events on Calendar by time

text:
# Question
Title: Display events on Calendar by time
I am trying to display the events on a calendar, and have setup the calendar module with the date/ time. I am able to get the events to display on the calendar but they all are showing up as all day events. I have adjusted the formatting of the date/ time every way I can think of.

Adam

# Answer
Fixed. Had a configuration issues with Dates
> 0 votes

---
Tags: entities, datetime
---


# Question
Title: How do I add a class to a section in omega?
Here is the original source:

```
<section id="section-content" class="section section-content">

```

I want to add some class to it:

```
<section id="section-content" class="section section-content my-custom-class">

```

I've tried a hook\_page\_alter() but either I haven't been able to zero in on the specific element or I'm attaching the classes incorrectly.

# Answer
This is untested, but I am pretty sure you just need to put this in mytheme/preprocess/preprocess-section.inc:

```
function mytheme_alpha_preprocess_section (&$variables)
{
  $variables['attributes_array']['class'][] = 'my-custom-class';
}

```

If you look at section.tpl.php, just `$attributes` gets printed out. `alpha_process()` flattens `$variables['attributes_array']` into `$attributes`.

Though, given that the header, content, and footer sections are unique, you probably don't need to explicitly add a class. You can also add classes to the zone and zone wrappers inside each section directy with the UI at admin/appearance/settings/mytheme, or just replace "section" with "zone" in the code above.
> 2 votes

---
Tags: 7, theming
---


title: Auto assign roles

text:
# Question
Title: Auto assign roles
I want to auto assign a "default" role for everyone that registers for the site. Is there any way to do this by default in Drupal 7?

# Answer
> 9 votes
You can do this using Rules... just add the action "After saving a new user account" with the action "add user role." Rules gives you even more power if you want, to only add that role on certain conditions and more.

Also - I should mention - Drupal does auto-assign the "authenticated user" role to everyone who registers for the site - you can just make sure that the authenticated role has the permissions you want...

---
Tags: 7
---


# Question
Title: How to create popup for email link with major email provider links?
Check out this new feature craigslist implemented. WHen you click on this button (like in the link below) that says "reply to this post", it pops up with this popup that shows the different email providers options (for web browsers, and local clients like Outlook).

How can this be done for Drupal?

# Answer
> 1 votes
First take a look here. Lots of JQuery plugins that integrate with Drupal.

I think Lightbox best fit here but check the rest. It provides a pop-up overlay similar to Craigslist's

I myself don't have any experience with these but since no one has answered thought I could try point you somewhere useful.

I did a quick search and also found these that could lead somewhere:

```
http://www.lullabot.com/articles/announcing-beautytips-jquery-tooltip-plugin
http://www.jquerypopup.com/

```

Anyway, I hope those hints helps you in some way.

# Answer
> 0 votes
Please look in to this, it explains the same https://community.openatrium.com/documentation-en/node/2286

---
Tags: views, ajax, javascript
---


title: Limited promoted nodes with order

text:
# Question
Title: Limited promoted nodes with order
I was wondering what is the best way to promote nodes into a page (ie front page).

Drupal comes with its own "promote to front" option and we have other ways such as using Flags modules for this purpose as well, but I need two features that none of those cover.

One is that I only want for example 5 nodes be promoted at the same time, so if the client promote one more node, one of the previous nodes will automatically be removed from the list.

Also I'd like to be able to set the order (weight) of those promoted nodes too.

I have tried to use views and draggableviews for ordering the nodes which works great but can't figure out how to limit the number of promoted nodes?

Many thanks

# Answer
> 0 votes
In Views, you can set the number of values returned in the pager config by selecting 'Display a specified number of items'. Have you tried that set to 5?

If you said something like 'the top 5 in the draggable views list will be displayed' in the help/description that would do it for your users, plus they could then bring back stuff if they wanted without having to go out and reflag it. to automatically unflag content, you could hook into hook\_flag() and unflag the oldest or something with some custom php code.

Check out The Flag PHP API, which talks all about that kinda stuff.

# Answer
> 0 votes
Sounds like a perfect example for when you should use nodequeue.

With nodequeue, you maintain an ordered list of items in the queue, and items can be promoted at either the top of the bottom of the queue. There is also an administration page for every queue in which administrators can re-order the items in the queue at any time. There also is excellent views integration.

You may choose to have the queue with the size of 10 for example, and using views only display the top 5. This gives your content authors the ability to re-order items they want to show on the homepage, including ones that recently fell off.

The flag module has no concept of 'weight' and would only make sense to use if the order can be determined programmatically (e.g. by most recent first).

---
Tags: nodes
---


# Question
Title: Why DrupalWebTestCase processing took so long?
I want to create a test that uses the database, so I must use the `DrupaWebTestCase` class.

I create the following test class with this simple test:

```
class MyModuleTest extends DrupalWebTestCase {
  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array (
      // Info stuff
    );
  }

  public function setUp() {
    parent::setUp('my_module');
  }

  public function testHelloWorld() {
    $this->assertEqual(t('Hello World'), 'Hello World');
  }
}

```

And this **SINGLE** test is taking around 1 minute every time. Why is that long?

I know Drupal must bootstrap, but it's annoying.

What I am doing wrong here?

I am launching the test from admin/config/development/testing.

I tried it on a fresh Drupal 7 installation: It took the same time.

# Answer
1 minute is not the time took from Drupal from executing `MyModuleTest::testHelloWorld()`; it's the time took to create the test environment, execute the tests, and delete the test environment, including the database tables, and the files created during the test.

When DrupalWebTestCase::setUp() is executed, a temporary Drupal installation is created right for the time to execute the test; after the test is terminated, the Drupal installation is deleted. This means, for example that at least the Node, User, and the System modules create (and then delete) their own database tables; the list of installed modules contains all the Drupal core modules that are necessary to run Drupal, and all the modules the test declares as dependency.

The only ways to speed up the execution would be:

* Use a different database engine for the tests. This would be possible by calling db\_set\_active() in `MyModuleTest::setUp()`, before calling `parent::setUp()`. It requires the settings.php file contains the definition for the connection to use during the tests.
* Instead of creating the single database tables, they are created from a backup file. This would require to hack the way the test environment is created. By default, any required module is asked to create its own database table; `MyModuleTest::setUp()` should handle the initialisation of the test environment without calling `parent::setUp()`.
The bigger issue with this approach is that the backup needs to contain the database tables updated for the latest versions of the modules; this is probably easier to do for Drupal core modules. The tests are speeded-up when they are executed frequently enough; if the test are executed rarely, then there isn't any performance improvement.

You can look at the Project Issue File Review module (a.k.a PIFR), which is the module running the server used to test Drupal core patches, and the patches submitted for Drupal.org projects with enabled tests.
> 2 votes

# Answer
I will preface this answer with the fact I'm still very new to automated testing.

DrupalWebTestCase could surely run faster, though I doubt you'll ever match the speed of PHPUnit. The only way I can think to reduce the overall time spent testing your code would be to use functional/implementation tests (DrupalWebTestCase) as infrequently as possible.

Enter DrupalUnitTestCase.

One trick I use is to seperate out DB interaction in my modules as much as possible so I can use serialized input for quick unit testing. Of course this doesn't always make sense, nor will it work under every circumstance but it can help speedup the time your tests take to run so you can test early and test often.

Consider the following non-working and untested code:

**Before**

```
//Cannot test with DrupalUnitTestCase due to DB interaction.
function module_my_custom_function($uid) {
  $result = db_query('SELECT n.nid, n.title, n.created
  FROM {node} n
  WHERE n.uid = :uid', array (':uid' => $uid));

  //Do stuff to $result here...

  return $whatever;
}

```

**After**

```
//Cannot test with DrupalUnitTestCase due to DB interaction.
function module_my_custom_function_query($uid) {
  return db_query('SELECT n.nid, n.title, n.created
  FROM {node} n
  WHERE n.uid = :uid', array (':uid' => $uid));
}

//Can test with DrupalUnitTestCase using serialized 'known to be good' input.
function module_my_custom_function($db_result) {

  //Do stuff to $db_result here...

  return $whatever;
}

```

Now I can snag known good values from `module_my_custom_function_query()` and manually insert it into my tests setUp() method using PHP's serialize() function.

```
$insert_in_unit_test_setup = serialize(module_my_custom_function_query(1));

```

I know many of you cringed at what I just did, but this has saved me tons of time during testing.

```
class MyModuleTest extends DrupalUnitTestCase {

  public static function getInfo() {
    return array (
      // Info stuff
    );
  }

  public function setUp() {
    //Unserialize your manually saved results here to avoid DB queries for quick testing.
    $this->saved_db_results = unserialize('a:3:{i:1;s:3:"One";i:2;s:3:"Two";i:3;s:5:"Three";}');
    parent::setUp('my_module');
  }

  public function testMyFunction() {
    $db_results = $this->saved_db_results;
    $result = module_my_custom_function($db_results);
    $expected = 'Whatever';
    $message = 'A message about the test...';
    $this->assertIdentical($result, $expected, $message);
  }
}

```

You can't completely avoid Functional tests, but you can at least reduce the number of times you have to run them during active development saving you time in the long run.

Some additional information on Drupals implementation of the Simpletest framework.
> 2 votes

---
Tags: 7, testing
---


title: can't access www.livesite.com/admin

text:
# Question
Title: can't access www.livesite.com/admin
I have just transferred my local server to a live site. I am able to log in as an administrator, but I am not able to access my administrator tools. The page directs me to a blank page. Initially I was able to change the site's theme, through the admin tools, but now I can't even do that. I am not sure what am I doing wrong, or if there is something that I have to change in the settings.php file etc?

Btw, the site update was using ftp only.

# Answer
A blank page often indicates a PHP Error. Is there an error in the PHP error logs you can reference?

Also, when uploading via FTP, you want to be sure that you properly transferred your .htaccess file which, on some Operating Systems, will be hidden on your local filesystem.
> 2 votes

# Answer
I think you are getting a memory\_limit error for admin pages. Usual admin pages will take more memory. Please check the error log and increase the memory\_limit.
> 1 votes

# Answer
Look in settings.php and change domains path, from your local to live domain.
> 0 votes

---
Tags: files
---


title: Error while registering

text:
# Question
Title: Error while registering
When I register as a new user I get an error.

`An illegal choice has been detected. Please contact the site administrator.`

If I reenter my password fields, and press create new account then it lets me register. Ideas?

# Answer
> 1 votes
An illegal choice typically means that the Form API received something it didn't expect when the form was processed. As Stan Ascher says, make sure you don't have modules enabled which modify the login process. You can tell if there are functions which end in \_user or \_form\_alter in those modules.

# Answer
> 0 votes
Have you done any customizations in registration page. Or you are using a default drupal registration form.

---
Tags: 7, users
---


title: Nested taxonomies in views

text:
# Question
Title: Nested taxonomies in views
I'm creating a site which has products, brands and affiliates. Products and brands are in the same taxonomy while affiliates are separate.

Products are terms that are children to brands. Affiliates are referenced in the brand term. I have the basic structure below for reference.

I'm trying to create a view that shows a users 10 favorite products along with the brand and url's for affiliates that carry the product. I've made my relationships in the view, but instead of displaying each brand with a link to the affiliates it duplicates the brand once per affiliate. In other words, if the brand has 3 affiliates it would show the brand 3 times with a single affiliate link under each.

How can I make my view combine the affiliates into a single result?

```
Product/brand taxonomy
-name
-affiliate(term reference to affiliates)

Affiliates taxonomy
-name
-logo
-url

```

# Answer
For a quick fix you can make 'Distinct' in the view setting setting.
> 0 votes

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


title: Imagefield_crop field in custom form?

text:
# Question
Title: Imagefield_crop field in custom form?
How can I add through the form API an image upload field with the cropping functionality implemented by this module?

http://drupal.org/project/imagefield\_crop/

I'm using Drupal 7. I need to implement an image upload field with cropping functionality. If there's another module that does the same job as Image Crop and plays more nicely with the form API, that's fine.

# Answer
> 0 votes
I ended up getting this working by using a module called Form Block and just putting the block containing the node form in the content. For some reason I never figured out, just calling drupal\_get\_form on that node form just did not work, even with the right node module files included. So, hopefully someone else struggling with this will be able to learn from this question

---
Tags: forms, media
---


# Question
Title: Arguments of hook_file_download_access_alter()
```
function hook_file_download_access_alter(&$grants, $field, $entity_type, $entity) {
  // For our example module, we always enforce the rules set by node module.
  if (isset($grants['node'])) {
    $grants = array('node' => $grants['node']);
  }
}

```

The arguments `$field`, `$entity_type`, `$entity` are not used in the implementation. What are these arguments used for, when the function is called?

# Answer
> 3 votes
You do not need to use `$field`, `$entity_type` and `$entity` in your implementation of hook\_file\_download\_access\_alter(), if you do not want to.

You should use theses arguments if you need to handle files differently depending on which field of which entity they belong to.

For example, node\_file\_download\_access() restricts access on files to people that can view the node. If you want to remove this restriction for nodes of a specific type `foo`, you would have to check whether `$entity_type == 'node'`and whether `$entity->type == 'foo'` and grant access if this is the case.

---
Tags: hooks
---


# Question
Title: Get term weight in node object for ordering with EntityFieldQuery
Is it posiible to expose taxonomy term weight in node object ?

I need to sort nodes using EntityFieldQuery by term reference field, but weight is not exposed to node object so i can say for example

```
->fieldOrderBy('field_custom_terms', 'weight', 'ASC');

```

and sort nodes by weight of terms.

# Answer
No, this is not possible. You can only order on actual field values, the term weight would require a JOIN to a non-field table and EFQ is not capable of doing that.

You will have to create a manual SQL query to do this. Note that Drupal by default maintains the node \<-\> term associations in the taxonomy\_index table, that one is easier and more reliable to query than a field data table.
> 5 votes

---
Tags: taxonomy-terms, database
---


title: How does page.tpl.php come into action?

text:
# Question
Title: How does page.tpl.php come into action?
When the line `<?php print $page; ?>` is encountered in the html.tpl.php template, what happens that make the page template (page.tpl.php) come into action?

# Answer
> 2 votes
It's actually the other way around; it's the theming of the page template that invokes the theming of the html template (as strange as that might sound).

When Drupal goes to serve a normal HTML page (through `drupal_deliver_html_page()`), it calls `drupal_render_page()`. To get the basic render array for the page, that function invokes `hook_element_info()` with the 'page' argument.

The `system_element_info()` function defines that type like this:

```
$types['page'] = array(
  '#show_messages' => TRUE,
  '#theme' => 'page',
  '#theme_wrappers' => array('html'),
);

```

When the `drupal_render_page()` function eventually gets around to calling `drupal_render()` on the `$page` array (once it's been populated with the page content/blocks/etc), `theme_page()` is called with the `$page` element as it's 'render element', and the return from that call is passed to the theme wrapper (`theme_html()`).

It's that return value that populates the `$page` variable in html.tpl.php

---
Tags: theming
---


# Question
Title: What's meaning of %contact in this menu path?
```
$items['admin/structure/contact/edit/%contact'] = array(
    'title' => 'Edit contact category',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('contact_category_edit_form', 4),
    'access arguments' => array('administer contact forms'),
    'file' => 'contact.admin.inc',
);

```

How does it get the path `admin/structure/contact/edit/%contact` and what does it mean by `%contact`?

# Answer
All requests on admin/structure/contact/edit/\[anything\] will be handled by a Drupal form callback, `contact_category_edit_form()` in contact.admin.in\` which returns a form array.

%contact means this parameter will be passed to `contact_load()` and the result will be pass to `contact_category_edit_form()` as first argument.

See hook\_menu().

> Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule\_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule\_abc' part defines the prefix for a load function, which here would be named `mymodule_abc_load()`.
> 2 votes

---
Tags: emails
---