# Question
Title: How can I sort the order of status messages?
I add my own validations to forms, for example the user registration. The errors I set with form\_set\_error are added below the drupal generated errors. I would like to show them in the same order of my form fields on the page.

I thought I can use theme\_status\_messages($variables). When I do a dpm($variables) on a from with status messages it just shows an empty array.

# Answer
> 1 votes
`$variables['display']`, passed to the theme function is optional, and its purpose is only to limit the type of messages being shown; for example, if its value is "error," only the error messages should be shown. The list of messages is returned from drupal\_get\_messages(), which should be called as `drupal_get_messages($variables['display'])`.

To answer to your comment, you can avoid duplicating all the code used by `theme_status_messages()` if you follow these steps:

* obtain the array of messages from `drupal_get_messages()`
* sort the obtained array of messages
* use the array to set the content of `$_SESSION['messages']`, which is the session variable used to contain all the messages set from the modules
* call `theme_status_messages()`, passing the same argument passed to your theme function (not the array obtained from `drupal_get_messages()`)

This method seems half of a hack, to me. What happens if Drupal would change how the list of messages are saved? It could be that future Drupal versions will not use a session variable for this purpose.
It also take the assumption that other modules didn't override the theme function, but it would be easy in the implementation of `hook_theme_registry_alter()` to save the previously defined theme function, and call that function instead of assuming that function is `theme_status_messages()`.

---
Tags: 7, users
---


# Question
Title: Set the id property of a form element using D6 Form API?
I want to set the `id` property of an input element of a form that I'm creating in a module using the form API. I'm doing this I looked up the documentation and it says this:

> # id
>
> INTERNAL. Used to populate form elements' id property. In rare cases, you can set this value yourself on a form element, to override the default setting.

It doesn't really say when I can or can't use it, so I'm hesitant to try to do this, since I can't rely on it.

I'm writing some javascript that has the id of the element hard-coded into it. Should I use the Drupal-generated id in my script instead?

# Answer
> 1 votes
I would avoid changing that at all and use the Drupal-generated IDs in your Javascript. I have never been forced to do otherwise.

Keep in mind, however, that you'll have better luck if you use classes or if you prefer IDs that don't have a node ID or other sequence-based ID in them. For example, I try to avoid using IDs when theming webforms because if I create the webform on another site, the ID will change.

If there are existing styles for what you want to do, I would check which selectors they are using as well.

Remember that you can add your own classes with the theming layer and then you can use them for your Javascript or jQuery. Sometimes this is the best choice, and I've done it numerous times.

If worst comes to worst, implement `hook_form_alter` and change the #id in question. If your form continues working, then you're good.

---
Tags: forms
---


# Question
Title: Limit the reviews on "Product" content type
I want to limit the users' review of my "Product" content type to only one, and I tried to implement a code from this link in Drupal 7 as a simple module named "review\_limit." I saw this module in my module list and installed it without an error.

This is my code:

```
function review_limit_form_alter($form_id, &$form) {
    // If the form is a "product_review" node form
    if ($form_id == 'product_review_node_form') {
        // Add an extra validation function //
        $form['#validate'][] = 'review_limit_user_node_limit';
    }
}

// Validation function
function review_limit_user_node_limit($node) {
    // Get our logged in user's details
    global $user;
    $result = db_query("SELECT n.uid, n.nid
    FROM {field_data_field_product_review_pr}
    Inner Join {node} n ON field_data_field_product_review_pr.entity_id = :nid
    Inner Join {users} ON n.uid = :uid", array(':nid' => $node->nid,':uid' => $user->uid))->fetchfield();
    //if founded referenced field from the logged user, drupal show error message
    if ($result) {
        // Throw error
        //drupal_set_message('You have already submitted a review of this item.', 'error');
        form_error($element['title'], t('You have already submitted a review of this item.'));
        die;
    }
}

```

and i have prepare a template named product--review.tpl.php, page--node--add--product\_review.tpl.php and call it from my template.php using

```
function bartik_theme() {
  return array(
    'product-review_node_form' => array(
      'arguments' => array(
          'form' => NULL,
      ),
      'template' => 'product_review-node-form',
      'render element' => 'form',
    ),
  );
}

```

This module does not work, every user is still can to create a product review node as much as they want. Did I miss anything? Can anyone help me to solve this problem?

# Answer
The error is that you use `die`; the hook should simply return to the calling function. If you use `die`, you are avoiding that the code calling the validation handler is called back, which means the code that checks if there are any validation errors, and shows them to the users is never executed.

If you look at the code used by a Drupal validation handler, such as user\_pass\_validate(), you will notice it doesn't use `die`, which is never used from any form validation handler.

```
function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  // Try to load by email.
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  $account = reset($users);
  if (!$account) {
    // No success, try to load by name.
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
    $account = reset($users);
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}

```
> 1 votes

---
Tags: 7, nodes, forms
---


# Question
Title: 30+ small modules versus 5 large modules versus 1 HUGE module: Which is better?
So, we have a large, complex Drupal 6 site, which has lots of secret sauce and magic glue making it work.

Where we can, we've contributed modules back and made them generic, but we still have 30 or so custom modules to keep it working the way we need it to. Each module (in most cases) has a specific function e.g. our hook alters for the notification system.

We are doing a huge code review at the moment and looking at improvements we can make. One thing suggested is to merge the large number of modules into a few smaller master modules, with lots of include files. We would, perhaps group by general site area e.g. "community", "admin" and "messaging", instead of specific modules per functionality.

1. Is the effort in doing this worth it? Will it speed up the site?
2. What module grouping would you recommend?
    * by site area ("community", "admin", "upload")
    * by hook ("form", "node", "user", "theme")
    * everything in one module
    * something else?
3. What naming conventions should we use for the include files to keep the codebase sane?
4. Am i right in assuming the goal should be tiny .module file with includes per hook / menu / area?

# Answer
It sounds like you don't really know what your bottleneck is. This restructuring will likely have very little impact on performance (unless you happen to find and trim some major bloat in the process), but it may make things easier for you to maintain. If you do decide to restructure I would recommend splitting up along "site features" (blog, image galleries, etc.).

But if performance is your concern you first have to diagnose the problem before you attempt surgery.
> 5 votes

# Answer
Modules should do one thing, and one thing well. The "thing" should be a piece of functionality on the site. That module should include all of the hooks to do that one thing. As much as possible, disabling a module should have limited side effects on the site, and should be limited to just disabling the "thing".

Ask yourself:

Can I have multiple hands in the project with how I am splitting / combining modules?

If I need to change the module a year from now, am I going to have an easy time honing in on where things are implemented?

If I need to edit some code, am I going to have to be worried about mucking up another feature (think shared hooks like form\_alter, block\_view, etc)?

I always choose ease of maintainability over minute performance impacts on a site.
> 2 votes

# Answer
You'll need to carry out performance testing to answer the question of if it will speed up the site. Search for Mark Sonnabaum's recent XHProf presentation, as this is a painless way to do so.

Another approach beyond the ones suggested that you could take is seeing if you can now re-implement any of your custom code using contributed modules. Rules, Views, and other contributed modules have probably come a ways since you first wrote your code, so this could be another way to simplify, although you will likely end up exporting those configurations again with Features anyway :) - still, at least it'll be a bit less code/configuration for you to maintain in the end if that's one of your goals.
> 1 votes

# Answer
Using the Drupal core code as example, each module should implement independent functionalities. For example, in Drupal, the module for handling the taxonomy term is the Taxonomy module; it is not the Node module that include that functionality in its code.

The question is then, when do you split a module in two, and when do you keep the code in the same module?

* If the code that should go in the new module is just few lines, then the code should be kept in the old module.
* If in the old module you keep writing in different hooks is similar to `if ($option_enabled) { /**/ }`, then the code should be written in a new module; in this way, instead of having a module that tests if the functionality has been enabled, the administrator users enable the new module if they want the functionality.

Keep in mind that, when you split code in two modules, the main module should not depend from the secondary module, but vice versa. This means the main module should not verify the secondary module is enabled before to execute some code; if this happens, you should consider re-write the code to use a hook that is then implemented from the secondary module.

Between the following snippets, the second is preferable.

```
if (module_exists('secondary_module')) {
  // Code that requires the secondary module.
}

```

```
// Invokes the hook that is implemented by the secondary module.
module_invoke_all('hook_name');

```
> 1 votes

---
Tags: 6, performance
---


title: drupal_write_record() cuts off data

text:
# Question
Title: drupal_write_record() cuts off data
I have some pretty straightforward code that combines some string values together and then writes them to the db using drupal\_write\_record(), and it seems that the values are getting cut off for some reason when actually written to the database.

```
$keys_string = str_replace('|', '', $product->attribute_keys);
$values_string = str_replace('|', '', $product->attribute_values);

$keys = array_filter(explode('~', $keys_string));
$values = array_filter(explode('~', $values_string));

$description = '';
foreach ($keys as $key => $data) {
    $description .= $keys[$key] . ' : ' . $values[$key] . "\n";
}

$description .= "\n" . $product->group_text;
....

// Write record to database.
$table = 'ridethis_combined';
$record = new stdClass();
$record->title = $title;
$record->description = $description;
$record->short_description = $product->group_text;
$record->upc = $product->upc;
$record->sku = $product->vendor_item_id;
$record->cost = $price;
$record->price = $price;
$record->bti_quantity = $product->available;
$record->hawley_quantity = NULL;
$record->weight = NULL;
$record->manufacturer = $product->manufacturer_name;
$record->image = $image_url;
$record->meta_description = $product->group_text;
$record->meta_keyword = $product->group_text;
$record->meta_title = $title;

drupal_write_record($table, $record);

```

When stepping through the code in a debugger, I can see that prior to drupal\_write\_record, the full concatenated value is is stored in $record-\>description. However, when I view the data in MySQL, only the concatenated values from $product-\>attribute\_keys and $product-\>attribute\_values is there; it's as if the $product-\>group\_text data was never there. The size of the db field is not an issue, since it has plenty of space for the content I'm writing to it.

Do you have any thought on what could be cutting this text off?

# Answer
> 2 votes
The function `drupal_write_record()` uses the database schema defined from the module. Check your `hook_schema()`, and see if it has the right length.

Post your `hook_schema()` implementation too, if this doesn't help.

---
Tags: database
---


title: What is rewriting my user related URLs?

text:
# Question
Title: What is rewriting my user related URLs?
My main username is 'bw\_admin'. If I visit my login page at `localhost:8888/mysite/?q=user` I would be able to login but after my login I can't view the account page. Instead I get a HTTP500 internal server error. What I notice it that the underscore of my username is being deleted automatically so I would be getting `localhost:8888/mysite/?q=user/bwadmin` instead of `localhost:8888/mysite/?q=user/bw_admin`.

after getting the error if I would just edit the bad URL into the URL of the mainpage of the site I can go on while logged in as admin. But it's important for future user to not have this problem so they won't panic

Here's a list of the modules that I've installed in case this might be a typical problem related to a certain module.

addthis
addtoany
admin\_menu
advanced\_help
auto\_nodetitle
autoload
cck
content\_profile
context
ctools
devel
devel\_themer
fckeditor
filefield
google\_analytics
image
imageapi
imagecache
imagefield
imce
imce\_wysiwyg
insert
jquery\_ui
jquery\_ui\_dialog
jquery\_update
lightbox2
menu\_breadcrumb
module\_filter
nice\_menus
oauth
panels
pathauto
token
twitter
views
webform
wysiwyg
wysiwyg\_imageupload

# Answer
The module that creates a URL like localhost:8888/mysite/?q=user/bwadmin (or localhost:8888/mysite/user/bwadmin, with clean URLs enabled) is the Pathauto module, which creates path alias for user, node, and taxonomy term URLs.

Check the module settings; there is a set of options that allows replacing some specific characters that would cause some problems; one of those characters is the underscore. In your case, the module is set to strip off underscores from the path alias it generates.
> 1 votes

---
Tags: 6, uri, users
---


# Question
Title: Force new articles to have tags (term + subterm) associated with it
previous question

I have a site where articles need to be classified as, apple, banana, cranberry, etc....

Each category has sub-cats like apple - 1, apple - 2, ... banana - 1, banana - 2 ...

Now apples can have 10 subs and banana can have 200 or something like that.

I already make a vocabulary using taxonomy of all the terms and subterms.

What I need to do is have it so that users submit articles and it must have a category and sub-cat associated with it.

I want to do it this way so that I can have an index page of all apple articles, or just apple - 1, or banana - 2's ... etc.

# Answer
Re: Correct Tags comment: I am not certain I understand what your concern is. :)

Two possible considerations: 1. You can make the selection of the field mandatory when the content is submitted. 2. You can expose the field in the view display to allow the user to make a selection
> 0 votes

# Answer
What you are seeking to do is very basic and one of the early things you learn how to do in Drupal. The simplest way to answer your question is to recommend you get a book such as Drupal 7 by Tom Geller or any of the other introductory Drupal books. Lynda.com also has a video series that can fill you in on how to use Drupal. You can accomplish want you seek by modifying or creating a content type and adding field s linked to taxonomy terms. You can make it a requirement to add a value for each new entry. Eventually you will want to master the Views module to find your content and display it.

Before you start working on the design of a site, yuo may want to spend some time studing Drupal basics. Drupal has a steep learning curve in the beginning and you will have to cover a lot of ground before it starts clicking and you will feel confident diving into a project.
> 0 votes

# Answer
RE: No checkboxes The views module can filter your content based upon the URl using contextual filters to sort through the hierarchy and control what is displayed at each level. Views can take the input from the URL (or panel module arguments) to determine what to display.

Path auto module would create the proper path aliases for each content entry.

I am currently working on a similar navigation problem and attempting to access the content through a menu generated using Taxonomy Menu that has arranged all the terms in a hierarchical menu. (There is a bug in the design I have not yet solved, so I cannot guarantee it works from personal experience...yet.)
> 0 votes

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


title: Drop down menu question

text:
# Question
Title: Drop down menu question
I found a tutorial for a nice menu for my site.

Everything went well till step 7; when I enter this in Views3 on Drupal 7, I get this error message:

> Display "Block" uses fields but there are none defined for it or all are excluded.

How can I solve this?

# Answer
> 1 votes
Have a look at your "content post date", it seems to be excluded (click at it, uncheck the option "exclude from display") therefore no field is displayed hence the error.

# Answer
> 0 votes
This is because you have selected *Fields* for show format. You have to change show format to *Content* or add some fields under *Fields* section.

---
Tags: 7, views
---


title: Page template suggestion per language?

text:
# Question
Title: Page template suggestion per language?
How can I add page templates for different Languages in my Drupal 6?

For example, if I want to make different page template for Bulgarian language, **page-bg.tpl.php** doesn't work.

# Answer
A drupal.org groups comment shows examples how to allow use of multiple tpl.php file versions.

Using

```
<?php $vars['template_file'] ?>

```

it is possible to create your own template file suggestions.

Example:

```
function phptemplate_preprocess_page(&$vars, $hook) {

  if($vars['language']->language == 'bg') {
    $vars['template_file'] = 'page-bg';
  }
}

```
> 4 votes

---
Tags: theming, i18n-l10n
---


# Question
Title: What options are there to allow users who have not logged in to see content on the home page?
I have a site where users must log in to access content. For the home page, I'd like these anonymous users to be able to view this content and the login box. Below are the ways I have done this in the past, but I'm looking for comments on how others may do this. Especially for ways that it could be done without touching templates or code.

* Modify page-front.tpl.php when a user is not logged in. This allows me to remove the "Access denied message"
* Create a block that is displayed on the home page for anonymous users. However, this still displays the "Access denied message"
* Implement Taxonomy access and have a term that allows anonymous access. This would eliminate the "Access denied message"

Are there other better methods to do this with as little code as possible? What is the best way?

Thanks.

# Answer
What kind of permission module are you using ? Is it possible you implement yourself these permission ?

I would restrict node access to anonymous user using a custom module implementing `hook_node_access()` and allow them to see the nodes on the front page (using the function `drupal_is_front_page()`):

```
function MYMODULE_node_access($node, $op, $account) {
  if ($op == 'view' && $account->uid == 0) {
    if (drupal_is_front_page()) {
      return NODE_ACCESS_ALLOW;
    } else {
      return NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}

```
> 0 votes

# Answer
You could use frontpage to set different front pages for anonymous, and authenticated visitors.
> 0 votes

---
Tags: users
---


title: Best option to extend user profile

text:
# Question
Title: Best option to extend user profile
If I want to add a new tab in the user profile page, let's say /user/%user/resume, should I create a new node type and render it in this tab, or should I declare a table describing a résumé per user, develop add/edit/delete forms and render them in this tab ?

For now, I implemented the second options and I am wondering if it would be easier to do it with the Field API by mapping my SQL table to an entity so that I don't need to create all those add/edit/delete forms. So I have a page callback for /user/%user/resume selecting everything necessary in the resume table and rendering the selected informations with a template.

The sub-question would be : should I always map my SQL tables to entities to benefit the Field API functionalities ?

Thank you,

# Answer
with Drupal you should never have to deal directly with tables and add/edit/delete forms again - Drupal does it all for you. In your case you could either extend the user profile and add a "resume" field or you could add a "resume" content type and use the reference module to reference it to the user.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to attach a css style with a node in the node-edit form
I don't want to save the style in a file. What I want is to store the css code in a field while editing node and use the id or class within the node content.

# Answer
take a look at css\_injector, it allows to add css only on specific pages, like 'node/add'.
> 0 votes

---
Tags: 6, nodes, theming
---


# Question
Title: Most effective way to create a landing page for content types?
I have a "facility" content type which I am creating programmatically, through a module called "facility". I would like to have a landing page, such that when you go to http://www.mysite.com/facilities, you are taken to a heavily styled/scripted page that displays facility information in a specific format. To do this, in my facility module, I implemented hook\_menu to point to a callback that will return the necessary markup. Here's my code:

facility.module

```
<?php

function facility_menu() {
    $items['facilities'] = array(
        'title' => 'Facilities',
        'page callback' => 'facility_landing',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK
    );

    return $items;
}

function facility_landing() {
    return file_get_contents(drupal_get_path('module', 'facility') . "/facility_landing.php");
}

```

Due to the length and complexity of the markup, I would like to have it in a separate file. The issue is that this markup is not being evaluated in the Drupal context, since it is being read in with PHP's file\_get\_contents function. For instance, if my markup contained...

```
<h1><?php echo $user->uid; ?></h1>

```

...nothing would be displayed. Is there a function within Drupal that will parse a PHP file in the bootstrapped environment, and return the generated string? If not, what is the best/easiest way to handle this situation?

EDIT: This just occurred to me - I've already created an API within Drupal that would allow me to access the facility info I need via AJAX. I could just output the page without the facility data, then include a JS file which would get that. I'm still not convinced that's the best way, though. Thoughts?

# Answer
If you want your code to live outside your module's .module file, hook\_menu has a way to tell Drupal where to look for your page callback. A common name for include files containing page callbacks is MODULENAME.pages.inc. Place this file in the same folder as your .module file. Just add one line to your menu item definition:

```
function facility_menu() {
  $items['facilities'] = array(
    'title' => 'Facilities',
    'page callback' => 'facility_landing',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'facility.pages.inc',
  );
  return $items;
}

```

Now Drupal will load the facility.pages.inc file when example.com/facilities is requested. In facility.pages.inc you place the facility\_landing() function. Inside facility\_landing() you call other functions to generate the page and finally you return the markup (Drupal 6) or render array (Drupal 7) for your landing page.
> 3 votes

---
Tags: routes, hooks
---


# Question
Title: What is the most performant method to run many UPDATE statements?
What is the most performant method and best practices method to run many UPDATE statements efficiently? Currently I'm just creating a text block of many UPDATE statements separated with semicolons and passing that into a single db\_query() call.

Using this method I'm currently getting this error, so I'm guessing it's not a smart way:

> PDOException: SQLSTATE\[HY000\]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL\_ATTR\_USE\_BUFFERED\_QUERY attribute.:

Is there a better way that is as fast? I will need to run possibly hundreds of UPDATE statements.

Why must I do so many queries? For every node, I track three metrics of that node. These metrics are determined form other sources programmatically (like traffic data). For speed, I created a table that just tracks the nid, and the values of the three metrics. On a regular basis, I have to update the metrics for every node in this table. Every node in the system will have a row in this table.

I determine a forth metric from the values of the three, so each day I have to:

* Update the values of metrics 1-3
* Update metric 4 based on values of metrics 1-3

# Answer
UPDATE statements alter data and are therefore by definition not fast. They might be relatively fast if you a small data set but the bigger you table gets, the slower an UPDATE will become, especially if it involves updating indexes and stuff.

So I doubt it would matter much if you execute them separately or in a single call. Instead, I would look into ways to "optimize" them in a more general way:

* Maybe you can rewrite it so that you need to execute less queries, e.g. use a subquery to get the value. Make sure to actually profile it to be sure that it is faster. A complex query could also be slower than a number of simple ones.
* Use `db_transaction()` to execute all queries in a single transaction. Not only will this enforce consistency (all or nothing, if you have an error in the 500. query the others changes will be reverted as well) it will also be considerably faster on many systems because (in the default configuration) MYSQL enforces a write to the file system after each transaction (and if you don't use transactions explicitly, every UPDATE/INSERT/DELETE query is considered a separate transaction).
* Maybe your table structure can be optimized so that you need less queries.
* If there is no way around executing hundreds of UPDATE queries, I would go for reliable instead of performant/fast. Have a look at how node access table rebuilds are done for example ( which can result in hundreds of thousands of INSERTS if you have many nodes). When one is necessary (e.g. a node access module is installed), it usually just sets a flag to inform the admin and then the actual rebuild is executed in the backend with a batch.

If you provide more details on what you are actually trying to do, I might be able to give you some actual advice as well.

EDIT:

Some more hints now that you posted what you are doing exactly.

* If you don't need to keep old data, you could try if you can first calculate the metrics for a number of nodes, then delete them and then do a multi-insert. Maybe that's faster, maybe not.
* Generally, I would implement what you're doing in a hook\_cron(). You could process N nodes per cron run, store the highest node id and on the next run, process the next N. If a query returns less than the requested N, you reached the end of your data set and are done for the day, set a flag to today and can start by zero at the next day. If you need to process all nodes at the same time, I'd create a simple drush script that you can start through system cron, but still group the processing into groups of nodes, to avoid memory issues.
* You could look into using a different backend for storing your metrics if you're on your own server and can install something. For example, there is http://oss.oetiker.ch/rrdtool/, which is specifically built for storing "time series data" (quote from the website). I have never used it though. And if you're in for big, then there are systems like Hadoop which is among others used by Facebook to process their *enormous* amount of daily metrics.
> 4 votes

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


# Question
Title: How to change Contact Form sendto from admin dynamically
In D7 I have a hook\_form\_alter to make changes to the Contact Form (Core). How can I change the sendto address from the admin to another email addres that is determined when the user requests the form?

# Answer
The core contact form is pretty limited in functionality. If you need more features, I recommend building your own form using the Webform module.
> 2 votes

---
Tags: emails
---


# Question
Title: Cannot call function leftJoin on a SelectQuery object?
```
$query = db_select('drupal5users', 'udf');
$query->leftJoin('drupal5users_roles', 'ur');
$query->fields('udf', array('uid','name','pass','mail','created','access','login','status','language','init'));
$query->fields('ur', array('rid'));

```

The above gives me the following error:

PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') subquery' at line 1.

If I comment out $query-\>leftJoin and the second $query-\>fields line, it works, so the problem lies with leftJoin. What am I doing wrong here?

# Answer
```
$query->leftJoin('drupal5users_roles', 'ur', 'udf.uid = ur.uid');

```
> 4 votes

---
Tags: 7, database, migrations
---


# Question
Title: Drupal mobile theme doesn't display image
I am working on a mobile version of a drupal website and I am using mobile tools to switch theme between desktop version and mobile version based on url. I am using fusion mobile theme on the mobile side. Now the matter is that no images are displayed in views in the mobile version. There is some kind of filtering that disables images on the theme but I can't find out where is that.

# Answer
> 1 votes
I have just found the solution: It was just a permission that wasn't given to the anonymous user.

---
Tags: 6, theming
---


# Question
Title: Different currency per-product in Ubercart
Vanilla ubercart configuration allows a single currency for all products, how can I use a different currency per-product. For example, I want to use USD for books and GBP for electronics, both in display and payment processing.

P.S. I don't think it is a duplicate of Multiple currency displayed in ubercart product page :P

# Answer
There isn't really a good way of dealing with this. One thing you need to figure out is what to do if you have multiple currency in the cart, since ubercart, payment methods etc can't handle this.

If you want an alternative currency for some products, one way of doing that would be to add some options CCK fields which holds the price and currency. Then you could `hook_currency_handler_alter` and `hook_currency_handler_format` to handle how the price should be displayed.

This is no easy task and you need to alter a lot of things to make sure the proper context is available to be able to load the node and figure out how the price should be displayed.

In other words, it's a real pain in ubercart and there isn't a good way of doing this really. The above is probably the best solution though.
> 2 votes

---
Tags: 6, ubercart
---


# Question
Title: Programmatically set the number of Multiple Value CCK fields in node edit form
I have a filefield multi-value CCK field and I want to be able to set the number of values that can be added based on some condition when the user is editing the existing node. Is there a way to handle this through a form\_alter? I do not want to set the number of values to "unlimited" for this case.

# Answer
> 0 votes
Use template.php and override the form functions and apply your logic there before rendering the form. Example override function

```
/* Overiding the question creation form */

function yourthemename_question_node_form($form) {
//  dsm($form);
  // Modify title text
  unset($form['title']['#title']);
  // Set a default value for the title field
    // Set a default value for the title field
  $title_value =   $form['title']['#value'];
  if($title_value ==''){
  $form['title']['#value'] = t('Enter Title Here');
}
  else { }
  $form['title']['#attributes'] = array(
       'onblur' => "if (this.value == '') {this.value = '".$form['title']['#value']."';} this.style.color = '#333333';",
         'onfocus' => "if (this.value == '".$form['title']['#value']."') {this.value = '';} this.style.color = '#333333';" );
  $title = drupal_render($form['title']);
  $body = drupal_render($form['body_field']['body']);
  $form['body_field']['format']['#collapsed'] = FALSE;
  $form['body_field']['format']['#collapsible'] = FALSE;
  $form['body_field']['format']['#title'] = NULL;
  $body_filter = drupal_render($form['body_field']['format']);
  $tags = drupal_render($form['taxonomy']['tags']);
  $thematic_areas = drupal_render($form['taxonomy']['47']);
  $buttons = drupal_render($form['buttons']);
  $remaining_form = drupal_render($form);
    return '<table><tbody style="border:none;"><tr><td style="width:73%;"><div id="form-title">'.$title.'</div>'.'<div id="form-body">'.$body.'<div id="body-format">'.$body_filter.'</div></div><span style="display:none";>'.$remaining_form.'</span>'.'</td><td style="vertical-align:top;">'.$thematic_areas.$tags.'<div id="publish-post">'.$buttons.'</div>'."</td></tr></tbody></table>";
}

```

# Answer
> 0 votes
You can use something like the following, this always shows 10 fields but can easily be adapted.

```
function MYMODULE_form_alter(&$form, $form_values, $form_id) {
  if (isset($form['#node']) && isset($form['type']['#value']) && $form_id == $form['type']['#value'] .'_node_form') {
    $field_name = 'MYFIELD';
    $startid = 0;
    foreach ($form[$field_name] as $k => $v) {
      if (isset($form[$field_name][$k]['#field_name'])) {
        $startid = $k > $startid ? $k : $startid;
      }
    }
    if ($startid <= 9) {
      $form[$field_name][$startid]['_weight']['#delta'] = 10;
      for ($i = $startid; $i <= 9; $i++) {
        $form[$field_name][$i] = $form[$field_name][$startid];
        $form[$field_name][$i]['#weight'] = $i;
        $form[$field_name][$i]['_weight']['#default_value'] = $i;
      }
    }
  }
}

```

---
Tags: entities, 6
---


title: Features module working confusion

text:
# Question
Title: Features module working confusion
I want to use features module. Can i use this module as stand alone and get it working or do i need help of modules like strongarm or context module. Will have have any added advantage if i user these modules along with features module ? Any good flow chart of how to use features module?

# Answer
> 1 votes
Features Module can help you export nodes, content types and almost any kind of entity. But if you want to export things like a settings value (eg: login settings) then you need strongarm to export these variables.

# Answer
> 1 votes
You can use Features without additional modules. In fact, the module page is quite clear about it. Quote:

```
Features also provides faux-exportable functionality for the
following Drupal core and contrib components:
- CCK fields
- CCK fieldgroups
- Content types
- Input filters
- User roles/permissions
- Custom menus and menu links *
- Taxonomy vocabularies *

  * Currently in development.

```

In other words, these things can be exported using features out-of-the-box. That said, I recommend installing Strongarm right away, because some of the things above are lined to variables that you will want to export as well. For instance, if you export a content type, you probably want to export its comment settings too.

---
Tags: 7, features
---


# Question
Title: How to allow user content on the front page?
I am just struggling with my first site and a handful of friends helping to beta test.

Whenever admin posts there is an option to post to front page, but not for others.

I am not sure if I want the users to even see that option -it might confuse the non-techy - but they do want to see their recent stuff on the front page.

How can I do that?

# Answer
For the content type you want to be promoted you need to set the options on that content type to automatically be promoted to front page.

In Drupal7 find this under admin/structure/types pick one of the content types and choose "edit". Under "Publishing Options" choose "Promoted to front page".
> 2 votes

# Answer
The user has to be granted the permission to *Administer content* in order to publish it to the first page. You can find this under *admin/people/permissions* under the node subcategory. Check the box for the respective user.
> 2 votes

# Answer
If you want fine grained control over this options have a look at override\_node\_options
> 1 votes

---
Tags: nodes
---


# Question
Title: Add multiple user-roles in install profile
I would like to create multiple roles with the same permissions in my install profile. To add one user in your install profile, it's quite simple. I use this snippet:

```
    // Make the new role
    $role = new stdClass;
    $role->name = 'User 1';
    $role->weight = 3;
    user_role_save($role);

    // Permissions to assign to the role.
    $perms = array(
    'access content',
    'access content overview',
    );

    // Grant the permissions. This function takes care of all necessary cache resets
    user_role_grant_permissions($role->rid, $perms);

```

I tried with an array, but it didn't work out. Drupal just ignored the array.

**The Array didn't work out...**:

```
    // Make the new role
    $role = new stdClass;
    $roles = array('Eindredacteur 1', 'Eindredacteur 2');
    $role->name = $roles;
    $role->weight = 3;
    user_role_save($role);

    // Permissions to assign to the role.
    $perms = array(
    'access content',
    );

    // Grant the permissions. This function takes care of all necessary cache resets
    user_role_grant_permissions($role->rid, $perms);

```

Anyone who can give me some advice?

# Answer
This should work:

```
// Make the first role
$role = new stdClass;
$role->name = 'Eindredacteur 1';
$role->weight = 3;
user_role_save($role);
$roleid_1 = $role->rid;

// Make the second role
$role = new stdClass;
$role->name = 'Eindredacteur 2';
$role->weight = 3;
user_role_save($role);
$roleid_2 = $role->rid;

// Permissions to assign to the role.
$perms = array(
'access content',
);

// Grant the permissions. This function takes care of all necessary cache resets
user_role_grant_permissions($roleid_1, $perms);
user_role_grant_permissions($roleid_2, $perms);

```
> 2 votes

---
Tags: users, distributions
---


title: Host has switched to fcgi

text:
# Question
Title: Host has switched to fcgi
Our hoster informed us, that he has switched to fcgi. Therefore he had to switch of this part of the .htaccess file and move it to a central part of the server configuration:

```
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

```

Is fcgi ok to host Drupal? Are there any objections against moving this part of .htaccess to an other part of the configuration?

# Answer
> 2 votes
FastCGI should be fine, however...

Your .htaccess may be replaced each time you upgrade Drupal, depending on how you upgrade files. If you do it manually, you need to diff the new one with old one, and determine if there are any changes and merge the changes.

In actually think all of those settings should be the defaults now in the stock PHP php.ini-dist, but I am not positive about the mbstring ones.

It is very probable that your permissions of your files directory (eg, sites/default/files) is messed up. Double check that Drupal can read, write, add, and remove files. The status page should show any problems, but you need to test all cases.

But, one common configuration with FastCGI with shared accounts is that Apache runs as your account user. This would mean that the site files and the files directory would be owned by the same user. This is a security consideration to keep in mind. Preferably, the site files should not have write access by the webserver; write access should be as limited as possible. You can "solve" this be revoking write access from your user account (ie, make files 444 and dirs 555) except for sites/default/files, but this is a major hassle.

If a host did that to me, I would be **EXTREMELY** upset. The provider should have warned you ahead of time so you could prepare, and also given you a test account so you could properly test things out.

Personally, I always recommend true VPS accounts to clients who want to run Drupal. The only time I would consider shared hosting are cases where the provider specializes in shared Drupal hosting.

---
Tags: .htaccess
---


# Question
Title: Display a field from a content type which is not displayed in the current node
I can add new variables to the node (like day, month, year) based on current node-\>created. The problem is I need to display the date field from another content type which is not displayed on the page. How do I fetch it from there?

Here is my code so far:

```
  function mytheme_preprocess_node(&$vars) {
        $node = $vars['node'];
        $vars['year'] = format_date($node->created, 'custom', 'Y' );
        $vars['month'] = format_date($node->created, 'custom', 'm' );
        $vars['day'] = format_date($node->created, 'custom', 'd' );
      }

```

and I display them in node.tpl.php simply printing them as $day, $month, $year. I am interested in finding an answer. Thanks.

# Answer
I think you're looking for the node\_load function. Example:

```
function mytheme_preprocess_node(&$vars) {
  // Load node with ID 123.
  $another_node = $node_load(123);
  // Format a date.
  $vars['another_node_created'] = format_date($another_node->created, 'custom', 'Y, m, d' );
}

```

Beware that node\_load returns raw data from the database. While `$another_node->created` is a safe value to use, user entered data (eg. the title or body text) needs to be checked before you print it (eg. `<?php print check_plain($another_node->title); ?>`). Not checking raw data is a security risk for your site. See Handle text in a secure fashion for more info.
> 2 votes

---
Tags: theming, nodes
---


# Question
Title: How to write a service module for Drupal 7 and Services 3.x?
Can somebody please give instructions on how to write a simple service module for Services 3.x and Drupal 7.x? I simply cannot find any that works with D7. Anything! Just a reworked version of echo\_service module would do!

At the very least please link to a working example. Thanks.

# Answer
> 5 votes
In addition to the link mentioned, here's some code from a module I wrote that uses webservices. Under "structure" the service should be enabled and an endpoint defined. You also set the allowed return types there.

So if you define 'api' as endpoint and want a json array, you would do a request like yoursite.com/api/servicename/arg1/arg2.json. You define the service name in hook\_services\_resources.

```
<?php

// $Id$
/* * **********************************************************************************************
 * @file
 * Based on the RESTful API shell module http://drupal.org/node/1034540
 */

/* * *************************************************************************************************
 * Include necessary files
 */
require_once (drupal_get_path('module', 'graph_data_api') . '/model/highchart_graph.php');

/* * *************************************************************************************************
 * Implementation of hook_help().
 * @see http://api.drupal.org/api/function/hook_help/6
 */

function graph_data_api_help($path, $arg) {
  $msg = t('<p>Provides a API for graph data for use with Highcharts.</p>');
  switch ($path) {
    case 'admin/help#graph_data_api':
      return $msg;
    case 'admin/modules#description':
      return $msg;
  }
}

/* * *************************************************************************************************
 * Implementation of hook_disable()
 * @see http://api.drupal.org/api/function/hook_disable/6
 */

function graph_data_api_disable() {
  cache_clear_all('services:methods', 'cache');
  //eco_debug( '*** graph_data_api_disable() called!' );
}

/* * *************************************************************************************************
 * Implementation of hook_enable()
 * @see http://api.drupal.org/api/function/hook_enable/6
 */

function graph_data_api_enable() {
  cache_clear_all('services:methods', 'cache');
  //eco_debug( '*** graph_data_api_enable() called!' );
}

/* * *************************************************************************************************
 * Implementation of hook_perm().
 * @see http://api.drupal.org/api/function/hook_perm/6
 */

function graph_data_api_permission() {
  return array(
      'request graph data' => array(
          'title' => t('Request graph data'),
          'description' => t('Allows user to use the graph api for Highchart graphs'),
      ),
  );
}

/* * *************************************************************************************************
 * Access callback
 * For now only view/retrieve is implemented and if the user is logged in, he gets access
 */

function _graph_data_api_graphdata_access($op) {
  global $user;
  $access = FALSE;

  switch ($op) {
    case 'view':
      if ($user->uid) {
        $access = TRUE;
      }
      break;
  }

  return $access;
}

/* * *************************************************************************************************
 * Implementation of hook_services_resources().
 * For now only retrieve with a GET request is implemented
 */

function graph_data_api_services_resources() {
  return array(
      'graphdata' => array(
          'retrieve' => array('help' => 'Retrieves graphdata',
              'callback' => '_graph_data_api_graphdata_retrieve',
              'access callback' => '_graph_data_api_graphdata_access',
              'access arguments' => array('view'),
              'access arguments append' => FALSE,
              'args' => array(
                  array('name' => 'parameters',
                      'type' => 'string',
                      'description' => 'The parameters that define requested data',
                      'source' => array('path' => '0'), // first argument in the url
                      'optional' => FALSE,
                  ),
              ),
          ),
      ),
  );
}

/* * *************************************************************************************************
 * Callback for the retrieve resource
 */

function _graph_data_api_graphdata_retrieve($arg) {

  $data = 'hello world';
  return $data;
}

```

---
Tags: 7, services
---


title: Drupal 7 node form processing cleaner

text:
# Question
Title: Drupal 7 node form processing cleaner
Below is an example of adding an additional submit handler to a node form. I don't like how in the submit handler I have a giant nested structure just to check if a file was uploaded...Is there a better way?

```
<?php
function rocdocs_polygons_form_polygons_node_form_alter(&$form, &$form_state, $form_id)
{
    $form['#submit'][] = 'rocdocs_polygons_form_polygons_node_form_submit';
}

function rocdocs_polygons_form_polygons_node_form_submit($form, &$form_state)
{
    if ($form_state['values']['field_shapes_file']['und'][0]['fid'])
    {

    }
}

```

# Answer
If you want to inspect the values of a submitted form, I'm afraid you'll have to dig in to a nested array.

However, if you need to check if a file has been uploaded, why don't you make it a required field? And if you have a reason to write your own check, why don't you add a validation function instead of a submit handler?
> 1 votes

---
Tags: nodes, forms
---


# Question
Title: How to list and store the value of hidden exposed filter of several views for anonymous user?
I need to list vocabulary terms as text links, and then store the choice for anonymous user. Then the exposed filter of several views should get stored value. What is the easiest way to achieve that?

# Answer
The User Alert module may provide a good starting point. It stores a uniqueid for each visitor in a cookie and keeps track of whether an alert has been closed. The logic for this would be similar, but you'll need to wire up the code in your own module to push the views-filter to the cookie and back.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How can I list the current user's posts?
How can I list all posts of the current user? I know I should use Views, but how do I do it?

# Answer
> 2 votes
You can use 'filter by current user' in the Views module.

# Answer
> 1 votes
The core Tracker module does this per user.

---
Tags: 7, views
---


# Question
Title: How to create a list of FULL Nodes without titles (Views)
I would like to create a list of FULL nodes with comments but no titles (with the module Views) is that possible?

Currently I have already a list which shows the FULL node with comments. But also the title which is even an URL.

Can someone explain me how I can do this with Views? If it isn't possible, is it then possible to have the title listed as plain text instead of an URL (duplicated content etc.)?

Using Drupal 6.x

Thanks in advance!

Ps: Just thinking, or should this be done with theming?

# Answer
> 0 votes
If you want to use the **full node** view and get rid of the title I would suggest you doing this with CSS `display:none`.
The method of @iStryker is good but it will just show a list of fields and you'll have to theme them in order to recreate the node view.

# Answer
> 1 votes
To create a view of just comments, Remove the `Node:Title` field (and all other fields), and add `Comment: Body`

To have the node title not a link, uncheck 'Link this field to its node'

# Answer
> 0 votes
exclude\_node\_title is a module for excluding many types of node and is available here for Drupal 6 and Drupal 7:

http://drupal.org/project/exclude\_node\_title

With this module, a checkbox is available for you to uncheck displaying the title.

---
Tags: views, 6
---


title: Moving forum out of the main database

text:
# Question
Title: Moving forum out of the main database
I have a Drupal 6 site with an increasingly bloated forum. I am wondering whether it is possible I can move the forum out of the main site's database to a new database, possibly hosted in a new server.

So I guess my question is a special case of distributing a single Drupal database over several servers.

# Answer
> 1 votes
One option is to have a multidomain setup where forum.yourdomain is your forum installation and www.yourdomain is your main portal. Then you could have a single sign on for both domains.

---
Tags: database, nodes
---


# Question
Title: "user:one-time-login-url" token not getting replaced by token_replace
I'm trying to send e-mails to users manually by using the hook\_mail\_alter hook. The following is my function in its entirety:

```
function custom_module_mail_alter(&$message) {
    $email = '[user:name],

A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at [site:login-url] in the future using:

username: [user:name]
password: Your password

--  [site:name] team';

    $account = $message['params']['account'];
    $uid = $account->uid;

    $_user = user_load($uid);

    dpm(token_replace($email, array('user'=>$_user)));
}

```

The output looks like this:

```
Peter,

A site administrator at Website has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at http://localhost/website/user in the future using:

username: Peter
password: Your password

--  Website team

```

As you can see, things like \[user:name\], \[site:name\], and \[site:login-url\] are properly processed. The only token that isn't processed is \[user:one-time-login-url\]. Any ideas why this is happening?

EDIT: Just for reference, the token *does* get processed in the Welcome e-mails that's sent out by the system automatically, so the token module is active *and* working... It just doesn't seem to get processed when I manually call token\_replace().

# Answer
> 11 votes
To replace that token, you need to call `token_replace()` as `token_replace($email, array('user' => $_user), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE))`.

The function user\_mail\_tokens() is described in the documentation as:

> Token callback to add unsafe tokens for user mails.
>
> This function is used by the token\_replace() call at the end of \_user\_mail\_text() to set up some additional tokens that can be used in email messages generated by user\_mail().

The code used by `_user_mail_text()` to call that callback is the following one.

```
// We do not sanitize the token replacement, since the output of this
// replacement is intended for an e-mail message, not a web browser.
return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE));

```

The Token module is not necessary to replace tokens, in Drupal 7. The code to replace tokens is part of the Drupal 7 core code; the Token module in Drupal 7 defines extra tokens that Drupal core modules don't define.

---
Tags: 7, tokens, emails
---


# Question
Title: Drush site install break when a custom commerce feature is enabled, why?
The D7 site i'm working has a feature that includes two custom product types, amongst other things. A custom feature gets auto-detected and added as a dependency because it contains a rule on one of the product types. Another feature added to the site install profile contains the permissions to those types.

After i exported the features and tried to install the site again, it breaks because:

* the product types are do not get created, i expect this log entry to show but does not:
WD features: Rebuilding feature\_name / commerce\_product\_type
Which, i'm guessing, is when the types get created from the feature. That log entry shows on a successful build (see below).
* consequently, the permissions feature causes a fatal error when trying to insert the types permissions into the db, since they don't exist and not defined by a module (from commerce\_entity\_access\_permissions).

The solution for the fix is to manually remove the auto-detected feature with the rules.

I assumed that there's something wrong with that feature but can't think of what. Has anyone experienced something like that?

# Answer
> 2 votes
It seems to be a problem with Features and how Drush site-install processes. Basically, `features_include()` is called after each feature is enabled during the site install. Somehow (but most likely due to the ordering of the dependencies), the `commerce_features` module gets enabled after my custom feature. As such, `features_include()`, which has already ran and cached its data, skips calling `commerce_features_features_api()`, which is crucial for my custom product types, included in yet another custom feature, to be created.

I opened an issue at http://drupal.org/node/1334438, see for more details and follow-ups.

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


# Question
Title: How to rename the views tabs in user accounts
How do i rename the "view" tab in the user accounts? I want to rename it to Profile. Am using drupal 7 and the zen sub-theme. Any suggestions are welcome.

# Answer
> 2 votes
The Tab Tamer module gives you a user interface to do that.

---
Tags: users
---


title: Add images to blog with ImageField?

text:
# Question
Title: Add images to blog with ImageField?
Using drupal 5.x. I have a content type I created called "Blog Entry" it has no fields other than the standard title and body. Now I want to be able to place images at arbitrary points in the body of the blog entry and have them appear. I already have ImageField and ImageCache installed for use with another content type. Is there a way I can use those two modules to achieve my goal or do I need to install something like the Image module?

# Answer
I found this article which describes one method of doing this. Looks promising not sure if it's the best way. For one I'm not immediately sure how to handle multiple images. How To: Inline Images with ImageField and ImageCache using HTML

**UPDATE**

Yes I can confirm this works. You can use a single ImageField and check the "Multiple values" checkbox when creating the image field to support multiple images. I named my field "blog\_images". Then on the "Display Fields" tab I set the label, teaser, and Full values to all be `"<hidden>"`
> 1 votes

---
Tags: media, nodes, 5
---


# Question
Title: Restrict block to specific pages is broken when using view pagination
I have a block I want displayed on a view page, which has filtering and pagination. The block shows fine when you change the filter, but if you go to page 2 (or any other page than the first), the block disappears. In the block config I have the following under "Only the listed pages":

```
myview
myview/*

```

How do I make it appear on all the pages in the view?

# Answer
It turns out since my block was itself a view, it received the `page` param from the url, and since pagination was turned on, it just went to other pages, which happened to be empty.

I fixed it by turning off pagination on the block view.
> 7 votes

# Answer
use myview\*

the pager will call change the URI to

```
myview?page=2 ...

```

myview\* will cover that case
> 1 votes

---
Tags: views, blocks
---


title: Migrating files with descriptions

text:
# Question
Title: Migrating files with descriptions
I'm currently migrating PDF files into a content type. I would like to know how to populate the file information description field with a more meaningful link (e.g. give a description to each imported file).

```
$arguments = MigrateFileFieldHandler::arguments(drupal_get_path('module', 'my_migrate').'/docs', 'file_copy', FILE_EXISTS_RENAME);

$this->addFieldMapping('field_publication_download', 'files')
  ->arguments($arguments);

```

# Answer
Here is a link that shows all the arguments you can pass to `MigrateFileFieldHandler`. As you can see description is the 7th argument.

If you don't want to specify any of the arguments before `description`, you still have to pass `NULL` to them e.g.:

```
$arguments = MigrateFileFieldHandler::arguments(
  drupal_get_path('module', 'my_migrate').'/docs',
  'file_copy',
  FILE_EXISTS_RENAME,
  NULL,
  NULL,
  NULL,
  array('source_field' => 'migrate_source_description_field'), //Can also pass a string here
);

```
> 1 votes

---
Tags: entities, migrations
---


# Question
Title: Is there a html5 video player for Drupal 6 that run well on ios device?
I need to play videos on my drupal 6 site that would run well on IOS device (HTML5?). Is such solution available?

My site currently serving flv files using jwplayer 6.x-1.1.

# Answer
Yes; try jPlayer: http://drupal.org/project/jplayer

Note that you might be better off implementing this directly (as I did recently) than using the module since the module supports the older version. You will also need m4v files to play video on iOS devices.

I implemented it by following their Quick Start Guide and placing the HTML and JS into my theme, tailored of course to be Drupal-friendly (i.e. using Drupal.behaviors for the JS and using preprocess functions to set file paths properly).

It works well, and my iOS-using client was able to listen to audio (I implemented it for audio) from their iOS device without issues.
> 3 votes

# Answer
Flowplayer has a new version that is supposed to work on iOS, but I haven't tried it yet.
> 3 votes

---
Tags: files, theming
---


title: Why delete old redirects?

text:
# Question
Title: Why delete old redirects?
I have many, MANY redirects (thousands). Most just redirect the system (node/12345) url to the friendly one - but we also have a lot of others.

I have Drupal set to **never** delete old redirects after they haven't been accessed for X amount of time, but the mere presence of the option to do so makes me think there's a legitimate reason I may want to.

Is there a lot of overhead? Or is it simply to keep the list manageable? Do people typically delete them, and if so, what's the time frame? Six months? A year?

# Answer
> 2 votes
Whether to keep redirects is an SEO question. Do you have good search results on Google which you don't want to loose. Or you have external sites or even print stuff that point to your old URLs. Then you have to keep them.

If all this is not true, you can safely delete you old redirects.

About the DB:

The redirects are stored in the url\_alias table. It has two indexes for the mapping from nid to redirect url and from redirect url to nid. This means that reading is fast even if you have thousands of redirects.

If you are creating a lot of redirects this can get slow. But this will not hit you for a few thousand redirects. If you have millions you have to dive into MySql details (or whatever DB system you are using) and find what you can do about it. Since you are only adding records to the DB table, there's a lot of DB tuning stuff that can help you.

# Answer
> 0 votes
Typical you wont have a big problem with that. But it depends on your site size and your server environment. Having less records in your table is always faster than having a more. Example:

Senario 1 : You have 10 redirects in your database. A user must be redirected and drupal executes the database SELECT function. Then after a very short time the database will return the result because it searches only within 10 records.

Senario 2 : You have 9999999 redirects in your database. A user must be redirected and drupal executes the database SELECT function. Your database server must search within 9999999 records and that may take a while. Also it may crash and go out of memory.

**BUT** if your redirect records remains constant then you wont have any problems at all. You can keep the redirects as long as you want.

---
Tags: 7, redirection
---


# Question
Title: Letting users remove webform submissions they've made earlier
I have a website where people can sign up for events. The client now wants the users be able to delete their submission for the event, by entering their email address, displaying a list of events they're attending, and choose which event they want to remove themselves from.

Is there any module that adds this functionality, or is it something that can be done out of the box?

# Answer
Implement sign ups as nodes instead of as webform submissions. Then you can grant the `delete own [node type] nodes` permission to allow users to cancel the sign up.
> 1 votes

# Answer
The webform\_xyz tables let you easily find this information. You can show it in a form and let the user delete his subscription.

However this isn't really secure, since all you need to know is the email address of a person to delete (or just lookup) his subscriptions. This might be no problem for a small, closed user group in an intranet. For a public site you have to identify the users. The easiest way is that they have to become drupal users before they can register and then delete themselves again.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How do I calculate and permanently store a field value with code
I would like to know how I can manually insert some PHP code inside a CCK node.

What I have is the following code for Drupal 6:

```
$output .= '<br>';
$mor = _pitch_detalle($cid, $previamente, $luego);
if (sizeof($mor) > 0) {
  $output .= theme('pitch', $mor);
}
return $output;

```

This code shows some information that changes from day to day, and each time the users view the page, the information changes. I want the user to see an unmodified version of that code, the same information that existed when the user created the page.

As the user cannot edit the page, I´m looking to insert a php snippet inside a CCK field that will remain unchanged. But that could lead to problems, so is there any way to do that in a safe way? Or maybe to insert code inside the template in other way?

# Answer
I haven't done this myself before, so I cannot give really detailed instructions. I think I would do something like this:

* Create a CCK text field in the content type(s) of your choice
* Create a custom module and implement hook\_form\_alter
* In your form alter function:
    + Give your CCK text field a #disabled property and set it to `true` (this will grey out the field so it cannot be edited)
    + Check if the field is already populated; if not, set the #default\_value to the return value of the code in your question

This means that when Drupal builds the form, your custom module will disable the CCK field and put your content in it if that has not been done before. Because we're just populating a form field, all Drupaly stuff like the 'Display Fields' page will keep working.

I hope that helps.
> 2 votes

---
Tags: entities
---


# Question
Title: Where should I put this JavaScript code ... the Drupal way?
I´ve read that you can create a mini module to limit comments length. I´ts cool, and it´s working, but I need to add to it some JS so it tells you how many characters you have left.

So I´ve found some easy thing to do (via Google):

Put this inside your head tag:

```
<script language=”javascript”>
function limit(what,chars,counter) {
if (what.value.length > chars) {
what.value=what.value.substr(0,chars);
alert(‘You exceed to ‘ + chars + ‘chars!’);
}
counting = (chars – what.value.length);
c = document.getElementById(counter);
c.innerHTML = counting;
}
</script>

```

And put this in your body:

```
<label for=”text”><strong>Text</strong></label> ¦ Chars left: <span id=”count1″>500</span></p>
<textarea name=”[1][3][t]” rows=”10″ cols=”50″ onkeyup=”limit(this,500,’count1′);” onkeydown=”limit(this,500,’count1′);” onblur=”limit(this,500,’count1′);” onfocus=”limit(this,500,’count1′);”></textarea>

```

The thing is that I should add that inside the textarea of the comment body. As you can see, the code works, but how do I make it work the Drupal way?

I need only to limit comment length.

Thanks for your help! Rosamunda

# Answer
Why don't you simply use the Maxlength module that does exactly what you want already pre-packaged?

Otherwise, I would either write a custom module and use drupal\_add\_js() and `hook_form_alter()`, or use them in your template.php file without having to write a module.

If you're stumped, and want to know how to do it, why don't you download the Maxlength module and analyse how it is written to clarify the processes involved?
> 1 votes

---
Tags: javascript
---


# Question
Title: Most simple way to integrate a html/jquery block into the system?
i want to build a form with jquery and html without using drupal forms api (looks too complicated for me to put effort on that). How can i do this? How do i have to use a node and how would that be visible? Does anyone know a tutorial for this?

I would appreciate any kinds of hints...

# Answer
> 1 votes
Surely you could just build the HTML form as you normally would, and set the Filter Format to Full HTML (if you're using the WYSIWYG). Seems an odd way of doing things though to be honest!

You could also take a look at the Webform module. That'll allow you to store form submissions easily as well! Or Form Builder, but I've never used it before and it doesn't appear to have a 1.0 release.

On another note, the form API in Drupal is not only REALLY powerful, but actually easier than it looks! It's definitely worth taking time to learn, as you'll find yourself coming back to it again and again!

---
Tags: javascript, theming
---


title: Inject a file record through SQL

text:
# Question
Title: Inject a file record through SQL
I am currently trying to inject a value and file into a user field called "field\_user\_pdf".

I am adding values to the following tables which is successful initally:

```
field_data_field_user_pdf
field_revision_field_user_pdf
file_managed
file_usage

```

The user is then able to see the file on their user profile. The user does not have permission to add/edit the file themselves, only an admin does, using the `field_permissions` module.

However if they edit and save their profile, all record of the file is deleted from the database.

This behaviour does NOT occur if the file was added to the user by an admin in the CMS, it only occurs when the file is inserted in MySQL by circumventing Drupal.

I have come to the above tables by both scrutinizing MySQL Insert logs as well as MySQL Database Dump diffs before and after.

Is there a table or column I am overlooking? Is there any where I can view the SQL Schema for inserting SQL for file fields?

# Answer
What you are doing, sorry, is plain wrong. There is a field API and you should use it instead of messing around with the SQL tables. If you are going around the field API and it breaks, you truly get to keep both parts. I find it astonishing you expect support for going around such a complex API.
> 3 votes

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


title: Trouble with form api

text:
# Question
Title: Trouble with form api
I got a problem to toggle the textfield if the ckeckbox with value 1 is checked.

```
function gkform_nameform() {
 $form['check'] = array
    (
    '#type'            => 'checkboxes',
    '#options'         => array
      (
      1 => 'Sometext',
      2 => 'Sometext2',
      ),
    );
$form['user_name'] = array(
'#type'=>'textfield',
'#states'=>array(
    'visible'=>array(
    ':input[name="check"]'=>array('checked'=> 'options' => '1' == TRUE),
    ),
  ),
 );

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Download')
);
return $form;
}

```

# Answer
> 3 votes
The Form API gives checkboxes names that include their options key. So your `:input` needs to be slightly adjusted to

```
':input[name="check[1]"]' => array('checked' => TRUE),

```

---
Tags: forms
---


# Question
Title: Does module_invoke() work for non core modules?
I tried using `module_invoke('casrel','nodeapi', $node, 'view')`, but what I get for `casrel_nodeapi()` is a truncated `$node` and "load" instead of "view".

Does anybody have an idea on what is happening?

# Answer
You are probably looking for module\_invoke\_all. The module\_invoke function only invokes a module in a specific module (casrel.module in your example).

By the way, you usually do not need to invoke hook\_nodeapi yourself. The node module invokes hook\_nodeapi when necessary, if you just use the api functions (like node\_view) correctly. If you need to alter a node before it's viewed, you need to *implement* hook\_nodeapi instead of invoking it.
> 1 votes

# Answer
> Does `module_invoke()` work for non core modules?

Yes, it does. For `module_invoke()` there isn't a difference between core modules, and third-party modules as the function doesn't verify the module being called is contained in a particular list, and Drupal doesn't have a way to know if a module is a Drupal core one, or not. There are many third-party modules that use `module_invoke()`, and none of them has issues with the function (if it is called with the right parameters).

I agree with marcvangend that you are invoking `hook_nodeapi()` directly when you should be using a function that Drupal make available. Still, if you are having issues with `module_invoke()`, then there is something wrong with your code, or you are not tracing correctly all the calls to the implementation of `hook_nodeapi()` for that module.
For example, when a module implements `hook_nodeapi()`, that hook is called from Drupal code. Are you sure that `casrel_nodeapi('load')` is being called from Drupal core, and it is not what `module_invoke('casrel','nodeapi', $node, 'view')` is causing? Consider that Drupal always invoke `hook_nodeapi('load')` before `hook_nodeapi('view')` because a node is first loaded, and then shown.
> 1 votes

---
Tags: hooks
---


# Question
Title: Publisher and Editor only without publishing rights role possible?
I want to have 2 user roles in the site: one that can create content but not being able to publish and the other just a supervisor that can (aprove-publish)

# Answer
What you want is a workflow, for example "Draft", "Requires Review" and "Published". The Editor can only take content to "requires review" while the publisher has permissions to change the workflow state to Published which is then visible to all users on the site.

http://drupal.org/project/workflow

If you want to get really fancy you could use Rules to automatically email the publisher when content goes into "requires review" so the Publisher gets a notification. or you could setup a view for them...
> 1 votes

---
Tags: users, nodes
---


title: Use views with the Homebox module

text:
# Question
Title: Use views with the Homebox module
Is it possible to use views inside the Homebox module? If so, how?

# Answer
> 3 votes
Yes it is!

You embed blocks into Homebox regions, so just create a block display of your view, and include it into your Homebox on the layout page.

Any disabled blocks will be listed at the bottom, just pick a region for them!

---
Tags: views, 7
---


# Question
Title: Simulating Facebook videos embedding behaviors in Drupal?
If users are posting comments to a Drupal site and the comment contains a link to a video on YouTube or other sites, I would like to see similar behavior to that when posting a link to a video on Facebook. That is, once the link is entered, it triggers the embedding mechanism and generates a preview in edit mode.

# Answer
> 1 votes
The emfield module does that. It's D6 only at the moment.

---
Tags: javascript, social-network
---


# Question
Title: Changing block content based on user input
I need to change the content of a block on the landing page based on user input.
Basically, I have a few links and a search form; if the user clicks on a link, I want the block to display some text, based on which link was clicked, and if the user uses the search form then to display information from an external database.

**Edit** I left this site for a while & now am coming back to it. I thought about it and if it's too hard to do in a module, then I could just make different pages for the texts & link them. And displaying data from the database is trivial.

# Answer
> 1 votes
You should try the Context module.

---
Tags: 7, blocks
---


# Question
Title: How do i use pathauto to create a url alias for nodes' menu local tasks?
The nodes are aliased automatically using the Pathauto module. E.g., `node/448` is displayed as `aliased/path`.

Is it possible to alias `node/448/edit` to `aliased/path/edit`?

# Answer
> 0 votes
The Sub-path URL Aliases module will do this.

# Answer
> 0 votes
It works perfectly for the SubPathAuto module. Just uncheck the `Skip administration paths from sub-path processing` option in `admin/config/search/path/subpaths.`

Delete existing aliases first `admin/config/search/path/delete_bulk` then go to `admin/config/search/path/update_bulk`, check all the options, and click `update.` If required clear cache.

However I realized that this method disables the overlay. But everything else works great.

---
Tags: nodes, routes, path-aliases
---


title: how to overwrite omega 960 grid margin?

text:
# Question
Title: how to overwrite omega 960 grid margin?
What is the correct way to overwrite the Omega theme stylesheet, so that the margin of `.grid-1` is 0 instead of 10px?

I tried to specify this style:

```
.grid-1 {
  margin-left: 0;
  margin-right: 0;
}

```

in two stylesheets: /sites/all/themes/mytheme/css/mytheme-alpha-default-normal.css -\> this one is not loaded at all

/sites/all/themes/mytheme/css/global.css -\> this one is overwritten by alpha-default-normal-12.css

The alpha-default-normal-12.css is always at the top of all loaded stylesheets, so it looks like it can't be overwritten. And it contains the styles for all .grid-x margins.

So, how to specify my own margin for a grid?

# Answer
> 4 votes
The best explanation of how to do a custom grid in Omega I have found is in the Omega documentation wiki: Creating and Setting up a Custom Grid for Omega 3.x. As the Omega documentation matures, I hope this will move into the main documentation.

The basic idea is below (but see the link above for more details):

1. Copy the appropriate `grids` entries from `alpha.info` into `mytheme.info`. There will be no `grids` entries initially in your `mytheme.info` if you have created a subtheme in the normal way. You will be copying various `grids[alpha_default]` entries. Then edit those entries to be `grids[mytheme_default]`.
2. Generate a new CSS grid file at http://grids.heroku.com/ or http://www.spry-soft.com/grids/. Just use this as a model for the next step, as it does not correspond exactly to the way Omega CSS grid files are written. The class naming conventions are a little different ("\_" vs "-", for instance.
3. Copy the css and png files you need from `sites/all/themes/omega/alpha/css/grid/alpha_default/{normal,wide,narrow,..}/alpha-default-*-*.{css,png}`. to `sites/all/themes/mythemes/css/grid/mytheme_default/{normal,wide,narrow,..}/mytheme-default-*-*.{css,png}`. You will not need all the files unless you are planning to provide a complete set of narrow, normal, and wide 12 and 16-column grids. Just put in the ones you need.
4. If you are changing the default number of columns from 12, don't forget to edit the number-of-column defaults for all the different regions given further down in `mytheme.info`. Otherwise your pages will look wrong because they are using the original default settings.
5. Note you must *also* rename the `mytheme/css/mytheme-alpha-default.css` and `mytheme/css/mytheme-alpha-default-{narrow,normal,wide}.css` files to `mytheme/css/mytheme-mytheme-default*.css`. This is because you have changed the `alpha-default` grids name to `mytheme-default`.

I did all this recently for a design I was given that was 960px wide with no left and right margins. I set up a 60px by 16-column 960px grid.

The Omega Tools module has an incomplete wizard for setting up your own custom grid. Unfortunately, it does very little of the above as of this writing.

---
Tags: theming
---


# Question
Title: Injecting database values with a non-Drupal application
I have a D7 site which I would like to allow a non-drupal application to be able to inject values into the database. Specifically, I would like to upload a file to a specific field and then associated that field entry with a predetermined user.

The external program is not running PHP either, so it's intended to be an entirely SQL based approach, and not touch Drupal code at all.

Is there a recommended or useful approach to this, for a way to extract the Schema from Drupal, or a CMS-agnostic method of tracking database updates / inserts?

Thanks!

# Answer
One method would be to use the Services module to create a web service that the external program could then communicate with.
> 3 votes

---
Tags: 7, database
---


# Question
Title: How to override 'views-slideshow-pager-fields.tpl.php'?
I'm taking over one of my co-workers project (i'm new to Drupal...).

I was able to override other view templates such as 'views-view--\[my content type\].tpl.php', 'views-view-fields--\[my content type.tpl.php', but I wasn't able to override 'views-slideshow-pager-fields.tpl.php'.

What naming convention should I use to override the file?

# Answer
Views Slideshow is a separate module. This video from MustardseedMedia addresses theming for the module. I have not watched it yet, let us know if it addresses your needs.
> 1 votes

---
Tags: paging
---


# Question
Title: Multiple separate forms for searching up different apache solr indexes
Mac\_Weber in IRC gave me some great info in relation to this earlier, but I have a more indepth question: is it possible to have multiple separate forms for searching up different apache solr indexes? Say for example I had a separate indexes on rock stars, countries, and organic food suppliers. I want a drupal website that has literaly separate pages with a search box to search upon these indexes.

# Answer
The the Search API is perfect for the job. This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine (including Solr). You can create multiple indexes with their own individual search pages/blocks and have granular control over what fields are searched and the relevancy.
> 3 votes

---
Tags: 7, search
---


# Question
Title: Link pages from a child term to it's parent
I have really two questions in one. I have pathauto make a page for all my terms. I have something like this:

```
USA
-NY
-NJ
-LA
UK
-London
-Hogwarts
-Manchester
France
-Paris
...

```

Anyway pathauto made pages for all the terms, so I have `site/USA` , `site/USA/NY` etc. I want to make it so that `site/USA/NY` has a link to it's parent which is `site/USA`. Is there any way to do this?

Another question, I'm also using the hierarchical select plugin to make a user select the deepest child possible (in this case just one level in). When a user tags content with NY, I also want that content to be tagged with USA, is that possible?

# Answer
> 0 votes
Node will have relation with the child term but there is no direct relation between the node and parent term.
So i think there are two ways to do it..
**ONE** : use node api and attached the parent term with the node.
**TWO** : while displaying the node fetch the parent term of the term and show them as well.

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


# Question
Title: Need help on a callback function with login form
When a user tries to log into my drupal website, I want to check an external database to see if he is registered there. If he is registered in the external db, an account will be created on Drupal when he logs into Drupal for the first time. This is what I currently have to modify the login form to check the second database and create a drupal account for the user if necessary

```
function converge_form_alter(&$form, &$form_state, $form_id)  {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['#submit'][] = 'converge_convergeAuthenticate';
  }
}

```

However, this callback function only gets called on a successful login in Drupal. How can I get the system to run the callback function even if the users password and username are incorrect (and create local account if the incorrect password matches external database)?

I also tried the following code to get the custom function called first but it's not working.

```
 if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    array_unshift($form['#submit'], 'converge_convergeAuthenticate');
  }

```

# Answer
```
function da_form_alter (&$form, $form_state, $form_id) {
   if ($form_id == 'user_login' || $form_id == 'user_login_block' ) {
     if (isset($form_state['post']['name'])) {
       $form['#validate'][] = da_login_validate($form, $form_state);
    }
  }
}

function da_login_validate($form, $form_state) {
  // Here you should check wheather the user is valid or not..
}

```

Better way to do this: you should read the source code of any module. For example, read the code of Facebook Connect which does the same thing.
> 2 votes

---
Tags: 6, hooks, users
---


# Question
Title: D7: $node->created property not available in mytheme_preprocess_block(&$variables) function?
Hello I need to insert a formated date in a block template: block--delta-blocks--page-title.tpl.php

As I think this can be done using a preprocess function to set the $day, $month, $year variables:

```
function cybele_preprocess_block(&$variables) {
    $variables['day'] = format_date($node->created, 'custom', 'd' );
  }

```

But it seems $node-\>created is not visible here. It works if I place it in:

```
function mytheme_preprocess_node(&$vars) {
    $node = $vars['node'];
    $vars['year'] = format_date($node->created, 'custom', 'Y' );
    $vars['month'] = format_date($node->created, 'custom', 'm' );
    $vars['day'] = format_date($node->created, 'custom', 'd' );

}

```

but not in \_preprocess\_block function. Can someone help me do that? Probably I need to declare in mytheme\_preprocess\_page but the block template won't see from there either.

# Answer
> 2 votes
The important difference between the two code examples you're giving, is `$node = $vars['node'];`. You can only use the variables that are available inside the function you're writing. If you declare a function `cybele_preprocess_block(&$variables)`, then the only variable you start with is $variables. In other words: inside that function, $node doesn't exist yet!

Sometimes, the current node is stored in the $variables array, so if it's in there, we can take it out again. That's what the line `$node = $vars['node'];` does: it creates a new variable $node and populates it with the value of $variables\['node'\]. You do not have to put the node in a separate variable; you can also do this:

```
function mytheme_preprocess_node(&$variables) {
  $variables['day'] = format_date($variables['node']->created, 'custom', 'd' );
}

```

If the node is *not* available inside $variables (which I think is the case in \_preprocess\_block) you will have to load the current node. Fortunately that's rather easy in Drupal 7, because you can use menu\_get\_object. This will only work when viewing a node page.

```
function mytheme_preprocess_block(&$variables) {
  $node = menu_get_object();
  $variables['day'] = format_date($node->created, 'custom', 'd' );
}

```

---
Tags: blocks, datetime, theming
---


# Question
Title: How to execute custom code on user signup
I need to do a REST request every time a new user signs up.

The REST request returns some data that I need to store for the Drupal user account, and be able to present as content somewhere.

What is the best/cleanest way to do that?

# Answer
> 1 votes
You can do it in a simple custom module, be sure to first understand Drupal hooks system as this is the base for (almost) everything Drupal.

In your module, you can implement `hook_user_presave()` to be called before a user account is saved. It will be called for both creation and update, so you will need to guard your code with a condition to detect new user. After the REST call, there is several option to store the returned data. The easiest one is the use the data attribute of the user account. It is a simple PHP array that will be serialized in a database columns. It is not very good performande wise and not very flexible (you can query the stored data) but it is easy.

```
function MODULE_user_presave(&$edit, $account, $category) {
  // Accoding to user_save's documentation, this is a new user if
  // $account->is_new is set to TRUE or if $account->uid is not set
  if ($category == 'account' && (!empty($account->is_new) || !isset($account->uid)))) {
    $edit['data']['MODULE'] = MODULE_get_data_from_rest($account);
  }
}

```

# Answer
> -1 votes
The Rules or Workflow modules may be what you are looking for.

# Answer
> -1 votes
A core feature in Drupal 7 is available that can trigger a specific action if a user is created, etc. You don't have to code to achieve this:

* Enable the module **Triggers**
* Go to **Configuration** \>\> **Actions** and create an action available on the dropdown list
* Go to **Structure** \>\> **Triggers**, click on the **User** tab and assign the action you created awhile back to **Trigger: After creating a new user account**

---
Tags: users, 8
---


# Question
Title: Is there a Drupal 6 equivalent to template_preprocess_taxonomy_term()?
Is there a Drupal 6 equivalent to the method template\_preprocess\_taxonomy\_term()? I'm looking to add some code that will provide some additional links on my taxonomy term pages and want to keep the code in template.php (don't like code in my templates themselves).

# Answer
Managed to eventually figure this out myself. I'm using the following in template.php to identify a taxonomy term page in D6:-

```
<?php
function THEME_preprocess_page(&$vars) {
  if (arg(0)=='taxonomy' && arg(1)=='term') {
    // do something
  }
}
?>

```
> 2 votes

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


title: How can I theme a module in Drupal 7?

text:
# Question
Title: How can I theme a module in Drupal 7?
I'm new to developing in Drupal and am trying to create my first module. I've got it all set up, but I don't know how to add the theme to it. Right now it just shows a blank page with only the text "Hello World".

```
   <?php
function news_main() {
    require_once('/global_applications/news/home.php');
}

function news_menu() {
    $items = array();

    $items['news'] = array(
        'page callback' => 'news_main',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
     );

    return $items;
}
?>

```

# Answer
Your function `news_main()` should return a string to be displayed in the content area of your selected theme, and the file you're including shouldn't display anything (e.g. echo, print).
> 1 votes

# Answer
You are seeing a page containing just that string because the code you are using is printing the string, and then it exits. This means the theming system used by Drupal is not used to render the page, which will just contain the echoed text.

If you want to theme a page, the page callback needs to return HTML content, as in Drupal 6, or an array that contains the same elements used for the array passed to drupal\_render().

As example of page callback, you can look at node\_add\_page():

```
function node_add_page() {
  $item = menu_get_item();
  $content = system_admin_menu_block($item);
  // Bypass the node/add listing if only one content type is available.
  if (count($content) == 1) {
    $item = array_shift($content);
    drupal_goto($item['href']);
  }
  return theme('node_add_list', array('content' => $content));
}

```

An example of page callback that returns an array is node\_page\_default(), which contains the following code:

```
function node_page_default() {
  $select = db_select('node', 'n')
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('promote', 1)
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->extend('PagerDefault')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access');

  $nids = $select->execute()->fetchCol();

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build = node_view_multiple($nodes);

    // 'rss.xml' is a path, not a file, registered in node_menu().
    drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
    drupal_set_title('');
  }
  else {
    drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);

    $default_message = '<p>' . t('No front page content has been created yet.') . '</p>';

    $default_links = array();
    if (_node_add_access()) {
      $default_links[] = l(t('Add new content'), 'node/add');
    }
    if (!empty($default_links)) {
      $default_message .= theme('item_list', array('items' => $default_links));
    }

    $build['default_message'] = array(
      '#markup' => $default_message,
      '#prefix' => '<div id="first-time">',
      '#suffix' => '</div>',
    );
  }
  return $build;
}

```

You first task is then to incorporate the code there is in the /global\_applications/news/home.php file into `news_main()`, and change it to either return HTML content, or an array as required by `drupal_render()`. The latter is preferred as it allows other modules to alter the output of the page callback.

Keep in mind that if you need to render a form, you should use the form API, which means that the page callback should be "drupal\_get\_form," in that case; the first argument passed in "page arguments" is the form ID for the form to render.
> 2 votes

---
Tags: theming
---


# Question
Title: Wrong order of entities, how to change that?
I've created my first module which shows a list with nodes containing a certain term (like a taxonomy list, like usual), but the entities gets listed in an unknown way - I'm new to this and don't know - and I want them to be listed in alphabetical order.

How do I change that?

Code to retrive and print the entities:

```
function mymodule_cmp($a, $b) {
  $a = (array) $a;
  $b = (array) $b;
  return strcmp($a['name'], $b['name']);

}

$terms = taxonomy_get_tree(10,0,1);

usort($terms, "mymodule_cmp");

$counter = 0;

$result = taxonomy_select_nodes($tid, FALSE);

foreach($result as $nid) {

    $node = node_load($nid);

            // Prints all that is needed.
    }

```

# Answer
Take a look at the Drupal API taxonomy\_select\_nodes(). You are missing the `$order` argument.

```
taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'));

```
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Get "Raw" views data (with no or little markup)
One thing i hate about views is this bunch of markup and nesting it uses to render the data on a page.

What i usually do to remedy this problem is iterate through the content variable and trim all tags so i can them display it as i wish. I know this kind of a dirty shortcut and i was wondering if there was a better way to do so.

Can' t views only output the raw data from the DB without adding all that markup to it ?

# Answer
> 2 votes
Are you using Views 6.x-3.x or 7.x-3.x? If so, you can do a ton of the grunt work of stripping out views' default markup by adjusting fields' 'Style settings'. If you're using an older version of Views, Semantic Views does just about the same thing. One gotcha: If you don't want the default  wrapper around each field, you need to check the 'configure the field and label wrapper' option and set it to 'None' - that trips me up sometimes.

To adjust the other bits of markup around, for example, the entire view, or each row, you can copy the views template files (in the `views/theme` folder) into your theme's folder, and modify them to your heart's content.

The reason Views creates all this extraneous markup is that it is trying to be all things for everyone. I find, a lot of times, that it's easiest (and barely helps performance or page load times) to just go with the default markup, unless I'm trying to do some advanced theming. There's a class for just about everything!

On another note – if you're trying to return just some data, in a format like JSON or XML or something similar, you'll want to use a different display type for views besides one of the standard 'Unformatted fields' or 'list' types...

# Answer
> 1 votes
The easiest way to accomplish this is:

1. Exclude the fields from displaying.
2. Add a field and choose "REWRITE RESULTS" to rewrite it with the fields that you want (from replacement patterns). You can add markup around the tokens if you want.
3. Uncheck "Provide default field wrapper elements" from show settings.

# Answer
> 1 votes
A combination of Views 3 and the Semantic Views module is usually enough for me.

Under extreme circumstances, when I want absolutely *zero* markup, e.g. to display a completely custom date, I create my own tiny template for the field in question (choosing the right file to create using the Theme Information part of the View). In your template, the default is `print $output;`, which is completely useless. For my date example, i replaced that with:

```
print my_pretty_date($row->{$field->aliases['field_date_value']},
  $row->{$field->aliases['field_date_value2']}
);

```

That will let me run my custom date formatting function with dates in MySQL datetime format.

IMPORTANT: I don't know if the `$row` data are sanitized. It is hard to find out too.

---
Tags: 7, views
---


title: Import a view during installation

text:
# Question
Title: Import a view during installation
I want to import a view during the installation of Drupal.

Does anybody have an idea on how to do this?

# Answer
> 0 votes
Yes, You can do this by using the Features Module

# Answer
> 2 votes
You don't usually programmability import views, instead you provides default ones by implementing `hook_views_api()` (usually in `MODULE.module`) and `hook_views_default_views()` (usually in `MODULE.views_default.inc`). Your module should return an array of views object has build with the code provided by the *export views* UI:

```
/**
 * Implementation of hook_views_api().
 */
function MODULE_views_api() {
  return array(
    'api' => '3.0',
  );
}

/**
 * Implements hook_views_default_views().
 */
function MODULE_views_default_views() {
  $export = array();

  $view = new view;
  $view->name = 'foo';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Foo';

  [ ... ]

  $export['foo'] = $view;

  return $export;
}

```

The Features module can generate the code for this.

# Answer
> 0 votes
If you have drush you can probably create a drush make file that specifies your features module should be included.

---
Tags: views
---